File size: 8,711 Bytes
166c438
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Compute TTC/DRAC and lane-change-event PET from metric trajectories."""
import warnings

import numpy as np
import pandas as pd

from _common import lane_direction, numeric, parser, read_csv, require, save_csv, unique


def time_from_intervals(df):
    """Recover recording-relative time from the released frame-interval field."""
    df = df.copy()
    numeric(df, ["Frame", "Ego_Vehicle_ID"], integer=True)
    unique(df, ["Frame", "Ego_Vehicle_ID"])
    require(df, ["Delta_t_s"])
    if "Time_Reference_ID" in df:
        raise ValueError("Resolve existing Time_Reference_ID before deriving a new time reference")
    delta = pd.to_numeric(df.Delta_t_s, errors="raise")
    observed = delta.notna()
    if not np.isfinite(delta[observed]).all() or delta[observed].le(0).any():
        raise ValueError("Observed Delta_t_s values must be finite and positive")
    ordered = df.assign(_delta=delta).sort_values(["Ego_Vehicle_ID", "Frame"])
    differences = ordered.groupby("Ego_Vehicle_ID").Frame.diff()
    if differences.dropna().ne(1).any() or ordered.loc[differences.notna(), "_delta"].isna().any():
        raise ValueError("Require consecutive vehicle frames with Delta_t_s after each first record")
    intervals = df.loc[observed, ["Frame"]].assign(_delta=delta[observed]).groupby("Frame")._delta.agg(["min", "max"])
    if not np.isclose(intervals["min"], intervals["max"], rtol=1e-8, atol=1e-10).all():
        raise ValueError("Conflicting Delta_t_s values for the same processed frame")
    times, references = {}, {}
    previous, elapsed, reference = None, 0.0, -1
    for frame in np.sort(df.Frame.unique()):
        frame = int(frame)
        if previous is None or frame != previous + 1 or frame not in intervals.index:
            reference += 1
            elapsed = 0.0
        else:
            elapsed += float(intervals.loc[frame, "min"])
        times[frame], references[frame] = elapsed, reference
        previous = frame
    df["Time_s"] = df.Frame.map(times)
    df["Time_Reference_ID"] = df.Frame.map(references)
    if df.groupby("Ego_Vehicle_ID").Time_Reference_ID.nunique().gt(1).any():
        raise ValueError("A vehicle spans disconnected time references; inspect its frame/interval mapping")
    return df


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"])
    lane_direction(df)
    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.isna().any() or 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="Released observation-group Basic CSV or single-source Basic CSV, with metric lengths")
    p.add_argument("--output", required=True, help="New Risk Semantic CSV")
    p.add_argument("--fps", type=float, help="Explicit constant source FPS; otherwise use Time_s or released Delta_t_s")
    p.add_argument("--drac-cap", type=float, default=15.0, help="DRAC cap in m/s^2 (default: 15)")
    p.add_argument("--fallback-length-m", type=float, help="Optional replacement length in meters for records with missing length")
    a = p.parse_args()
    df = read_csv(a.input)
    if "Time_s" not in df:
        if a.fps is not None:
            if not np.isfinite(a.fps) or a.fps <= 0:
                p.error("Provide a finite positive constant --fps")
            numeric(df, ["Frame"], integer=True)
            df["Time_s"] = (df.Frame - df.Frame.min()) / a.fps
        elif "Delta_t_s" in df:
            df = time_from_intervals(df)
        else:
            p.error("Provide Time_s, released Delta_t_s, or the actual constant --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()