Skip to content

Features for machine learning

Module: crashmetrics.features.

A model is only as good as its training table. crashmetrics.features turns every run into one row of numbers: the injury criteria as targets or labels, the shape of each signal as features, and the design parameters alongside. Because every run goes through the same, protocol -correct calculation, test and CAE rows are consistent with each other.

Only NumPy is needed. pandas is used by to_dataframe if it is installed; any ML library (scikit-learn, XGBoost, PyTorch) takes the output of to_matrix directly.

Step 1: features of one signal

signal_features describes the shape of any channel: an acceleration, a force, a deflection, a moment.

from crashmetrics.features import signal_features

f = signal_features(t, chest_deflection, prefix="chest_")
f["chest_peak_abs"], f["chest_rise_ms"], f["chest_width50_ms"]
Feature Meaning
max, min, peak_abs Largest, smallest and largest absolute value
t_max_ms, t_min_ms, t_peak_abs_ms When they occur, ms from the first sample
mean, rms, std Time-averaged level and spread over the record
integral, abs_integral Area under the signal (for an acceleration in m/s² this is the velocity change)
onset_ms, end_ms, active_ms First and last time above 5 % of the peak, and the time between
rise_ms 10 % to 90 % rise time before the peak
width50_ms Total time above half the peak
excursions50 Separate excursions above half the peak: 1 for a single pulse, 2 or more for multiple impacts (for example bottoming out)
centroid_ms, energy50_ms Time centroid of the signal energy, and when half of it has accumulated (early or late loading)
dominant_hz, spectral_centroid_hz Strongest frequency and power-weighted mean frequency

Timing and width features use the magnitude, so they do not depend on the channel's sign convention. A feature that cannot be defined (the rise time of an all-zero channel) is nan, and every call returns the same columns in the same order.

Filter first

Pass filtered channels (CFC 1000 for head accelerations, CFC 180 or 60 for pulses and so on). Raw noise inflates the peak, rise and frequency features.

Step 2: criteria plus shape for a load case

The load-case extractors combine the criteria with the shape features:

from crashmetrics.features import head_features, pulse_features

head_features(t, a_resultant_g)
# {'head_hic15': 654.1, 'head_hic15_t1_ms': 6.65, 'head_hic15_t2_ms': 13.35,
#  'head_hic36': ..., 'head_a3ms': 106.9, 'head_peak_g': 120.0,
#  'head_t_peak_ms': 10.0, 'head_colour': 'yellow', 'head_rise_ms': ..., ...}

pulse_features(t, accel_x_ms2, v0=50 / 3.6)
# {'pulse_olc_g': ..., 'pulse_delta_v': ..., 'pulse_restitution': ...,
#  'pulse_max_crush_mm': ..., 'pulse_peak_decel_g': ..., 'pulse_rise_ms': ...}
  • head_colour is the Euro NCAP headform colour of HIC15, a ready-made label for classification models.
  • head_hic36 is nan if the record is shorter than 36 ms (no warning per run).
  • For any other criterion, put its result object in the row: flatten (next step) turns it into columns.

Step 3: any result object as columns

flatten turns a result, however nested, into a flat dict:

from crashmetrics.features import flatten

flatten(nij(t, fz, my, fx=fx), prefix="nij.")
# {'nij.value': 0.36, 'nij.category': 'NTE', ...}

flatten(score_mpdb(...))     # about 350 columns, for example
# 'points', 'occupants.driver.points',
# 'occupants.driver.regions.head_neck.points',
# 'occupants.driver.regions.head_neck.band', ...

Dataclasses and dicts are walked recursively, short tuples get index keys, and NumPy arrays (time histories) are left out, so every value is a single number, string, bool or None.

Step 4: one row per run

feature_table runs your extractor on every run:

from crashmetrics.features import feature_table, head_features
from crashmetrics.signals import cfc_filter, resultant


def extract(folder):
    t, ax, ay, az = load_headform(folder)          # your loader
    a = resultant(*(cfc_filter(t, c, cfc=1000) for c in (ax, ay, az)))
    return head_features(t, a)


runs = {p.name: p for p in sorted(Path("doe").iterdir())}
params = {"run01": {"thickness": 0.7, "clearance_mm": 65}, ...}
rows = feature_table(runs, extract, params=params)
  • runs is a dict {name: input} or a list of (name, input) pairs; the input is whatever your extractor takes (a folder, a file, arrays). For LS-DYNA run folders, load_headform can be the read_nodout loader in Loading your data, and read_run(folder) gives contact, section, belt and airbag channels for more features (LS-DYNA ASCII output).
  • params adds the design parameters to each row, so the table is directly a training set.
  • The extractor may return a dict, a result object or a list of them (for example head, neck and chest features of the same run).
  • A run that raises an exception does not stop the batch: its row gets an error column ("ValueError: signal must contain only finite values."). Use on_error="raise" while developing the extractor.

