Download Principal Processing Code/annotate_interactions.py from InterestingITS/U-EASWS: direct link, hf CLI and curl.
- Browser
- Download file 7.53 kB
-
https://huggingface.co/datasets/InterestingITS/U-EASWS/resolve/main/Principal%20Processing%20Code/annotate_interactions.py
- Command line
-
hf download 'hf://datasets/InterestingITS/U-EASWS/Principal Processing Code/annotate_interactions.py'
-
curl -L -o annotate_interactions.py https://huggingface.co/datasets/InterestingITS/U-EASWS/resolve/main/Principal%20Processing%20Code/annotate_interactions.py
7.53 kB
| """Annotate all supplied candidate pairs using existing calibrated PR parameters.""" | |
| import numpy as np | |
| import pandas as pd | |
| from _common import numeric, output_path, parser, read_csv, require, unique | |
| PARAMETERS = [f"{name}_{side}" for name in ["rx", "ry", "bx", "by"] for side in ["plus", "minus"]] | |
| PAIR_COLUMNS = ["Frame", "EV_Vehicle_ID", "POV_Vehicle_ID", "x_local", "y_local", "v_rel", "cangle"] | |
| SEMANTICS = ["Interaction_Target_ID", "x_local", "y_local", "v_rel", "Interaction Strength", | |
| "Is Interacting", "Interaction Type"] | |
| def validate_parameters(params): | |
| params = params.copy() | |
| numeric(params, ["cangle"], integer=True) | |
| numeric(params, ["round_v"] + PARAMETERS) | |
| unique(params, ["cangle", "round_v"]) | |
| if not params.cangle.isin([0, 1]).all() or params[PARAMETERS].le(0).any().any(): | |
| raise ValueError("cangle must be binary and all PR parameters must be positive") | |
| params["round_v"] = params.round_v.astype(float) | |
| return params.sort_values("round_v") | |
| def annotate_pairs(pairs, basic, params, tolerance=None): | |
| pairs = pairs.copy() | |
| numeric(pairs, ["Frame", "EV_Vehicle_ID", "POV_Vehicle_ID", "cangle"], integer=True) | |
| numeric(pairs, ["x_local", "y_local", "v_rel"]) | |
| unique(pairs, ["Frame", "EV_Vehicle_ID", "POV_Vehicle_ID"]) | |
| if (pairs.EV_Vehicle_ID == pairs.POV_Vehicle_ID).any() or not pairs.cangle.isin([0, 1]).all(): | |
| raise ValueError("Invalid pair IDs or cangle; cangle is a binary class, NOT an angle in radians") | |
| if pairs.v_rel.le(0).any() or np.hypot(pairs.x_local, pairs.y_local).gt(50.0 + 1e-6).any(): | |
| raise ValueError("Candidate pairs must have nonzero relative speed and be within 50 m") | |
| pairs["round_v"] = pairs.v_rel.round(1).astype(float) | |
| joined = pd.merge_asof(pairs.sort_values("round_v"), params, on="round_v", by="cangle", | |
| direction="nearest", tolerance=tolerance) | |
| if joined[PARAMETERS].isna().any().any(): | |
| raise ValueError("Missing calibrated parameters: do not silently discard candidate pairs") | |
| pr_exponent = np.zeros(len(joined)) | |
| for axis in ["x", "y"]: | |
| sign = np.sign(joined[f"{axis}_local"]) | |
| scale = (1 + sign) / 2 * joined[f"r{axis}_plus"] + (1 - sign) / 2 * joined[f"r{axis}_minus"] | |
| shape = (1 + sign) / 2 * joined[f"b{axis}_plus"] + (1 - sign) / 2 * joined[f"b{axis}_minus"] | |
| pr_exponent += np.abs(joined[f"{axis}_local"] / scale) ** shape | |
| joined["Interaction Strength"] = np.exp(-pr_exponent) | |
| joined["Is Interacting"] = (joined["Interaction Strength"] > np.exp(-1)).astype(int) | |
| lookup = basic.set_index(["Frame", "Ego_Vehicle_ID"]) | |
| lanes, directions = [], [] | |
| for role in ["EV", "POV"]: | |
| keys = pd.MultiIndex.from_arrays([joined.Frame, joined[f"{role}_Vehicle_ID"]]) | |
| values = lookup.reindex(keys) | |
| if values[["Lane number", "Direction"]].isna().any().any(): | |
| raise ValueError("Pair vehicle/frame lacks a valid basic trajectory, lane, or direction") | |
| lanes.append(values["Lane number"].to_numpy()) | |
| directions.append(values.Direction.to_numpy()) | |
| if not np.equal(*directions).all(): | |
| raise ValueError("Only same-direction candidate pairs are supported") | |
| joined["Interaction Type"] = np.where(joined.cangle.eq(1), "Lane Changing/Weaving", | |
| np.where(np.equal(*lanes), "Car Following", "Parallel Driving")) | |
| joined = joined.rename(columns={"EV_Vehicle_ID": "Ego_Vehicle_ID", "POV_Vehicle_ID": "Interaction_Target_ID"}) | |
| return joined[["Frame", "Ego_Vehicle_ID"] + SEMANTICS] | |
| def process(basic, pairs_path, params, output, chunksize=500000, tolerance=None): | |
| basic = basic.copy() | |
| numeric(basic, ["Frame", "Ego_Vehicle_ID"], integer=True) | |
| require(basic, ["Lane number", "Direction", "x_center", "y_center"]) | |
| unique(basic, ["Frame", "Ego_Vehicle_ID"]) | |
| if "Source_ID" in basic and basic.Source_ID.nunique() != 1: | |
| raise ValueError("Run separately for each source recording") | |
| if set(SEMANTICS) & set(basic.columns): | |
| raise ValueError("Input must be Basic Trajectory data without existing interaction fields") | |
| params = validate_parameters(params) | |
| seen, first, count = set(), True, 0 | |
| last_frame, boundary_pairs = None, set() | |
| # CSV blocks are written immediately; no list of all annotated blocks is retained. | |
| with output_path(output) as temporary, pd.read_csv(pairs_path, usecols=PAIR_COLUMNS, chunksize=chunksize) as reader: | |
| for chunk in reader: | |
| if chunk.empty: | |
| continue | |
| numeric(chunk, ["Frame", "EV_Vehicle_ID", "POV_Vehicle_ID"], integer=True) | |
| if not chunk.Frame.is_monotonic_increasing or (last_frame is not None and chunk.Frame.iloc[0] < last_frame): | |
| raise ValueError("Candidate CSV must be sorted by Frame for cross-block duplicate validation") | |
| if last_frame is not None: | |
| overlap = chunk.loc[chunk.Frame.eq(last_frame), ["EV_Vehicle_ID", "POV_Vehicle_ID"]] | |
| if boundary_pairs.intersection(map(tuple, overlap.to_numpy())): | |
| raise ValueError("Duplicate candidate pair across CSV blocks") | |
| tail = chunk.loc[chunk.Frame.eq(chunk.Frame.iloc[-1]), ["EV_Vehicle_ID", "POV_Vehicle_ID"]] | |
| tail_pairs = set(map(tuple, tail.to_numpy())) | |
| boundary_pairs = boundary_pairs | tail_pairs if last_frame == chunk.Frame.iloc[-1] else tail_pairs | |
| last_frame = chunk.Frame.iloc[-1] | |
| annotations = annotate_pairs(chunk, basic, params, tolerance) | |
| seen.update(zip(annotations.Frame, annotations.Ego_Vehicle_ID)) | |
| result = annotations.merge(basic, on=["Frame", "Ego_Vehicle_ID"], how="left", validate="many_to_one") | |
| result = result[list(basic.columns) + SEMANTICS] | |
| result.to_csv(temporary, mode="w" if first else "a", header=first, index=False) | |
| first, count = False, count + len(result) | |
| absent = basic.loc[[key not in seen for key in zip(basic.Frame, basic.Ego_Vehicle_ID)]].copy() | |
| absent["Interaction_Target_ID"] = -1 | |
| absent[["x_local", "y_local", "v_rel"]] = np.nan | |
| absent["Interaction Strength"], absent["Is Interacting"], absent["Interaction Type"] = 0.0, 0, "Safe" | |
| absent = absent[list(basic.columns) + SEMANTICS] | |
| absent.to_csv(temporary, mode="w" if first else "a", header=first, index=False) | |
| count += len(absent) | |
| print(f"Saved {count:,} rows; all candidate pairs retained regardless of PR threshold") | |
| def main(): | |
| p = parser(__doc__) | |
| p.add_argument("--input", required=True, help="One-source Basic Trajectory CSV, final metric coordinates") | |
| p.add_argument("--pairs", required=True, help="Existing validated candidate-pair CSV, not generated here") | |
| p.add_argument("--parameters", required=True, help="Existing scenario-specific MLE calibration CSV") | |
| p.add_argument("--output", required=True, help="New Interaction Semantic CSV") | |
| p.add_argument("--chunksize", type=int, default=500000) | |
| p.add_argument("--speed-tolerance", type=float, help="Optional nearest-bin tolerance; omitted preserves source rule") | |
| a = p.parse_args() | |
| if a.chunksize < 1 or (a.speed_tolerance is not None and a.speed_tolerance < 0): | |
| p.error("Invalid chunk size or speed tolerance") | |
| process(read_csv(a.input), a.pairs, read_csv(a.parameters), a.output, a.chunksize, a.speed_tolerance) | |
| if __name__ == "__main__": | |
| main() | |