"""Classify failed Bench2Drive routes and extract collision geometry from recorder kinematics. Usage: python failure_report.py --merged merged.json --routes bench2drive220.xml \ --npz-dir DIR --extents extents.json --out report.json """ import argparse import json import math import re import xml.etree.ElementTree as ET from pathlib import Path import carla import numpy as np CARLA_MAPS = Path("/workspace/carla0915/CarlaUE4/Content/Carla/Maps") HALF_FOV = math.radians(55.0) CAM_BACK = 1.5 EGO_EXTENT = (2.446, 0.918) _maps = {} def get_map(town): if town not in _maps: for p in (CARLA_MAPS / town / "OpenDrive" / f"{town}.xodr", CARLA_MAPS / "OpenDrive" / f"{town}.xodr"): if p.exists(): _maps[town] = carla.Map(town, p.read_text()) break return _maps[town] def is_success(rec): if rec["status"] not in ("Completed", "Perfect"): return False return all(not v or k == "min_speed_infractions" for k, v in rec["infractions"].items()) def interp_state(traj, t): """traj columns: t, x, y, yaw, (v). Returns x, y, yaw at time t.""" i = int(np.clip(np.searchsorted(traj[:, 0], t), 1, len(traj) - 1)) a, b = traj[i - 1], traj[i] w = 0.0 if b[0] == a[0] else float(np.clip((t - a[0]) / (b[0] - a[0]), 0, 1)) dyaw = (b[3] - a[3] + 180) % 360 - 180 return a[1] + w * (b[1] - a[1]), a[2] + w * (b[2] - a[2]), a[3] + w * dyaw def corners(x, y, yaw, ext): c, s = math.cos(math.radians(yaw)), math.sin(math.radians(yaw)) return [(x + lx * c - ly * s, y + lx * s + ly * c) for lx in (-ext[0], ext[0]) for ly in (-ext[1], ext[1])] def in_fov(ego_pose, other_pose, ext): ex, ey, eyaw = ego_pose c, s = math.cos(math.radians(eyaw)), math.sin(math.radians(eyaw)) cx, cy = ex - CAM_BACK * c, ey - CAM_BACK * s for px, py in corners(*other_pose, ext): lx = (px - cx) * c + (py - cy) * s ly = -(px - cx) * s + (py - cy) * c if lx > 0 and abs(math.atan2(ly, lx)) < HALF_FOV: return True return False def to_ego_frame(ego_pose, p): ex, ey, eyaw = ego_pose c, s = math.cos(math.radians(eyaw)), math.sin(math.radians(eyaw)) dx, dy = p[0] - ex, p[1] - ey return dx * c + dy * s, -dx * s + dy * c def speed_at(traj, t, dt=0.3): a, b = interp_state(traj, t - dt), interp_state(traj, t) return math.hypot(b[0] - a[0], b[1] - a[1]) / dt def last_departure(hero, t_end, window=20.0): """Last standstill (>=0.5 s below 0.1 m/s) that ended within `window` s before t_end.""" v = np.convolve(hero[:, 4], np.ones(5) / 5, "same") sel = np.where((hero[:, 0] > t_end - window) & (hero[:, 0] < t_end) & (v < 0.1))[0] if not len(sel): return None k = sel[-1] start = k while start > 0 and v[start - 1] < 0.1: start -= 1 if hero[k, 0] - hero[start, 0] < 0.5: return None return {"t_stop": float(hero[start, 0]), "t_depart": float(hero[k, 0]), "x": float(hero[k, 1]), "y": float(hero[k, 2])} def collision_features(d, town, extents, t_c, other_id): hero = d["hero"] actors = json.loads(str(d["actors"])) otype = actors.get(str(int(other_id)), "?") others = d["others"] tr = others[others[:, 1] == other_id][:, [0, 2, 3, 4]] feat = {"t": round(float(t_c), 2), "other_type": otype} ego_c = interp_state(hero, t_c) m = get_map(town) wp = m.get_waypoint(carla.Location(x=ego_c[0], y=ego_c[1], z=0), project_to_road=True) feat["ego_in_junction"] = bool(wp.is_junction) feat["ego_speed"] = round(speed_at(hero, t_c - 0.1), 2) dep = last_departure(hero, t_c) if dep: feat["departed_from_stop_s_before"] = round(t_c - dep["t_depart"], 2) feat["stop_duration"] = round(dep["t_depart"] - dep["t_stop"], 2) feat["dist_since_departure"] = round(float(np.linalg.norm(np.array(ego_c[:2]) - [dep["x"], dep["y"]])), 1) loc = carla.Location(x=dep["x"], y=dep["y"], z=0) wpd = m.get_waypoint(loc, project_to_road=True) signs = wpd.get_landmarks(25.0, False) feat["stop_reason"] = sorted({l.type for l in signs if l.type in ("206", "1000001")}) or None if len(tr) < 2: feat["other_track"] = "missing" return feat ext = extents.get(otype, (2.4, 1.0)) t_pre = min(t_c - 0.1, tr[-1, 0]) oth_c = interp_state(tr, t_pre) lx, ly = to_ego_frame(ego_c, oth_c) feat["other_rel_xy"] = (round(lx, 1), round(ly, 1)) feat["rel_heading"] = round(((oth_c[2] - ego_c[2] + 180) % 360) - 180, 0) feat["other_speed"] = round(speed_at(tr, t_pre), 2) if tr[0, 0] < t_pre - 0.3 else None # Field-of-view history (geometry only, ignores occlusion and fog). ts = tr[(tr[:, 0] >= t_c - 15) & (tr[:, 0] <= t_pre), 0] vis = [(t, in_fov(interp_state(hero, t), interp_state(tr, t), ext)) for t in ts] seen = [t for t, v in vis if v] feat["first_tracked_s_before"] = round(t_c - float(tr[0, 0]), 1) feat["in_fov_at"] = {f"-{k}s": bool(any(v for t, v in vis if abs(t - (t_c - k)) < 0.06)) for k in (0.5, 1.0, 1.5, 2.0, 3.0)} feat["last_in_fov_s_before"] = round(t_c - max(seen), 2) if seen else None feat["fov_time_last15s"] = round(0.1 * len(seen), 1) # Warning time: start of the last uninterrupted in-FOV stretch before impact. warn = None for t, v in reversed(vis): if not v: break warn = t feat["warning_s"] = round(t_c - warn, 2) if warn is not None else 0.0 if dep: feat["stop_is_route_start"] = dep["t_stop"] < 1.0 t_d = dep["t_depart"] feat["in_fov_at_departure"] = bool(tr[0, 0] <= t_d and in_fov(interp_state(hero, t_d), interp_state(tr, t_d), ext)) feat["tracked_at_departure"] = bool(tr[0, 0] <= t_d) # Was the other actor parked and then started (scenario-triggered)? sp = [speed_at(tr, t) for t in ts[ts > ts[0] + 0.3]] if len(ts) > 3 else [] feat["other_started_from_rest"] = bool(sp and min(sp[: max(1, len(sp) // 2)]) < 0.3 and max(sp) > 3) return feat MSG_RE = re.compile(r"type=(\S+) and id=(\d+) at \(x=([-\d.]+), y=([-\d.]+)") def collision_time(d, other_id, x, y): """Recorder collision time with this actor if logged, else when the ego passed the reported location.""" coll = d["collisions"] hit = coll[coll[:, 1] == other_id] if len(hit): return float(hit[0, 0]) hero = d["hero"] dist = np.hypot(hero[:, 1] - x, hero[:, 2] - y) close = np.where(dist < 1.0)[0] return float(hero[close[0], 0] if len(close) else hero[np.argmin(dist), 0]) def classify_collision(f): lx, ly = f.get("other_rel_xy", (None, None)) if lx is None: return "unknown" rh = abs(f.get("rel_heading", 0)) if f["other_type"].startswith("walker."): return "pedestrian" if lx > 0 and f.get("other_speed") is not None and f["other_speed"] < 0.5: return "ego hits stationary vehicle" if lx < -1.5 and rh < 45: return "rear-ended by other" if lx > 1.5 and rh < 45: return "ego hits vehicle ahead (same direction)" if rh > 135 and abs(ly) < 3.0: return "head-on" if 45 <= rh <= 135 or (f.get("ego_in_junction") and rh > 30): return "crossing" return "side-swipe / lane change" def main(): ap = argparse.ArgumentParser() ap.add_argument("--merged", required=True) ap.add_argument("--routes", required=True) ap.add_argument("--npz-dir", required=True) ap.add_argument("--extents", required=True) ap.add_argument("--out", required=True) args = ap.parse_args() extents = {k: tuple(v) for k, v in json.load(open(args.extents)).items()} meta = {} for r in ET.parse(args.routes).iter("route"): meta[r.attrib["id"]] = {"town": r.attrib["town"], "scenario": [s.attrib["type"] for s in r.iter("scenario")][0]} recs = json.load(open(args.merged))["_checkpoint"]["records"] report = [] for rec in recs: rid = rec["route_id"].split("_")[1] entry = {"route": rid, **meta[rid], "status": rec["status"], "score": rec["scores"]["score_composed"], "success": is_success(rec), "infractions": {k: v for k, v in rec["infractions"].items() if v and k != "min_speed_infractions"}} if not entry["success"]: npz = Path(args.npz_dir) / f"RouteScenario_{rid}_rep0.npz" if npz.exists(): d = np.load(npz, allow_pickle=False) feats = [] for kind in ("collisions_vehicle", "collisions_pedestrian", "collisions_layout"): for msg in rec["infractions"].get(kind, []): m = MSG_RE.search(msg) if not m: continue otype, oid, cx, cy = m.group(1), int(m.group(2)), float(m.group(3)), float(m.group(4)) t_c = collision_time(d, oid, cx, cy) others = d["others"] if kind != "collisions_layout" and np.any(others[:, 1] == oid): f = collision_features(d, meta[rid]["town"], extents, t_c, oid) f["class"] = classify_collision(f) else: f = {"t": round(t_c, 2), "other_type": otype, "class": "static object / layout", "ego_speed": round(speed_at(d["hero"], t_c - 0.1), 2)} f["kind"] = kind f["other_id"] = oid feats.append(f) entry["collisions"] = feats entry["duration"] = round(float(d["hero"][-1, 0]), 1) else: entry["collisions"] = "no recorder log" report.append(entry) json.dump(report, open(args.out, "w"), indent=1) n_fail = sum(not e["success"] for e in report) print(f"{len(report)} routes, {len(report) - n_fail} success, {n_fail} failed -> {args.out}") if __name__ == "__main__": main()