Step 5: to CSV, pandas or a model

from crashmetrics.features import to_dataframe, to_matrix, write_csv

write_csv(rows, "features.csv")             # all columns, missing cells empty

df = to_dataframe(rows)                     # needs pandas
df[df.error.isna()].describe()

names, X = to_matrix([r for r in rows if "error" not in r])
y = X[:, names.index("head_hic15")]

to_matrix keeps the numeric columns (bools as 0/1, missing values as nan), or the columns you name, in that order. Then, for example with scikit-learn:

from sklearn.ensemble import RandomForestRegressor

inputs = ["thickness", "clearance_mm", "speed_kph"]
_, X = to_matrix(good_rows, inputs)
model = RandomForestRegressor().fit(X, y)

Next: designs, targets and sensitivity

DOE, sensitivity and probabilistic ratings adds design-of-experiments sampling, margins to the limits as continuous targets (crashmetrics.margins.margin_features fits straight into a feature row), sensitivity ranking and Monte Carlo star ratings.

Good practice for crash training data

  1. Remove failed and suspicious runs before training. Check the error column, and the LS-DYNA energy checks and termination status (LS-DYNA energy checks) for CAE runs.
  2. Keep targets out of the inputs. If you predict HIC15, do not train on HIC36, the 3 ms clip or the peak of the same signal: they are other views of the target.
  3. Hold out runs (or whole design variants) to check a model. With few runs, a physically shaped model (for example a power law in log space, as in the example) usually beats a flexible one.
  4. Same pipeline for test and CAE. Filter classes, units and time zero must match, otherwise the model learns the difference between the sources.

Complete example

Sixteen headform runs over stiffness, clearance and speed, plus one broken run. The script builds the feature table, writes it to CSV, looks at the labels and correlations, and fits a surrogate checked on held-out runs:

"""Example 11: an ML-ready feature table from many runs.

Sixteen headform runs over bonnet stiffness, under-bonnet clearance and
impact speed (synthetic data). `feature_table` runs one extractor per
run, joins the design parameters, records a failing run instead of
stopping, and the table goes to CSV, pandas or a NumPy matrix for a
model.
"""

from itertools import product

import numpy as np

from crashmetrics.features import (
    feature_table,
    flatten,
    head_features,
    to_matrix,
    write_csv,
)
from crashmetrics.signals import cfc_filter, resultant

t = np.arange(0.0, 0.04, 2e-5)                          # s, 50 kHz
rng = np.random.default_rng(11)


def simulate(stiffness, clearance_mm, speed_kph):
    """Toy headform model: x and z accelerations in g."""
    duration = 0.012 / np.sqrt(stiffness)
    scale = (speed_kph / 40.0) ** 2
    a = 95.0 * stiffness * scale * np.where(
        t < duration, np.sin(np.pi * t / duration), 0.0)
    if clearance_mm < 70.0:                             # second hit on the engine
        hit = np.clip((t - 0.6 * duration) / 0.002, 0.0, 1.0)
        a = a + (70.0 - clearance_mm) * 6.0 * scale * np.sin(np.pi * hit)
    a = a + rng.normal(0.0, 2.0, t.size)                # sensor noise
    return 0.9 * a, 0.436 * a


# --- 1. The runs and their design parameters ----------------------------------
runs, params = {}, {}
levels = product([0.8, 1.0, 1.2, 1.4], [50.0, 80.0], [35.0, 40.0])
for i, (stiffness, clearance, speed) in enumerate(levels, start=1):
    name = f"run{i:02d}"
    runs[name] = simulate(stiffness, clearance, speed)
    params[name] = {"stiffness": stiffness, "clearance_mm": clearance,
                    "speed_kph": speed}
runs["run17"] = (np.full(t.size, np.nan), np.zeros(t.size))   # a broken channel
params["run17"] = {"stiffness": 1.0, "clearance_mm": 80.0, "speed_kph": 40.0}


# --- 2. One extractor for one run: filter, resultant, features ---------------
def extract(channels):
    ax, az = channels
    a = resultant(cfc_filter(t, ax, cfc=1000), cfc_filter(t, az, cfc=1000))
    return head_features(t, a)


rows = feature_table(runs, extract, params=params)
columns = write_csv(rows, "crashmetrics_features.csv")
print(f"{len(rows)} runs x {len(columns)} columns -> crashmetrics_features.csv")
print("Columns:", ", ".join(columns[:7]), "...", ", ".join(columns[-3:]))
print("Failed  :", [(r["run"], r["error"]) for r in rows if "error" in r])

