U-EASWS / Principal Processing Code /annotate_risk.py
InterestingITS's picture
Upload 11 files
cf2bed9 verified
Raw History Blame Contribute Delete
6.4 kB
"""Source-compatible TTC/DRAC and lane-change-event PET; see documented limitations."""
import warnings
import numpy as np
import pandas as pd
from _common import numeric, parser, read_csv, require, save_csv, unique
def crossing_time(times, xs, target, start, sign):
indexes = np.flatnonzero(times >= start)
if len(indexes) < 2:
return None
signed = (xs - target) * sign
for k in range(indexes[0], len(times) - 1):
if signed[k] >= 0:
return times[k]
if signed[k + 1] >= 0:
return times[k] - signed[k] / (signed[k + 1] - signed[k]) * (times[k + 1] - times[k])
return None
def annotate(df, drac_cap=15.0, fallback_length=None):
df = df.copy()
require(df, ["Lane number", "Direction", "Vehicle_Length_m"])
numeric(df, ["Frame", "Ego_Vehicle_ID"], integer=True)
numeric(df, ["Time_s", "x_center", "v_x"])
unique(df, ["Frame", "Ego_Vehicle_ID"])
if df[["Lane number", "Direction"]].isna().any().any():
raise ValueError("Lane and Direction cannot be missing")
if "Source_ID" in df and df.Source_ID.nunique() != 1:
raise ValueError("Compute risk separately for each source recording")
if drac_cap <= 0 or np.isnan(drac_cap):
raise ValueError("DRAC cap must be positive; use inf for no cap")
lengths = pd.to_numeric(df.Vehicle_Length_m, errors="raise")
if lengths.isna().any():
if fallback_length is None or not np.isfinite(fallback_length) or fallback_length <= 0:
raise ValueError("Missing lengths: supply actual estimates or explicitly opt into a fallback")
warnings.warn(f"Using {fallback_length} m for {lengths.isna().sum()} missing length rows")
lengths = lengths.fillna(fallback_length)
if not np.isfinite(lengths).all() or lengths.le(0).any():
raise ValueError("Lengths must be positive and finite")
df["_length"] = lengths
df = df.sort_values(["Ego_Vehicle_ID", "Frame"]).reset_index(drop=True)
grouped = df.groupby("Ego_Vehicle_ID", sort=False)
if grouped._length.nunique().gt(1).any() or grouped.Direction.nunique().gt(1).any():
raise ValueError("Length and Direction must be constant within each trajectory")
if grouped.Frame.diff().dropna().ne(1).any():
raise ValueError("PET requires gap-filled consecutive trajectory frames")
if grouped.Time_s.diff().dropna().le(0).any() or df.groupby("Frame").Time_s.nunique().gt(1).any():
raise ValueError("Inconsistent physical times")
previous = grouped["Lane number"].shift()
df["_cutin"] = previous.notna() & previous.ne(df["Lane number"])
cache = {vid: (g.Time_s.to_numpy(), g.x_center.to_numpy()) for vid, g in grouped}
parts = []
for _, group in df.groupby(["Frame", "Direction"], sort=False):
group = group.copy().reset_index(drop=True)
n = len(group)
x, v = group.x_center.to_numpy(), group.v_x.to_numpy()
lane, ids = group["Lane number"].to_numpy(), group.Ego_Vehicle_ID.to_numpy()
length, times = group._length.to_numpy(), group.Time_s.to_numpy()
ttc, pet, drac = np.full(n, np.inf), np.full(n, np.nan), np.zeros(n)
target_ttc, target_pet = np.full(n, -1, dtype=np.int64), np.full(n, -1, dtype=np.int64)
for i in range(n):
sign = np.sign(v[i])
if sign == 0:
continue
leaders = np.flatnonzero((lane == lane[i]) & ((x - x[i]) * sign > 0))
if len(leaders):
j = leaders[np.argmin(np.abs(x[leaders] - x[i]))]
clearance = abs(x[j] - x[i]) - (length[i] + length[j]) / 2
closing = abs(v[i]) - abs(v[j])
if clearance > 0 and closing > 0:
ttc[i], drac[i] = clearance / closing, min(closing ** 2 / (2 * clearance), drac_cap)
target_ttc[i] = ids[j]
if group._cutin.iloc[i]:
followers = np.flatnonzero((lane == lane[i]) & ((x[i] - x) * sign > 0))
if not len(followers):
continue
j = followers[np.argmin(np.abs(x[followers] - x[i]))]
clear = crossing_time(*cache[ids[i]], x[i] + sign * length[i] / 2, times[i], sign)
arrive = crossing_time(*cache[ids[j]], x[i] - sign * length[j] / 2, times[i], sign)
if clear is not None and arrive is not None:
value = max(0.0, arrive - clear)
for a, b in [(i, j), (j, i)]:
if np.isnan(pet[a]) or value < pet[a]:
pet[a], target_pet[a] = value, ids[b]
high_pet, high_long = pet < 2.5, (ttc < 3.0) | (drac > 3.0)
target = np.where(high_pet, target_pet,
np.where(high_long, target_ttc, np.where(target_ttc != -1, target_ttc, target_pet)))
group["TTC"], group["PET"], group["DRAC"] = ttc, pet, drac
group["Max_Risk_Target_ID"] = target
group["Risk_Level"] = np.where(high_pet | high_long, "High Risk", "Low Risk")
parts.append(group)
return pd.concat(parts, ignore_index=True).drop(columns=["_length", "_cutin"]).sort_values(
["Ego_Vehicle_ID", "Frame"]).reset_index(drop=True)
def main():
p = parser(__doc__)
p.add_argument("--input", required=True, help="One-source Basic Trajectory CSV with metric lengths")
p.add_argument("--output", required=True, help="New Risk Semantic CSV")
p.add_argument("--fps", type=float, help="Constant source FPS, only if Time_s is absent")
p.add_argument("--drac-cap", type=float, default=15.0, help="Legacy cap in m/s^2; inf changes legacy behavior")
p.add_argument("--fallback-length-m", type=float, help="Explicit legacy imputation, e.g. 5; otherwise fail")
a = p.parse_args()
df = read_csv(a.input)
if "Time_s" not in df:
if a.fps is None or not np.isfinite(a.fps) or a.fps <= 0:
p.error("Provide Time_s or the actual constant --fps; never infer mixed frame rates")
numeric(df, ["Frame"], integer=True)
df["Time_s"] = (df.Frame - df.Frame.min()) / a.fps
elif a.fps is not None:
p.error("Time_s already exists; omit --fps")
print(f"DRAC cap={a.drac_cap}; no-closing TTC=inf; PET is event-level")
save_csv(annotate(df, a.drac_cap, a.fallback_length_m), a.output)
if __name__ == "__main__":
main()