"""cine-28: measure one vehicle's speed from its line in a CFOS minute.
Follows the line channel by channel (the time of the strongest bend near the previous channel's time), then fits a
straight line: metres per second = 1 / slope.  usage: speed.py FILE.npy T_SECONDS [C0 C1]"""
import json, sys
import numpy as np
from scipy import ndimage
FS = 30.0
p, t0 = sys.argv[1], float(sys.argv[2])
C0, C1 = (int(sys.argv[3]), int(sys.argv[4])) if len(sys.argv) > 4 else (185, 245)
a = np.load(p, allow_pickle=False)
x = a - np.median(a, axis=1, keepdims=True)
env = ndimage.gaussian_filter1d(np.abs(x), 0.35 * FS, axis=1)   # the vehicle sits between its stretch and squeeze bands
cm = (C0 + C1) // 2
ts, cs = [], []
t = t0 * FS
for direction in (range(cm, C1), range(cm - 1, C0 - 1, -1)):
    t = t0 * FS
    for c in direction:
        lo, hi = int(max(0, t - 0.6 * FS)), int(min(env.shape[1], t + 0.6 * FS))
        k = lo + int(np.argmax(env[c, lo:hi])); t = k
        ts.append(k / FS); cs.append(c)
ts, cs = np.array(ts), np.array(cs)
A = np.vstack([cs, np.ones_like(cs)]).T
(sl, b), res, *_ = np.linalg.lstsq(A, ts, rcond=None)
r2 = 1 - ((ts - A @ [sl, b]) ** 2).sum() / ((ts - ts.mean()) ** 2).sum()
v = 1 / sl
print(json.dumps({"file": p.split("/")[-1], "t0": t0, "channels": [C0, C1], "m_per_s": round(float(v), 2),
                  "km_h": round(float(abs(v) * 3.6), 1), "r2": round(float(r2), 3),
                  "points": [[int(c), round(float(tt), 3)] for c, tt in sorted(zip(cs, ts))]}))
