Download prepare_data.py from blazebsc/whereabouts-crash-detection: direct link, hf CLI and curl.
- Browser
- Download file 15.7 kB
-
https://huggingface.co/blazebsc/whereabouts-crash-detection/resolve/main/prepare_data.py
- Command line
-
hf download hf://blazebsc/whereabouts-crash-detection/prepare_data.py
-
curl -L -o prepare_data.py https://huggingface.co/blazebsc/whereabouts-crash-detection/resolve/main/prepare_data.py
15.7 kB
| #!/usr/bin/env python3 | |
| import io | |
| """ | |
| Builds the crash-confirmation training set. | |
| Positive class : synthesized vehicle-crash sensor windows built from the | |
| published FMVSS 208/214 crash-pulse corridors (real crash | |
| physics specs: 20-28 G haversine deceleration over 80-120 ms, | |
| vehicle structural ringing, mount low-pass, random phone | |
| orientation), embedded in simulated driving context. | |
| Negative classes: real phone motion (WISDM v1.1 — walking/jogging/stairs/ | |
| sitting/standing at 20 Hz) + synthetic hard negatives | |
| (pothole, hard brake, phone drop, bumpy road, door slam — | |
| the exact false-positive set). | |
| Output: train.pt / val.pt — dicts of windows (N,3,200 float32 @25 Hz) + labels. | |
| The model is a CONFIRMATION layer for the rule-based detector, which has | |
| already gated on impact + delta-v + stillness; the synthetic crashes must | |
| therefore also contain those signatures (they do: pulse + delta-v + post- | |
| impact stillness are part of the synthesis). | |
| """ | |
| io | |
| import math | |
| import random | |
| import tarfile | |
| import urllib.request | |
| import numpy as np | |
| SEED = 42 | |
| random.seed(SEED) | |
| np.random.seed(SEED) | |
| FS = 50 # model sample rate (Hz) — matches real phone accelerometer | |
| WINDOW_SEC = 8 # 4 s pre-impact + 4 s post | |
| WINDOW = FS * WINDOW_SEC | |
| GRAVITY = 9.81 | |
| WISDM_URL = "https://www.cis.fordham.edu/wisdm/includes/datasets/latest/WISDM_ar_latest.tar.gz" | |
| WISDM_LOCAL = "/tmp/opencode/wisdm.tar.gz" | |
| import io | |
| import math | |
| import random | |
| import tarfile | |
| import urllib.request | |
| import numpy as np | |
| SEED = 42 | |
| random.seed(SEED) | |
| np.random.seed(SEED) | |
| FS = 50 # model sample rate (Hz) — matches real phone accelerometer | |
| WINDOW_SEC = 8 # 4 s pre-impact + 4 s post | |
| WINDOW = FS * WINDOW_SEC | |
| GRAVITY = 9.81 | |
| WISDM_URL = "https://www.cis.fordham.edu/wisdm/includes/datasets/latest/WISDM_ar_latest.tar.gz" | |
| WISDM_LOCAL = "/tmp/opencode/wisdm.tar.gz" | |
| # ---------------------------------------------------------------- utilities | |
| def rotation_matrix(): | |
| """Random 3D rotation applied so the impact axis is arbitrary (phone orientation).""" | |
| a, b, c = (random.uniform(0, 2 * math.pi) for _ in range(3)) | |
| ca, sa = math.cos(a), math.sin(a) | |
| cb, sb = math.cos(b), math.sin(b) | |
| cc, sc = math.cos(c), math.sin(c) | |
| rx = np.array([[1, 0, 0], [0, ca, -sa], [0, sa, ca]]) | |
| ry = np.array([[cb, 0, sb], [0, 1, 0], [-sb, 0, cb]]) | |
| rz = np.array([[cc, -sc, 0], [sc, cc, 0], [0, 0, 1]]) | |
| return rz @ ry @ rx | |
| def resample(signal, src_hz, dst_hz=FS): | |
| n_out = max(2, int(len(signal) * dst_hz / src_hz)) | |
| x = np.arange(len(signal)) | |
| return np.interp(np.linspace(0, len(signal) - 1, n_out), x, signal) | |
| def add_gravity_and_noise(sig, rotation, noise_g=0.04): | |
| g = rotation @ np.array([0.0, 0.0, GRAVITY]) | |
| noise = np.random.normal(0, noise_g * GRAVITY, (len(sig), 3)) | |
| return sig + g + noise | |
| def downmix(sig): | |
| """(N,3) → (3,N) transposed view for windowing.""" | |
| return sig.T.copy() | |
| def windows_from(signal_3xn, window=WINDOW, stride=WINDOW // 2): | |
| out = [] | |
| for start in range(0, len(signal_3xn[0]) - window + 1, stride): | |
| out.append(signal_3xn[:, start:start + window]) | |
| return out | |
| # ------------------------------------------------- synthesis: crash + events | |
| def crash_pulse(duration_ms=None, peak_g=None): | |
| """FMVSS 208-style frontal crash deceleration: haversine pulse + structural | |
| ringing + mount low-pass, per the published corridor (20-28 G, 80-120 ms).""" | |
| duration_ms = duration_ms or random.uniform(80, 120) | |
| peak_g = peak_g or random.uniform(20, 28) | |
| n = int(duration_ms / 1000 * 1000) # 1 kHz internal | |
| t = np.linspace(0, duration_ms / 1000, n) | |
| # haversine deceleration pulse | |
| pulse = peak_g * 0.5 * (1 - np.cos(2 * np.pi * t / (duration_ms / 1000))) | |
| # vehicle structural ringing: 35 Hz damped oscillation | |
| ringing = np.random.uniform(2, 5) * np.sin(2 * np.pi * 35 * t) * np.exp(-t / 0.03) | |
| sig = (pulse + ringing) * GRAVITY | |
| # phone-mount low-pass (~35 Hz) applied by simple moving average | |
| k = max(1, int(1000 / 35)) | |
| sig = np.convolve(sig, np.ones(k) / k, mode="same") | |
| return sig # 1 kHz, single axis (deceleration direction) | |
| def embed_impact(context_3xn, fs, impact_signal_1k): | |
| """Embed a crash pulse mid-context with a random orientation + delta-v.""" | |
| rot = rotation_matrix() | |
| n_imp = len(impact_signal_1k) | |
| imp = resample(impact_signal_1k, 1000, fs) | |
| imp_3 = (rot @ np.vstack([imp, np.zeros_like(imp), np.zeros_like(imp)])).T | |
| ctx = context_3xn.copy() | |
| n = ctx.shape[0] | |
| start = n // 2 - n_imp // 2 | |
| end = min(n, start + len(imp_3)) | |
| ctx[start:end] += imp_3[: end - start] | |
| # delta-v: velocity drop across the impact — decelerate the driving-noise | |
| # amplitude slightly after impact (car has stopped) | |
| half = ctx.shape[0] // 2 | |
| ctx[half:] *= 0.15 | |
| return ctx | |
| def driving_context(seconds): | |
| """Simulated driving: gravity (random orientation) + road noise + engine vibration.""" | |
| n = int(seconds * FS) | |
| rot = rotation_matrix() | |
| t = np.arange(n) / FS | |
| road = np.random.normal(0, 0.12, (n, 3)) | |
| engine = 0.03 * np.sin(2 * np.pi * random.uniform(8, 14) * t)[:, None] * np.ones((1, 3)) | |
| g = (rot @ np.array([0.0, 0.0, GRAVITY]))[None, :] | |
| return g + road + engine | |
| def stationary_context(seconds): | |
| n = int(seconds * FS) | |
| rot = rotation_matrix() | |
| g = (rot @ np.array([0.0, 0.0, GRAVITY]))[None, :] | |
| return g + np.random.normal(0, 0.03, (n, 3)) | |
| # --------------------------------------------------------- synthetic events | |
| def synth_pothole(ctx): | |
| """Sharp 3-5 G spike + damped ringing; driving continues (no delta-v).""" | |
| ctx = ctx.copy() | |
| n = ctx.shape[0] | |
| pos = n // 3 | |
| spike_n = int(0.04 * FS) | |
| rot = rotation_matrix() | |
| spike = np.random.uniform(3, 5) * GRAVITY | |
| t = np.linspace(0, math.pi, spike_n) | |
| wave = spike * np.sin(t) | |
| imp = (rot @ np.vstack([wave, np.zeros_like(wave), np.zeros_like(wave)])).T | |
| ctx[pos:pos + spike_n] += imp | |
| return ctx | |
| def synth_hard_brake(ctx): | |
| """Sustained -0.5 g along travel axis for 1.5 s; no impact spike.""" | |
| ctx = ctx.copy() | |
| n = ctx.shape[0] | |
| rot = rotation_matrix() | |
| brake_n = int(1.5 * FS) | |
| pos = min(n // 3, n - brake_n) | |
| brake = -0.5 * GRAVITY * np.ones(brake_n) * np.hanning(brake_n) * 2 | |
| ctx[pos:pos + brake_n] += (rot @ np.vstack([brake, np.zeros_like(brake), np.zeros_like(brake)])).T | |
| return ctx | |
| def synth_phone_drop(): | |
| """5-10 G brief spikes + bounces while parked (no delta-v — speed ~0).""" | |
| ctx = stationary_context(WINDOW_SEC / FS) | |
| rot = rotation_matrix() | |
| for bounce_t in (0.3, 0.45, 0.65): | |
| spike_n = int(0.03 * FS) | |
| pos = int(bounce_t * FS) | |
| spike = np.random.uniform(5, 10) * GRAVITY * np.hanning(spike_n) | |
| imp = (rot @ np.vstack([spike, np.zeros_like(spike), np.zeros_like(spike)])).T | |
| pos = min(pos, ctx.shape[1] - spike_n) | |
| ctx[pos:pos + spike_n] += imp | |
| return ctx | |
| def synth_bumpy_road(ctx): | |
| """Repeated 0.5-2 G oscillation; driving continues.""" | |
| ctx = ctx.copy() | |
| n = ctx.shape[0] | |
| t = np.arange(n) / FS | |
| bump = np.random.uniform(0.5, 2.0) * GRAVITY * np.sin(2 * np.pi * np.random.uniform(3, 6) * t) | |
| rot = rotation_matrix() | |
| ctx += (rot @ np.vstack([bump, bump * 0.3, -bump * 0.5])).T | |
| return ctx | |
| def synth_door_slam(ctx): | |
| """2-6 G spike while parked.""" | |
| ctx = ctx.copy() | |
| rot = rotation_matrix() | |
| spike_n = int(0.05 * FS) | |
| pos = ctx.shape[1] // 2 | |
| spike = np.random.uniform(2, 6) * GRAVITY * np.hanning(spike_n) | |
| ctx[pos:pos + spike_n] += (rot @ np.vstack([spike, np.zeros_like(spike), np.zeros_like(spike)])).T | |
| return ctx | |
| # ------------------------------------------------------------ WISDM loader | |
| def load_wisdm(): | |
| """Real phone motion at 20 Hz: dict activity → (N,3) accel array in m/s².""" | |
| if not __import__("os").path.exists(WISDM_LOCAL): | |
| urllib.request.urlretrieve(WISDM_URL, WISDM_LOCAL) | |
| rows = {} | |
| with tarfile.open(WISDM_LOCAL) as tar: | |
| raw = tar.extractfile("WISDM_ar_v1.1/WISDM_ar_v1.1_raw.txt").read().decode() | |
| for line in io.StringIO(raw): | |
| parts = line.strip().rstrip(";").split(",") | |
| if len(parts) != 6: | |
| continue | |
| try: | |
| activity, x, y, z = parts[1], float(parts[3]), float(parts[4]), float(parts[5]) | |
| except ValueError: | |
| continue | |
| rows.setdefault(activity, []).append([x, y, z]) | |
| out = {} | |
| for activity, samples in rows.items(): | |
| arr = np.array(samples) * GRAVITY # WISDM stores in g | |
| out[activity] = arr | |
| return out | |
| # ------------------------------------------------------------------ dataset | |
| def build_dataset(): | |
| wisdm = load_wisdm() | |
| train_x, train_y = [], [] | |
| val_x, val_y = [], [] | |
| def add(sig_3xn, label, split="train"): | |
| if sig_3xn.shape[0] > sig_3xn.shape[1]: | |
| sig_3xn = sig_3xn.T # (N, 3) row-oriented → (3, N) | |
| for w in windows_from(sig_3xn): | |
| (train_x if split == "train" else val_x).append(w) | |
| (train_y if split == "train" else val_y).append(label) | |
| def split_sig(sig, train_frac=0.8): | |
| cut = int(len(sig[0]) * train_frac) | |
| return sig[:, :cut], sig[:, cut:] | |
| # ---- negatives: real WISDM daily-life motion (80/20 split per activity) | |
| for activity, arr in wisdm.items(): | |
| # resample each axis independently (arr is (N,3)) | |
| sig = np.stack([resample(arr[:, ax], 20, FS) for ax in range(3)]) # (3,N) | |
| tr, va = split_sig(sig) | |
| for w in windows_from(tr): | |
| train_x.append(w) | |
| train_y.append(0) | |
| for w in windows_from(va): | |
| val_x.append(w) | |
| val_y.append(0) | |
| # ---- negatives: synthetic hard negatives (the false-positive set) | |
| hard = [ | |
| synth_pothole(driving_context(WINDOW_SEC)), | |
| synth_hard_brake(driving_context(WINDOW_SEC)), | |
| synth_phone_drop(), | |
| synth_bumpy_road(driving_context(WINDOW_SEC)), | |
| synth_door_slam(stationary_context(WINDOW_SEC / FS)), | |
| ] | |
| for i, sig in enumerate(hard): | |
| # jitter the context so no two are identical | |
| add(sig + np.random.normal(0, 0.05 * GRAVITY, sig.shape), 0) | |
| add(sig + np.random.normal(0, 0.05 * GRAVITY, sig.shape), 0, "val") | |
| # ---- negatives: REAL driving data from the S23 (drive_home.csv) | |
| import csv as csv_mod | |
| for csv_file in ("drive_home.csv", "drive_trip.csv"): | |
| try: | |
| rows = [] | |
| with open(csv_file) as f: | |
| for r in csv_mod.DictReader(f): | |
| try: | |
| rows.append([ | |
| float(r["accel_x"]), float(r["accel_y"]), float(r["accel_z"]) | |
| ]) | |
| except (ValueError, KeyError): | |
| pass | |
| if len(rows) < WINDOW: | |
| continue | |
| sig = np.array(rows, dtype=np.float32).T # (3, N) | |
| tr, va = split_sig(sig) | |
| for w in windows_from(tr): | |
| train_x.append(w) | |
| train_y.append(0) | |
| for w in windows_from(va): | |
| val_x.append(w) | |
| val_y.append(0) | |
| except Exception: | |
| pass | |
| # ---- VZCrash: REAL crashes + real near-miss/normal-driving negatives | |
| # 100 Hz vehicle-mounted IMU in g, 16 s events; downsample to 50 Hz m/s². | |
| # Crash windows are centered on the peak |accel| sample; negatives use | |
| # strided windows. Validation split uses the dataset's own val files. | |
| def vzcrash_events(split, max_neg_events=None): | |
| import glob as glob_mod | |
| import pyarrow as pa | |
| files = sorted(glob_mod.glob(f"vzcrash/data/{split}-*.parquet")) | |
| crashes, negs = [], [] | |
| for fp in files: | |
| tbl = pq_read.read_table(fp, columns=["label", "gsensor"]) | |
| lab = np.asarray(tbl["label"].to_pylist(), dtype=np.int64) | |
| col = tbl["gsensor"].combine_chunks() | |
| try: | |
| # list<fixed_size_list<float32,3>> — slice events via offsets | |
| if isinstance(col, pa.ChunkedArray): | |
| col = pa.concat_arrays(col.chunks) | |
| offs = np.asarray(col.offsets) | |
| flat = (col.flatten().flatten() | |
| .to_numpy(zero_copy_only=False) | |
| .astype(np.float32).reshape(-1, 3)) | |
| events = ((flat[offs[i]:offs[i + 1]], i) for i in range(len(offs) - 1)) | |
| except Exception: | |
| events = ((np.asarray(x, dtype=np.float32), i) | |
| for i, x in enumerate(tbl["gsensor"].to_pylist())) | |
| for arr, i in events: | |
| if arr.ndim != 2 or arr.shape[0] < WINDOW * 2: | |
| continue | |
| ev = (arr[0::2] + arr[1::2]) * 0.5 * GRAVITY # 100→50 Hz, g→m/s² | |
| (crashes if lab[i] == 0 else negs).append(ev) | |
| if max_neg_events is not None and len(negs) > max_neg_events: | |
| rng = random.Random(SEED) | |
| rng.shuffle(negs) | |
| negs = negs[:max_neg_events] | |
| return crashes, negs | |
| import pyarrow.parquet as pq_read # noqa: local alias for clarity | |
| def add_vzcrash(split, max_neg_events=None, frac=1.0): | |
| crashes, negs = vzcrash_events(split, max_neg_events) | |
| print(f" vzcrash {split}: {len(crashes)} crash events, {len(negs)} negative events") | |
| for ev in crashes: | |
| pk = int(np.argmax(np.abs(ev).max(axis=1))) | |
| start = min(max(0, pk - WINDOW // 2), len(ev) - WINDOW) | |
| w = ev[start:start + WINDOW].T.copy() | |
| if random.random() <= frac: | |
| (train_x if split == "train" else val_x).append(w) | |
| (train_y if split == "train" else val_y).append(1) | |
| for ev in negs: | |
| for w in windows_from(ev.T.copy())[:2]: | |
| if random.random() <= frac: | |
| (train_x if split == "train" else val_x).append(w) | |
| (train_y if split == "train" else val_y).append(0) | |
| add_vzcrash("train", max_neg_events=62000) | |
| add_vzcrash("validation", frac=0.15) # sample val to keep the npz small | |
| # ---- positives: synthetic phone-mount crash pulses (domain bridge — | |
| # VZCrash IMUs are vehicle-mounted; the app runs on a phone) | |
| for i in range(600): | |
| ctx = driving_context(WINDOW_SEC) | |
| pulse = crash_pulse() | |
| # vary peak | |
| sig = embed_impact(ctx, FS, pulse * random.uniform(0.8, 1.3)) | |
| add(sig + np.random.normal(0, 0.04 * GRAVITY, sig.shape), 1, | |
| "val" if i % 5 == 0 else "train") | |
| # ---- extra negatives: driving with NO event (context only) | |
| for i in range(200): | |
| add(driving_context(WINDOW_SEC) + np.random.normal(0, 0.05 * GRAVITY, (WINDOW, 3)), | |
| 0, "val" if i % 5 == 0 else "train") | |
| # shuffle (train only) | |
| idx = list(range(len(train_x))) | |
| random.shuffle(idx) | |
| train_x = [train_x[i] for i in idx] | |
| train_y = [train_y[i] for i in idx] | |
| return (np.array(train_x, dtype=np.float32), np.array(train_y, dtype=np.int64), | |
| np.array(val_x, dtype=np.float32), np.array(val_y, dtype=np.int64)) | |
| if __name__ == "__main__": | |
| tr_x, tr_y, va_x, va_y = build_dataset() | |
| print(f"train: {len(tr_y)} ({sum(tr_y)} crash) val: {len(va_y)} ({sum(va_y)} crash)") | |
| np.savez_compressed("/home/blake7/Documents/GitHub/paralino/ml/dataset.npz", | |
| train_x=tr_x, train_y=tr_y, val_x=va_x, val_y=va_y) | |
| print("saved ml/dataset.npz") | |