U-EASWS / Processing_Code /annotate_interactions.py
zhangyeye123's picture InterestingITS's picture
Duplicate from InterestingITS/U-EASWS
166c438
Raw History Blame Contribute Delete
7.67 kB
"""Annotate all supplied candidate pairs using existing calibrated PR parameters."""
import numpy as np
import pandas as pd
from _common import lane_direction, 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"])
lane_direction(basic)
unique(basic, ["Frame", "Ego_Vehicle_ID"])
if "Source_ID" in basic and (basic.Source_ID.isna().any() or 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="Released observation-group Basic CSV or single-source Basic CSV, with final metric coordinates")
p.add_argument("--pairs", required=True, help="Full candidate-pair CSV generated by generate_vehicle_pairs.py")
p.add_argument("--parameters", required=True, help="Scenario/source PR parameter CSV generated by fit_pr_parameters.py")
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()