ConsDrive / scripts /analysis /stall_reasons.py
ZenoNing's picture
Upload ConsDrive v2 source (part 2)
314ecfb verified
Raw History Blame Contribute Delete
7.47 kB
"""Classify why the ego was standing still, from recorder kinematics + traffic-light states.
Usage: python stall_reasons.py --merged merged.json --npz-dir DIR --tl-dir DIR --stoplines stoplines.json
--out stalls.json
For every stop (speed < 0.1 m/s for >= MIN_STOP_S) the ego's actually driven path after the stop is taken as
the path it should have driven. Every 0.5 s of the stop is labelled
blocked a vehicle/walker is on that path (within 22 m) now or within the next 3 s (recorded future)
red_light a same-direction stop line on the path belongs to a red/yellow light
stop_sign the ego is inside a stop-sign trigger and has been stopped for < 4 s
free none of the above: nothing required the ego to wait
and the stop records how long it had been continuously free when the ego finally moved.
"""
import argparse
import json
import math
import numpy as np
MIN_STOP_S = 3.0
STEP_S = 0.5
PATH_LEN = 25.0
CONFLICT_S = (2.5, 22.0) # arc length range from the ego centre (excludes vehicles behind)
LATERAL = {"vehicle": 2.0, "walker": 1.5}
LOOKAHEAD_S = 3.0
STOP_SIGN_WAIT_S = 4.0
CREEP_THROTTLE = 0.4
def future_path(hero, i_end):
"""Driven path from the stop position, resampled every 0.5 m; straight ahead if the ego never moved again."""
x0, y0, yaw0 = hero[i_end, 1], hero[i_end, 2], math.radians(hero[i_end, 3])
pts = [(x0, y0)]
dist = 0.0
for x, y in hero[i_end + 1:, 1:3]:
step = math.hypot(x - pts[-1][0], y - pts[-1][1])
if step < 0.25:
continue
pts.append((x, y))
dist += step
if dist >= PATH_LEN:
break
if dist < 5.0:
pts = [(x0 + s * math.cos(yaw0), y0 + s * math.sin(yaw0)) for s in np.arange(0, PATH_LEN, 0.5)]
pts = np.array(pts)
seg = np.hypot(*np.diff(pts, axis=0).T)
s = np.concatenate([[0.0], np.cumsum(seg)])
grid = np.arange(0.0, min(s[-1], PATH_LEN) + 1e-6, 0.5)
path = np.stack([np.interp(grid, s, pts[:, 0]), np.interp(grid, s, pts[:, 1])], axis=1)
heading = np.arctan2(*np.gradient(path, axis=0)[:, ::-1].T) if len(path) > 1 else np.array([yaw0])
return path, grid, heading
def project(points, path, grid):
d = np.hypot(points[:, None, 0] - path[None, :, 0], points[:, None, 1] - path[None, :, 1])
j = d.argmin(axis=1)
return d[np.arange(len(points)), j], grid[j], j
def tl_state_fn(tl):
changes = tl["changes"]
by_id = {}
for t, i, s in changes:
by_id.setdefault(int(i), []).append((t, int(s)))
def state(tl_id, t):
seq = by_id.get(tl_id)
if not seq:
return 4
k = np.searchsorted([c[0] for c in seq], t, side="right") - 1
return seq[max(k, 0)][1]
return state
def analyse_route(z, tl, lights, signs):
hero, ctrl, others = z["hero"], z["hero_ctrl"], z["others"]
types = json.loads(str(z["actors"]))
kinds = {int(k): ("walker" if v.startswith("walker.") else "vehicle") for k, v in types.items()}
t, v = hero[:, 0], hero[:, 4]
state = tl_state_fn(tl)
# recorder ids of the town's traffic lights (match by location)
rec_ids = tl["tl_ids"].astype(int)
rec_locs = tl["tl_locs"]
stop_lines = []
for light in lights:
if len(rec_locs) == 0:
break
d = np.hypot(*(rec_locs - np.array(light["loc"])).T)
if d.min() < 1.0:
for x, y, yaw, _, _ in light["stops"]:
stop_lines.append((x, y, math.radians(yaw), int(rec_ids[d.argmin()])))
stop_lines = np.array(stop_lines) if stop_lines else np.zeros((0, 4))
signs = np.array(signs) if signs else np.zeros((0, 4))
stopped = v < 0.1
edges = np.diff(np.concatenate([[0], stopped.astype(int), [0]]))
starts, ends = np.nonzero(edges == 1)[0], np.nonzero(edges == -1)[0] - 1
moved_before = np.concatenate([[0.0], np.cumsum(np.hypot(*np.diff(hero[:, 1:3], axis=0).T))])
out = []
for i0, i1 in zip(starts, ends):
t0, t1 = max(t[i0], 2.5), t[i1]
if t1 - t0 < MIN_STOP_S:
continue
path, grid, heading = future_path(hero, i1)
# actors on the path now or within LOOKAHEAD_S
sel = (others[:, 0] >= t0) & (others[:, 0] <= t1 + LOOKAHEAD_S)
rows = others[sel]
conflict_t = np.zeros(0)
if len(rows):
d, s, _ = project(rows[:, 2:4], path, grid)
lat = np.array([LATERAL[kinds.get(int(i), "vehicle")] for i in rows[:, 1]])
hit = (d < lat) & (s >= CONFLICT_S[0]) & (s <= CONFLICT_S[1])
conflict_t = rows[hit, 0]
# same-direction stop lines on the path
lines = []
if len(stop_lines):
d, s, j = project(stop_lines[:, :2], path, grid)
dyaw = np.abs((stop_lines[:, 2] - heading[j] + np.pi) % (2 * np.pi) - np.pi)
ok = (d < 2.5) & (s <= 20.0) & (dyaw < math.radians(45))
lines = sorted({int(i) for i in stop_lines[ok, 3]})
in_sign = bool(len(signs)) and bool(np.any(
np.hypot(signs[:, 0] - hero[i0, 1], signs[:, 1] - hero[i0, 2]) < np.maximum(signs[:, 2], signs[:, 3]) + 2.0))
labels = []
for ts in np.arange(t0, t1, STEP_S):
if np.any((conflict_t >= ts) & (conflict_t <= ts + LOOKAHEAD_S)):
labels.append("blocked")
elif any(state(i, ts) in (0, 1) for i in lines):
labels.append("red_light")
elif in_sign and ts - t0 < STOP_SIGN_WAIT_S:
labels.append("stop_sign")
else:
labels.append("free")
free_run = 0
for lab in reversed(labels):
if lab != "free":
break
free_run += 1
departed = i1 + 1 < len(hero)
dep_ctrl = ctrl[(ctrl[:, 0] > t1 - 0.1) & (ctrl[:, 0] < t1 + 0.8)]
creep = departed and t1 - t0 >= 39.0 and len(dep_ctrl) > 0 and np.any(np.abs(dep_ctrl[:, 2] - CREEP_THROTTLE) < 1e-3)
dep_conflict = bool(np.any((conflict_t >= t1) & (conflict_t <= t1 + LOOKAHEAD_S)))
counts = {k: labels.count(k) * STEP_S for k in ("blocked", "red_light", "stop_sign", "free")}
out.append(dict(
t0=round(float(t0), 2), t1=round(float(t1), 2), duration=round(float(t1 - t0), 2),
route_start=bool(moved_before[i0] < 1.0), ended=("creep" if creep else "policy" if departed else "route_end"),
first=labels[0], free_run_s=free_run * STEP_S, departed_into_conflict=dep_conflict, **counts))
return out
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--merged", required=True)
ap.add_argument("--npz-dir", required=True)
ap.add_argument("--tl-dir", required=True)
ap.add_argument("--stoplines", required=True)
ap.add_argument("--out", required=True)
args = ap.parse_args()
towns = {r["route_id"]: r["town_name"] for r in json.load(open(args.merged))["_checkpoint"]["records"]}
stoplines = json.load(open(args.stoplines))
result = {}
for rid, town in sorted(towns.items()):
z = np.load(f"{args.npz_dir}/{rid}.npz", allow_pickle=True)
tl = np.load(f"{args.tl_dir}/{rid}_tl.npz")
result[rid] = analyse_route(z, tl, stoplines.get(town, []), stoplines.get(f"{town}/stop_signs", []))
json.dump(result, open(args.out, "w"), indent=1)
stops = [s for v in result.values() for s in v]
print(f"{len(stops)} stops >= {MIN_STOP_S}s in {len(result)} routes")
if __name__ == "__main__":
main()