# --- 3. A quick look at the table ---------------------------------------------
print(f"\n{'run':6} {'stiff':>5} {'clear':>5} {'kph':>4} {'HIC15':>6} "
      f"{'rise ms':>7} {'width ms':>8} {'centroid':>8}  colour")
good = [r for r in rows if "error" not in r]
for r in good[::3]:
    print(f"{r['run']:6} {r['stiffness']:5.1f} {r['clearance_mm']:5.0f} "
          f"{r['speed_kph']:4.0f} {r['head_hic15']:6.0f} {r['head_rise_ms']:7.2f} "
          f"{r['head_width50_ms']:8.2f} {r['head_centroid_ms']:8.2f}  "
          f"{r['head_colour']}")
labels = [r["head_colour"] for r in good]
print("Colour counts:", {c: labels.count(c) for c in sorted(set(labels))})

# --- 4. Which signal features go with HIC15? ---------------------------------
names, x = to_matrix(good)
y = x[:, names.index("head_hic15")]
criteria = ("head_hic", "head_a3ms", "head_peak_g")    # criteria, not shape
amplitude = ("head_mean", "head_rms", "head_std", "head_integral",
             "head_abs_integral", "head_min")
shape = [n for n in names if n.startswith("head_")
         and not n.startswith(criteria) and n not in amplitude]
corr = {n: np.corrcoef(x[:, names.index(n)], y)[0, 1] for n in shape
        if np.std(x[:, names.index(n)]) > 0}
top = sorted(corr.items(), key=lambda item: -abs(item[1]))[:4]
print("\nStrongest shape features vs HIC15:",
      ", ".join(f"{n} {c:+.2f}" for n, c in top))

# --- 5. A surrogate from the design parameters, checked on held-out runs ------
# HIC grows roughly as acceleration^2.5, so fit log(HIC) (a power law);
# with acceleration ~ speed^2 the speed exponent should come out near 5.
design = ["stiffness", "clearance_mm", "speed_kph"]
_, xd = to_matrix(good, design)
features = np.column_stack(
    [np.ones(len(y)), np.log(xd[:, 0]), xd[:, 1], np.log(xd[:, 2])])
test = np.arange(len(y)) % 4 == 0                       # every 4th run held out
coef, *_ = np.linalg.lstsq(features[~test], np.log(y[~test]), rcond=None)
pred = np.exp(features[test] @ coef)
r2 = 1 - np.sum((y[test] - pred) ** 2) / np.sum((y[test] - y[test].mean()) ** 2)
print(f"Surrogate log(HIC15) ~ log(stiffness) + clearance + log(speed): "
      f"exponents {coef[1]:.2f} (stiffness), {coef[3]:.2f} (speed)")
print(f"Checked on {int(test.sum())} held-out runs: R^2 = {r2:.2f}, "
      f"mean error {np.mean(np.abs(y[test] - pred)):.0f} HIC")

# --- 6. Any result object becomes columns with flatten() ---------------------
print("\nflatten(features of run01) has", len(flatten(rows[0])), "columns;",
      "nested scores give keys like 'occupants.driver.regions.head_neck.points'")

# With pandas:
#   from crashmetrics.features import to_dataframe
#   df = to_dataframe(rows)
#   df.groupby("head_colour").mean(numeric_only=True)

Output:

17 runs x 30 columns -> crashmetrics_features.csv
Columns: run, stiffness, clearance_mm, speed_kph, head_hic15, head_hic15_t1_ms, head_hic15_t2_ms ... head_dominant_hz, head_spectral_centroid_hz, error
Failed  : [('run17', 'ValueError: signal must contain only finite values.')]

run    stiff clear  kph  HIC15 rise ms width ms centroid  colour
run01    0.8    50   35    274    7.63     1.69     7.80  green
run04    0.8    80   40    281    4.47     8.93     6.72  green
run07    1.0    80   35    224    4.01     8.00     6.01  green
run10    1.2    50   40   1067    6.48     4.23     6.25  orange
run13    1.4    50   35    714    6.05     4.60     5.76  yellow
run16    1.4    80   40    856    3.36     6.72     5.08  yellow
Colour counts: {'brown': 1, 'green': 11, 'orange': 1, 'yellow': 3}

Strongest shape features vs HIC15: head_width50_ms -0.31, head_active_ms -0.30, head_end_ms -0.30, head_centroid_ms -0.29
Surrogate log(HIC15) ~ log(stiffness) + clearance + log(speed): exponents 1.90 (stiffness), 5.02 (speed)
Checked on 4 held-out runs: R^2 = 0.99, mean error 16 HIC

flatten(features of run01) has 29 columns; nested scores give keys like 'occupants.driver.regions.head_neck.points'

The fitted speed exponent comes out near 5. That is what physics expects: acceleration grows with speed squared and HIC with acceleration to the power 2.5.