Download Processing_Code/reconstruct_trajectories.py from InterestingITS/U-EASWS: direct link, hf CLI and curl.
- Browser
- Download file 6.71 kB
-
https://huggingface.co/datasets/InterestingITS/U-EASWS/resolve/main/Processing_Code/reconstruct_trajectories.py
- Command line
-
hf download hf://datasets/InterestingITS/U-EASWS/Processing_Code/reconstruct_trajectories.py
-
curl -L -o reconstruct_trajectories.py https://huggingface.co/datasets/InterestingITS/U-EASWS/resolve/main/Processing_Code/reconstruct_trajectories.py
6.71 kB
| """Metric screening, PCHIP/linear gap filling, sEMA and physical kinematics.""" | |
| import numpy as np | |
| import pandas as pd | |
| from _common import lane_direction, numeric, parser, read_csv, require, save_csv, unique, preflight_outputs | |
| from filter_trajectory_outliers import split_tracks | |
| def sema(values, fps, window_s=0.6): | |
| values = np.asarray(values, dtype=float) | |
| delta = fps * window_s | |
| if not np.isfinite(delta) or delta <= 0: | |
| raise ValueError("FPS and smoothing window must be positive") | |
| result = np.empty(len(values)) | |
| for i in range(len(values)): | |
| radius = int(min(3 * delta, i, len(values) - 1 - i)) | |
| weights = np.exp(-np.abs(np.arange(-radius, radius + 1)) / delta) | |
| result[i] = np.dot(values[i - radius:i + radius + 1], weights) / weights.sum() | |
| return result | |
| def kinematics(position, dt): | |
| position = np.asarray(position, dtype=float) | |
| velocity, acceleration = np.zeros(len(position)), np.zeros(len(position)) | |
| if len(position) < 2: | |
| return velocity, acceleration | |
| velocity[1:-1] = (position[2:] - position[:-2]) / (2 * dt) | |
| velocity[0], velocity[-1] = (position[1] - position[0]) / dt, (position[-1] - position[-2]) / dt | |
| if len(position) > 2: | |
| acceleration[1:-1] = (position[2:] - 2 * position[1:-1] + position[:-2]) / dt ** 2 | |
| acceleration[0] = (velocity[1] - velocity[0]) / dt | |
| acceleration[-1] = (velocity[-1] - velocity[-2]) / dt | |
| return velocity, acceleration | |
| def fill_lane(series): | |
| if not series.notna().any(): | |
| raise ValueError("No lane observations for a vehicle") | |
| return series.ffill().bfill() | |
| def interpolate_coordinates(series): | |
| count = series.notna().sum() | |
| if count < 2: | |
| raise ValueError("At least two valid coordinate observations are required") | |
| method = "linear" if count == 2 else "pchip" | |
| return series.interpolate(method=method, limit_direction="both") | |
| def reconstruct(df, fps, source, window_s=0.6, id_offset=0, frame_offset=0, | |
| time_offset=0.0, merge_x=None, diverge_x=None, return_audit=False): | |
| if fps <= 0 or not np.isfinite(fps) or not np.isfinite(time_offset): | |
| raise ValueError("Finite positive FPS and finite time offset required") | |
| df = df.copy() | |
| require(df, ["Lane number", "Direction"]) | |
| lane_direction(df, allow_missing=True) | |
| numeric(df, ["Frame", "Vehicle_ID"], integer=True) | |
| numeric(df, ["x_center", "y_center"]) | |
| unique(df, ["Frame", "Vehicle_ID"]) | |
| if "Source_ID" in df and not df.Source_ID.eq(source).all(): | |
| raise ValueError("Reconstruct one constant-FPS source video at a time") | |
| first_frame = df.Frame.min() | |
| df, rejected, audit = split_tracks(df, fps) | |
| parts = [] | |
| for vid, group in df.groupby("Vehicle_ID", sort=True): | |
| group = group.sort_values("Frame").set_index("Frame") | |
| if group.Direction.dropna().nunique() != 1 or not group["Lane number"].notna().any(): | |
| raise ValueError(f"Missing/changing Direction or missing lanes for vehicle {vid}") | |
| if not group.Direction.dropna().isin(["Left", "Right"]).all(): | |
| raise ValueError(f"Direction must be Left or Right for vehicle {vid}") | |
| frames = np.arange(group.index.min(), group.index.max() + 1) | |
| expanded = group.reindex(frames) | |
| out = pd.DataFrame({"Source_ID": source, "Original_Vehicle_ID": vid, | |
| "Original_Frame": frames, "Frame": frames + frame_offset, | |
| "Ego_Vehicle_ID": int(vid) + id_offset, | |
| "Time_s": time_offset + (frames - first_frame) / fps}) | |
| out["Delta_t_s"] = np.r_[np.nan, np.full(len(frames) - 1, 1 / fps)] | |
| out["Lane number"] = fill_lane(expanded["Lane number"]).to_numpy() | |
| out["Direction"] = expanded.Direction.ffill().bfill().to_numpy() | |
| for axis in ("x", "y"): | |
| filled = interpolate_coordinates(expanded[f"{axis}_center"]) | |
| if filled.isna().any(): | |
| raise ValueError(f"Unfilled coordinates: vehicle {vid}") | |
| position = sema(filled.to_numpy(), fps, window_s) | |
| out[f"{axis}_center"] = position | |
| out[f"v_{axis}"], out[f"a_{axis}"] = kinematics(position, 1 / fps) | |
| if merge_x is not None: | |
| out["Dist_to_Merge_m"] = np.abs(out.x_center - merge_x) | |
| if diverge_x is not None: | |
| out["Dist_to_Diverge_m"] = np.abs(out.x_center - diverge_x) | |
| parts.append(out) | |
| out = pd.concat(parts, ignore_index=True) if parts else pd.DataFrame() | |
| print(f"Rejected {int(audit.Rejected.sum())} tracks; review audit for reasons; lane filling=ffill/bfill") | |
| if return_audit: | |
| return out, rejected, audit | |
| if out.empty: | |
| raise ValueError("No trajectories remain after screening") | |
| return out | |
| def main(): | |
| p = parser(__doc__) | |
| p.add_argument("--input", required=True, help="Metric trajectory CSV with lane/direction annotations") | |
| p.add_argument("--output", required=True, help="New reconstructed metric trajectory CSV") | |
| p.add_argument("--source", required=True, help="Source video identifier") | |
| p.add_argument("--fps", required=True, type=float, help="Actual constant source frame rate") | |
| p.add_argument("--rejected", required=True, help="New rejected metric-record CSV for review") | |
| p.add_argument("--audit", required=True, help="New per-vehicle screening summary CSV") | |
| p.add_argument("--window-s", type=float, default=0.6) | |
| p.add_argument("--id-offset", type=int, default=0, help="Explicit offset for unique IDs across sources") | |
| p.add_argument("--frame-offset", type=int, default=0, help="Frame-label offset, not elapsed time") | |
| p.add_argument("--time-offset", type=float, default=0.0, help="Seconds at first input source frame") | |
| p.add_argument("--merge-x-m", type=float, help="Measured merge reference x in the same metric system") | |
| p.add_argument("--diverge-x-m", type=float, help="Measured diverge reference x in the same metric system") | |
| a = p.parse_args() | |
| preflight_outputs(a.output, a.rejected, a.audit) | |
| out, rejected, audit = reconstruct(read_csv(a.input), a.fps, a.source, a.window_s, | |
| a.id_offset, a.frame_offset, a.time_offset, | |
| a.merge_x_m, a.diverge_x_m, return_audit=True) | |
| save_csv(audit, a.audit) | |
| save_csv(rejected, a.rejected) | |
| if out.empty: | |
| raise ValueError("All trajectories rejected; review saved audit; no reconstruction file written") | |
| save_csv(out, a.output) | |
| if __name__ == "__main__": | |
| main() | |