Batch runs, analytics and ML¶
Building a training set?
Features for machine learning does the loop below
for you: feature_table adds signal shape features, design
parameters and per-run error handling.
crashmetrics returns plain numbers and small dataclasses, so results drop straight into tables. This page shows how to process many runs (a DOE, a variant study, a test series) into one results table for analytics, dashboards or machine-learning models.
The pattern¶
import csv
from pathlib import Path
rows = []
for run in sorted(Path("doe").iterdir()): # one folder per run
t, ax, ay, az = load_headform(run) # your loader
a = resultant(*(cfc_filter(t, c, cfc=1000) for c in (ax, ay, az)))
hic = calculate_hic(t, a)
rows.append({
"run": run.name,
"hic15": hic.value,
"peak_g": peak(t, a).value,
"clip_3ms_g": clip_3ms(t, a),
"colour": hic_colour(hic.value),
})
with open("results.csv", "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=list(rows[0]))
writer.writeheader()
writer.writerows(rows)
For LS-DYNA runs, a load_headform built on read_nodout is in
Loading your data,
and read_run(run) reads every ASCII file of a run (rcforc, secforc,
sbtout ...) in one call; see LS-DYNA ASCII output.
Three habits make this robust:
- One row per run, one column per quantity: easy to filter, plot and join with design parameters.
- Keep the design parameters in the same row (thickness, stiffness, clearance, variant name): the table is then directly a training set.
-
Catch failures per run so one bad file does not stop the batch:
Results as dictionaries¶
Every result object is a dataclass:
from dataclasses import asdict
asdict(calculate_hic(t, a)) # {'value': ..., 'start_time': ..., 'end_time': ...}
asdict(nij(t, fz, my, fx=fx)) # includes the category and per-category maxima
Scores nest further, e.g. mpdb.occupants["driver"].regions["chest_abdomen"].points;
pick the fields you want into your row.
Analytics with pandas¶
import pandas as pd
df = pd.read_csv("results.csv")
df.describe() # spread of every criterion
df.sort_values("hic15", ascending=False).head(10) # worst runs
df.pivot(index="stiffness", columns="clearance_mm", values="hic15")
df.groupby("colour").size() # colour distribution
df.corr(numeric_only=True)["hic15"] # what drives HIC
Export to Excel for a report with df.to_excel("results.xlsx")
(needs openpyxl).
Data for surrogate and ML models¶
With design parameters and results in one table, a surrogate is a few lines. A linear fit with NumPy:
import numpy as np
X = df[["stiffness", "clearance_mm"]].to_numpy()
y = df["hic15"].to_numpy()
coef, *_ = np.linalg.lstsq(np.column_stack([np.ones(len(y)), X]), y, rcond=None)
or any scikit-learn model:
from sklearn.ensemble import RandomForestRegressor
model = RandomForestRegressor().fit(X, y)
model.predict([[1.1, 80.0]])
Because the criteria are computed the same way for every run (and for test and CAE alike), the labels are consistent, which matters more for a model than the choice of algorithm.
Complete example¶
A 12-run DOE over bonnet stiffness and under-bonnet clearance, written to CSV, with correlations and a linear surrogate:
"""Example 10: batch processing a DOE into a results table (CSV, pandas, ML).
Each design variant (here: bonnet stiffness and under-bonnet clearance)
gives a headform acceleration. The loop computes the criteria for every
run and writes one row per run, ready for analytics, dashboards or as a
training set for a surrogate / machine-learning model.
"""
import csv
from dataclasses import asdict
from itertools import product
import numpy as np
from crashmetrics.acceleration import clip_3ms, peak
from crashmetrics.pedestrian import calculate_hic, hic_colour
from crashmetrics.signals import cfc_filter, resultant
t = np.arange(0.0, 0.03, 2e-5) # s, 50 kHz
def headform_pulse(stiffness, clearance_mm):
"""Toy model: stiffer bonnets peak higher; small clearance bottoms out."""
duration = 0.012 / np.sqrt(stiffness)
a = 95.0 * stiffness * 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 * np.sin(np.pi * hit)
return 0.9 * a, 0.436 * a # x and z components, g
rows = []
for stiffness, clearance in product([0.8, 1.0, 1.2, 1.4], [50.0, 70.0, 90.0]):
# Filter each component, then form the resultant (never filter a resultant).
ax, az = headform_pulse(stiffness, clearance)
a = resultant(cfc_filter(t, ax, cfc=1000), cfc_filter(t, az, cfc=1000))
hic = calculate_hic(t, a)
rows.append({
"stiffness": stiffness,
"clearance_mm": clearance,
"hic15": round(hic.value, 1),
"hic_window_ms": round((hic.end_time - hic.start_time) * 1000, 2),
"peak_g": round(peak(t, a).value, 1),
"clip_3ms_g": round(clip_3ms(t, a), 1),
"colour": hic_colour(hic.value),
})
# --- 1. Write the table ---------------------------------------------------------
with open("crashmetrics_doe_results.csv", "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=list(rows[0]))
writer.writeheader()
writer.writerows(rows)
print(f"Wrote {len(rows)} runs to crashmetrics_doe_results.csv")
print(f"{'stiffness':>9} {'clearance':>9} {'HIC15':>7} "
f"{'peak g':>7} {'3 ms g':>7} colour")
for r in rows:
print(f"{r['stiffness']:9.1f} {r['clearance_mm']:9.0f} {r['hic15']:7.0f} "
f"{r['peak_g']:7.1f} {r['clip_3ms_g']:7.1f} {r['colour']}")
# --- 2. Quick analytics with numpy (pandas works the same way) ---------------
x = np.array([[r["stiffness"], r["clearance_mm"]] for r in rows])
y = np.array([r["hic15"] for r in rows])
for i, name in enumerate(["stiffness", "clearance_mm"]):
print(f"Correlation of HIC15 with {name:12s}: {np.corrcoef(x[:, i], y)[0, 1]:+.2f}")
coef, *_ = np.linalg.lstsq(np.column_stack([np.ones(len(y)), x]), y, rcond=None)
print(f"Linear surrogate: HIC15 = {coef[0]:.0f} {coef[1]:+.0f} x stiffness "
f"{coef[2]:+.1f} x clearance_mm")
# --- 3. Every result object is a dataclass: asdict() gives a plain dict -------
ax, az = headform_pulse(1.0, 90.0)
a = resultant(cfc_filter(t, ax, cfc=1000), cfc_filter(t, az, cfc=1000))
result = calculate_hic(t, a)
print({key: round(value, 5) for key, value in asdict(result).items()})
# With pandas installed:
# import pandas as pd
# df = pd.read_csv("crashmetrics_doe_results.csv")
# df.pivot(index="stiffness", columns="clearance_mm", values="hic15")
Output:
Wrote 12 runs to crashmetrics_doe_results.csv
stiffness clearance HIC15 peak g 3 ms g colour
0.8 50 533 185.0 75.4 green
0.8 70 280 76.0 71.4 green
0.8 90 280 76.0 71.4 green
1.0 50 779 200.0 94.0 yellow
1.0 70 438 95.0 87.8 green
1.0 90 438 95.0 87.8 green
1.2 50 1067 214.6 112.4 orange
1.2 70 630 114.0 103.6 green
1.2 90 630 114.0 103.6 green
1.4 50 1396 228.9 130.6 brown
1.4 70 858 133.0 118.9 yellow
1.4 90 858 133.0 118.9 yellow
Correlation of HIC15 with stiffness : +0.79
Correlation of HIC15 with clearance_mm: -0.51
Linear surrogate: HIC15 = 135 +1121 x stiffness -9.8 x clearance_mm
{'value': 437.74055, 'start_time': 0.00198, 'end_time': 0.01002}