Download Processing_Code/generate_vehicle_pairs.py from InterestingITS/U-EASWS: direct link, hf CLI and curl.
- Browser
- Download file 5.89 kB
-
https://huggingface.co/datasets/InterestingITS/U-EASWS/resolve/main/Processing_Code/generate_vehicle_pairs.py
- Command line
-
hf download hf://datasets/InterestingITS/U-EASWS/Processing_Code/generate_vehicle_pairs.py
-
curl -L -o generate_vehicle_pairs.py https://huggingface.co/datasets/InterestingITS/U-EASWS/resolve/main/Processing_Code/generate_vehicle_pairs.py
5.89 kB
| """Generate directed same-direction pairs and the author's relative-velocity local coordinates.""" | |
| import json | |
| from pathlib import Path | |
| import numpy as np | |
| import pandas as pd | |
| from scipy.spatial import cKDTree | |
| from _common import numeric, output_path, parser, read_csv, require, unique, preflight_outputs | |
| PAIR_COLUMNS = ["Frame", "EV_Vehicle_ID", "POV_Vehicle_ID", "x_local", "y_local", "v_rel", "cangle", | |
| "cangle_deg", "Distance_m", "Angle_Defined"] | |
| def iter_pairs(basic, distance_threshold=50.0, min_distance=0.5, x_column="x_center", y_column="y_center", audit=None): | |
| basic = basic.copy() | |
| if not np.isfinite([distance_threshold, min_distance]).all() or not 0 <= min_distance < distance_threshold: | |
| raise ValueError("Require 0 <= min_distance < distance_threshold") | |
| numeric(basic, ["Frame", "Ego_Vehicle_ID"], integer=True) | |
| numeric(basic, [x_column, y_column, "v_x", "v_y"]) | |
| require(basic, ["Direction"]) | |
| unique(basic, ["Frame", "Ego_Vehicle_ID"]) | |
| if not basic.Direction.isin(["Left", "Right"]).all(): | |
| raise ValueError("Direction must be Left or Right") | |
| if "Source_ID" in basic and (basic.Source_ID.isna().any() or basic.Source_ID.nunique() != 1): | |
| raise ValueError("Process one synchronized source recording at a time") | |
| if "Time_s" in basic: | |
| numeric(basic, ["Time_s"]) | |
| if basic.groupby("Frame").Time_s.nunique().gt(1).any(): | |
| raise ValueError("A frame must represent a single physical time") | |
| stats = audit if audit is not None else {} | |
| stats.update(input_rows=len(basic), output_pairs=0, zero_relative_velocity_pairs=0, undefined_heading_angle_pairs=0, | |
| max_distance_m=distance_threshold, max_distance_inclusive=False, min_distance_m=min_distance, | |
| min_distance_inclusive=True, position_difference="POV-EV", velocity_difference="EV-POV") | |
| for (frame, direction), group in basic.groupby(["Frame", "Direction"], sort=True): | |
| if len(group) < 2: | |
| continue | |
| group = group.sort_values("Ego_Vehicle_ID") | |
| xy = group[[x_column, y_column]].to_numpy(float) | |
| undirected = cKDTree(xy).query_pairs(distance_threshold, output_type="ndarray") | |
| if not len(undirected): | |
| continue | |
| indexes = np.concatenate([undirected, undirected[:, ::-1]]) | |
| i, j = indexes.T | |
| delta = xy[j] - xy[i] | |
| distance = np.linalg.norm(delta, axis=1) | |
| velocity = group[["v_x", "v_y"]].to_numpy(float) | |
| dv = velocity[i] - velocity[j] | |
| relative = np.linalg.norm(dv, axis=1) | |
| eligible = (distance >= min_distance) & (distance < distance_threshold) | |
| stats["zero_relative_velocity_pairs"] += int((eligible & (relative == 0)).sum()) | |
| keep = eligible & (relative != 0) | |
| i, j, delta, dv, distance, relative = i[keep], j[keep], delta[keep], dv[keep], distance[keep], relative[keep] | |
| if not len(i): | |
| continue | |
| vi, vj = velocity[i], velocity[j] | |
| cross = vi[:, 0] * vj[:, 1] - vj[:, 0] * vi[:, 1] | |
| dot = np.sum(vi * vj, axis=1) | |
| angle = -np.degrees(np.arctan2(cross, dot)) | |
| defined = (np.linalg.norm(vi, axis=1) > 0) & (np.linalg.norm(vj, axis=1) > 0) | |
| # Preserve the uploaded atan2(0,0)=0 convention; expose the undefined heading explicitly. | |
| stats["undefined_heading_angle_pairs"] += int((~defined).sum()) | |
| ids = group.Ego_Vehicle_ID.to_numpy() | |
| out = pd.DataFrame({"Frame": frame, "EV_Vehicle_ID": ids[i], "POV_Vehicle_ID": ids[j], | |
| "x_local": (dv[:, 1] * delta[:, 0] - dv[:, 0] * delta[:, 1]) / relative, | |
| "y_local": np.sum(dv * delta, axis=1) / relative, | |
| "v_rel": relative, "cangle": ((np.abs(angle) >= 5) & (np.abs(angle) <= 175)).astype(int), | |
| "cangle_deg": angle, "Distance_m": distance, "Angle_Defined": defined}) | |
| stats["output_pairs"] += len(out) | |
| yield out.sort_values(["EV_Vehicle_ID", "POV_Vehicle_ID"]).reset_index(drop=True) | |
| def generate_pairs(basic, **kwargs): | |
| parts = list(iter_pairs(basic, **kwargs)) | |
| return pd.concat(parts, ignore_index=True) if parts else pd.DataFrame(columns=PAIR_COLUMNS) | |
| def main(): | |
| p = parser(__doc__) | |
| p.add_argument("--input", required=True, help="Released observation-group Basic CSV or single-source Basic CSV; positions in meters") | |
| p.add_argument("--output", required=True, help="New frame-sorted directed pair CSV") | |
| p.add_argument("--audit", required=True, help="New JSON counts and conventions") | |
| p.add_argument("--x-column", default="x_center", help="Metric longitudinal coordinate column; x_reconstructed for older reconstruction tables") | |
| p.add_argument("--y-column", default="y_center", help="Metric lateral coordinate column; y_reconstructed for older reconstruction tables") | |
| p.add_argument("--max-distance-m", type=float, default=50.) | |
| p.add_argument("--min-distance-m", type=float, default=0.5, help="Minimum center-distance cutoff in meters") | |
| a = p.parse_args() | |
| preflight_outputs(a.output, a.audit) | |
| if Path(a.audit).resolve() == Path(a.output).resolve() or Path(a.audit).exists(): | |
| raise FileExistsError("Choose distinct new output and audit filenames") | |
| stats = {} | |
| with output_path(a.output) as temporary: | |
| first = True | |
| for part in iter_pairs(read_csv(a.input), a.max_distance_m, a.min_distance_m, a.x_column, a.y_column, stats): | |
| part.to_csv(temporary, mode="w" if first else "a", header=first, index=False) | |
| first = False | |
| if first: | |
| pd.DataFrame(columns=PAIR_COLUMNS).to_csv(temporary, index=False) | |
| with output_path(a.audit) as temporary: | |
| Path(temporary).write_text(json.dumps(stats, indent=2, allow_nan=False), encoding="utf-8") | |
| if __name__ == "__main__": | |
| main() | |