File size: 15,732 Bytes
410b1bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9df87c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
410b1bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
#!/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")