Skip to content

crashmetrics.features

features

Feature extraction for analytics and machine learning.

Turns crash signals and crashmetrics results into flat rows of numbers, one row per run, ready for a CSV file, a pandas DataFrame or a scikit-learn model. Only NumPy is needed; pandas is used if installed.

Functions:

  • signal_features: Shape features of any 1D signal (peaks, timing, impulse, pulse width, energy centroid, frequency content).
  • head_features: HIC15, HIC36, 3 ms clip, peak and the Euro NCAP headform colour of a resultant head acceleration, plus its shape.
  • pulse_features: OLC, delta-V, rebound, dynamic crush and the shape of a vehicle crash pulse.
  • flatten: Any result object (dataclass, dict, nested scores) as a flat dict of numbers and labels.
  • feature_table: Run an extractor over many runs, one row per run; a failing run gives an error column instead of stopping the batch.
  • write_csv, to_dataframe, to_matrix: Hand the table to a CSV file, pandas, or NumPy arrays for model training.

Conventions:

  • Time is in seconds on input; times in feature names ending in _ms are milliseconds from the first sample.
  • Amplitude features keep the input unit (g, N, mm ...).
  • Features that cannot be defined for a signal (for example the rise time of an all-zero signal) are nan, so every row has the same columns.

Value module-attribute

Value = float | int | str | bool | None

A cell of a feature row.

signal_features

signal_features(
    time: ArrayLike,
    signal: ArrayLike,
    prefix: str = "",
    spectrum: bool = True,
) -> dict[str, float]

Return shape features of a 1D signal.

Parameters:

Name Type Description Default
time ArrayLike

1D time array in s, strictly increasing.

required
signal ArrayLike

Signal of the same length, in any unit.

required
prefix str

Text put in front of every feature name, e.g. "head_".

''
spectrum bool

Include the frequency features (needs a resampling and an FFT).

True

Returns:

Type Description
dict

Features, in the signal's unit unless named otherwise:

  • max, min, peak_abs: largest, smallest and largest absolute value.
  • t_max_ms, t_min_ms, t_peak_abs_ms: their times.
  • mean, rms, std.
  • integral, abs_integral: area under the signal and under its magnitude (unit x s; for an acceleration in m/s^2 the integral is the velocity change).
  • onset_ms, end_ms, active_ms: first and last time the magnitude is at least 5 % of peak_abs, and the time between.
  • rise_ms: time from 10 % to 90 % of peak_abs before the peak.
  • width50_ms: total time at or above 50 % of peak_abs.
  • excursions50: number of separate excursions above 50 % of peak_abs (1 for a single pulse, more for multiple impacts).
  • centroid_ms: time centroid of the signal energy (x^2).
  • energy50_ms: time at which half of the signal energy has accumulated.
  • dominant_hz, spectral_centroid_hz: frequency of the largest spectral peak and the power-weighted mean frequency (if spectrum is True).
Notes

Timing and width features use the magnitude |signal|, so they do not depend on the sign convention of the channel. Times are measured from the first sample.

head_features

head_features(
    time: ArrayLike,
    acceleration: ArrayLike,
    prefix: str = "head_",
    shape: bool = True,
) -> dict[str, Value]

Return head injury criteria and shape features.

Parameters:

Name Type Description Default
time ArrayLike

1D time array in s.

required
acceleration ArrayLike

Resultant head (or headform) acceleration in g, already filtered (CFC 1000).

required
prefix str

Text put in front of every feature name.

'head_'
shape bool

Also include signal_features of the acceleration.

True

Returns:

Type Description
dict

hic15, hic15_t1_ms, hic15_t2_ms, hic36 (nan if the record is shorter than 36 ms), a3ms, peak_g, t_peak_ms and colour (the Euro NCAP headform colour of HIC15, a label for classification), followed by the shape features.

pulse_features

pulse_features(
    time: ArrayLike,
    acceleration: ArrayLike,
    v0: float,
    prefix: str = "pulse_",
    shape: bool = True,
) -> dict[str, Value]

Return crash pulse metrics and shape features.

Parameters:

Name Type Description Default
time ArrayLike

1D time array in s, starting at T0.

required
acceleration ArrayLike

Vehicle longitudinal acceleration in m/s^2 (negative when decelerating), filtered (CFC 60 or 180).

required
v0 float

Impact velocity in m/s.

required
prefix str

Text put in front of every feature name.

'pulse_'
shape bool

Also include signal_features of the acceleration in g.

True

Returns:

Type Description
dict

olc_g, delta_v, rebound_velocity, restitution, max_crush_mm, t_max_crush_ms, t_zero_velocity_ms, peak_decel_g and mean_decel_g, followed by the shape features of the acceleration in g.

flatten

flatten(
    obj: Any,
    prefix: str = "",
    sep: str = ".",
    max_items: int = 50,
) -> dict[str, Value]

Return any result as a flat dict of numbers and labels.

Dataclasses and mappings are walked recursively and their keys joined with sep: score_mpdb(...) gives keys such as "occupants.driver.regions.head_neck.points". Short lists and tuples of values get index keys ("limits.0"). NumPy arrays (time histories) and longer sequences are left out, so every value is a single number, string, bool or None.

Parameters:

Name Type Description Default
obj Any

A result object, dict, or plain value.

required
prefix str

Text put in front of every key, e.g. "mpdb.".

''
sep str

Separator between nested names.

'.'
max_items int

Longest list or tuple that is expanded.

50

feature_table

feature_table(
    runs: Mapping[str, Any] | Iterable[tuple[str, Any]],
    extract: Callable[[Any], Any],
    id_column: str = "run",
    params: Mapping[str, Mapping[str, Any]] | None = None,
    on_error: str = "record",
) -> list[dict[str, Value]]

Run extract on every run and return one flat row per run.

Parameters:

Name Type Description Default
runs Mapping[str, Any] | Iterable[tuple[str, Any]]

Run names and inputs: a dict {name: input} or pairs (name, input). The input is anything extract accepts, such as a folder path or a tuple of arrays.

required
extract Callable[[Any], Any]

Function returning the features of one run: a dict, a result object or a list of them (all are flattened with flatten).

required
id_column str

Name of the column holding the run name.

'run'
params Mapping[str, Mapping[str, Any]] | None

Design parameters per run name (thickness, variant ...), added to the row so the table is directly a training set.

None
on_error str

"record" (default): a run that raises an exception gets a row with only its name, its parameters and an error column, and the batch continues. "raise": stop at the first error.

'record'

Returns:

Type Description
list of dict

One row per run, in input order.

write_csv

write_csv(
    rows: Sequence[Mapping[str, Any]],
    path: str | PathLike[str],
    columns: Sequence[str] | None = None,
) -> list[str]

Write rows to a CSV file and return the column names.

The columns are the union of all rows' keys in first-seen order (unless given), so runs with missing features or an error column still line up; missing cells are left empty.

to_dataframe

to_dataframe(rows: Sequence[Mapping[str, Any]]) -> Any

Return the rows as a pandas DataFrame (pandas must be installed).

to_matrix

to_matrix(
    rows: Sequence[Mapping[str, Any]],
    columns: Sequence[str] | None = None,
) -> tuple[list[str], NDArray[float64]]

Return numeric columns as a 2D float array for model training.

Parameters:

Name Type Description Default
rows Sequence[Mapping[str, Any]]

Feature rows, e.g. from feature_table.

required
columns Sequence[str] | None

Columns to use, in order. By default every column whose values are all numbers (bools count as 0/1) or missing.

None

Returns:

Type Description
(names, matrix)

Column names and an array of shape (rows, columns). Missing values are nan; drop or impute them before training.