InterestingITS commited on
Commit
4417cb3
·
verified ·
1 Parent(s): 770dc3c

Delete Principal Processing Code

Browse files
Principal Processing Code/README.md DELETED
@@ -1,102 +0,0 @@
1
- # U-EASWS principal processing code
2
-
3
- This partial processing-code package implements coordinate transformation, metric trajectory screening and reconstruction, six-column vehicle-length estimation, and risk/interaction annotation. It requires source-specific inputs and calibration; it is not an end-to-end reproduction of all released data.
4
-
5
- ## Installation
6
-
7
- Python 3.12 is used for testing. Keep the Python files together and install the dependencies:
8
-
9
- ```bash
10
- python -m pip install -r requirements.txt
11
-
12
- ```
13
-
14
- All processing scripts provide `--help`. Arguments describe required inputs; replace the uppercase filenames and source identifiers below with actual values. Outputs must have new filenames; existing files are not overwritten.
15
-
16
- ## Files and processing order
17
-
18
- | File | Required input | Output |
19
- | --- | --- | --- |
20
- | `coordinate_transform.py` | Source pixel trajectories and completed calibration JSON | Metric centers with source identity |
21
- | `reconstruct_trajectories.py` | Metric centers with verified lane/direction annotations and source FPS | Screened, gap-filled, smoothed trajectories; rejected records; per-vehicle audit |
22
- | `filter_trajectory_outliers.py` | Metric centers and FPS | The same screening as reconstruction, available independently |
23
- | `estimate_vehicle_length.py` | Six-column raw detections and the same calibration | Fixed per-vehicle lengths and quality fields |
24
- | `merge_vehicle_lengths.py` | Reconstructed trajectories and per-vehicle lengths | Basic trajectories with `Vehicle_Length_m` |
25
- | `annotate_risk.py` | Basic trajectories with timing and per-vehicle lengths | TTC, PET, DRAC and risk labels |
26
- | `annotate_interactions.py` | Basic trajectories, precomputed candidate pairs and calibrated PR parameters | Candidate-pair interaction annotations |
27
- | `_common.py` | Shared helper | CSV validation and output handling |
28
- | `calibration_template.json` | User-supplied measurements | Configuration structure without scene-specific measurements |
29
-
30
- Screening is automatically performed by reconstruction **after conversion to meters, before interpolation and smoothing**. Do not run the old 100-observation pixel-window filter first. The independent screening script is optional, not an additional default stage. Vehicle-length estimation is a separate branch using the raw detections; join lengths only to retained trajectories using source and original vehicle ID.
31
-
32
- ```bash
33
- python coordinate_transform.py --input RAW_DETECTION_DATA.csv --calibration SCENE_CALIBRATION.json --source SOURCE_VIDEO_KEY --output METRIC_TRAJECTORIES.csv
34
- python reconstruct_trajectories.py --input METRIC_TRAJECTORIES_WITH_LANES.csv --fps SOURCE_FPS --source SOURCE_VIDEO_KEY --output RECONSTRUCTED_TRAJECTORIES.csv --rejected REJECTED_TRAJECTORIES.csv --audit SCREENING_SUMMARY.csv
35
- python estimate_vehicle_length.py --input RAW_DETECTION_DATA.csv --calibration SCENE_CALIBRATION.json --source SOURCE_VIDEO_KEY --output VEHICLE_LENGTH_ESTIMATES.csv
36
- python merge_vehicle_lengths.py --input RECONSTRUCTED_TRAJECTORIES.csv --lengths VEHICLE_LENGTH_ESTIMATES.csv --output BASIC_TRAJECTORY_DATA.csv
37
- python annotate_risk.py --input BASIC_TRAJECTORY_DATA.csv --output RISK_SEMANTIC_DATA.csv
38
- python annotate_interactions.py --input BASIC_TRAJECTORY_DATA.csv --pairs CANDIDATE_PAIRS.csv --parameters PR_PARAMETERS.csv --output INTERACTION_SEMANTIC_DATA.csv
39
- ```
40
-
41
- `SOURCE_FPS` must be replaced with the actual numerical FPS (30 or 60 for these recordings). Supply verified `Lane number` and `Direction` before reconstruction; the six raw columns do not determine them. Each invocation processes one constant-FPS recording. Do not compute risk over independent or simultaneous recordings concatenated as one video.
42
-
43
- ## Six-column vehicle-length input
44
-
45
- Required columns are exactly named `Frame, Vehicle_ID, x_center_px, y_center_px, width_px, height_px`. Frame and vehicle ID must be integers with unique `(Frame, Vehicle_ID)` keys. Center, width and height are in pixels in the same stabilized/cropped view used for calibration. `width_px` and `height_px` are image-axis bounding-box extents, not physical vehicle dimensions. Extra columns are not used for length filtering.
46
-
47
- The estimator needs no confidence scores, image dimensions, corner columns, detector model or videos. It constructs the four corners internally from center +/- half-width/half-height, transforms all four to meters, and takes the longitudinal max-minus-min as each frame's length candidate. This is geometry arithmetic, not re-detection or matching. Candidates with missing/nonfinite coordinates or nonpositive dimensions are excluded. With at least four candidates, a 1.5-IQR filter is applied; Q25 is used as the fixed vehicle length if at least five candidates remain. Otherwise length is missing and quality is `insufficient`. The lateral extent is only a bbox diagnostic.
48
-
49
- Confidence, image-boundary and matching-distance filters are not implemented in this six-column version. Do not claim that they were performed without separate upstream evidence. Metric calibration remains necessary; six pixel columns alone cannot determine lengths in meters. Missing length is not silently replaced with 5 m.
50
-
51
- ## Calibration template
52
-
53
- The JSON contains no actual scene coordinates, distances or source mappings. Copy it for each scene and fill:
54
-
55
- - `master_source`: reference source key, also present under `sources`.
56
- - `origin_px`: `[x, y]` of the physical origin in the master image.
57
- - `reference_segments`: master-image endpoints and measured physical distance in meters; at least one valid segment.
58
- - `sources`: actual source keys; each non-master source needs at least four nondegenerate corresponding `src_points` and `master_points`, in matching order.
59
- - `validation_src`, `validation_master`: optional paired independent checkpoints; retain both as `null` when unavailable. Validation of the physical calibration still remains the user's responsibility.
60
- - `rotation_rad`: set to `0` only for an already horizontally aligned road; the current implementation does not support nonzero rotation or a curved-road Frenet projection.
61
-
62
- Fill all required `null` values, remove unused sources/segments or fill them, and only then set `template_only` to `false`. The untouched template deliberately fails. Previously flagged scene calibrations still require independent review; replacing them with a blank template does not resolve historical calibration issues.
63
-
64
- The scale is the arithmetic mean of physical/pixel distance ratios. Non-master images use RANSAC homography (3-pixel threshold). Metric coordinates subtract the origin and reverse image y; positive metric x follows the horizontally aligned road and positive y points upward. Centers and boxes must use the same calibration. Independent checkpoints, when supplied, produce RMSE and maximum error diagnostics.
65
-
66
- ## Screening and reconstruction
67
-
68
- Thresholds follow the supplied `Reconstruction(5).py`. Let N be the number of observed valid records before interpolation; duration is N/FPS, not elapsed first-to-last frame time. Records must be chronologically sorted for path calculation (the code sorts them).
69
-
70
- | Rule | Condition for rejecting a whole vehicle track |
71
- | --- | --- |
72
- | Short observed duration | N/FPS < 0.5 s |
73
- | Too few observations | N < 15 |
74
- | Suspected low-motion track | N/FPS >= 2 s AND extent diagonal < 1 m AND mean path speed < 0.5 m/s |
75
-
76
- The extent diagonal is `sqrt((max(x)-min(x))**2 + (max(y)-min(y))**2)`, not net start-to-end displacement or maximum pairwise distance. Mean path speed is the sum of distances between consecutive observations divided by N/FPS. All inequalities and the AND relationship are intentional. At 30/60 FPS, N >= 0.5*FPS already implies N >= 15; the 15-observation rule is retained from the source. The default thresholds are visible in `split_tracks`.
77
-
78
- These rules remove short tracks and suspected persistent low-motion detections. They do not explicitly measure movement irregularity, identify every false trajectory, or distinguish a static misdetection from a genuinely stopped vehicle. Noisy oscillating false detections can have a high path-based speed and pass screening. Review `REJECTED_TRAJECTORIES.csv` and `SCREENING_SUMMARY.csv`; they preserve rejection reasons and measured screening features. If every track is rejected, the command saves both review files and stops without writing a reconstructed dataset.
79
-
80
- After screening, missing frames between each vehicle's first and last observation are inserted. Exactly two valid coordinate observations select linear interpolation; three or more select PCHIP; fewer than two fail. Large gaps alone do not select linear interpolation. With the default 15-observation screen and finite input coordinates, two-point whole tracks are rejected before interpolation; the two-point interpolation helper remains implemented but is not normally reached in the full pipeline. No unsupported fallback is silently applied after a PCHIP error.
81
-
82
- Lane and direction use forward fill followed by backward fill. Vehicle identity is held constant within each single-vehicle group; no interpolation crosses vehicle IDs. At least one lane observation and a single nonmissing direction per retained track are required. sEMA uses T=0.6 s and a boundary-limited symmetric 3T window, followed by first/second-order position differences. Final `x_center` and `y_center` are smoothed positions in meters, velocities are m/s and accelerations m/s^2. Invalid numeric rows and duplicate keys fail explicitly; malformed input is not silently dropped.
83
-
84
- `Source_ID`, `Original_Vehicle_ID` and `Original_Frame` preserve lineage. `--id-offset`, `--frame-offset`, and `--time-offset` explicitly control IDs, frame labels and physical time origin. Time is referenced to the earliest input frame before screening. `Delta_t_s` is missing at each track's first record and 1/FPS afterward. This code does not infer historical ID mappings. For Basic tables without lineage use a verified `--mapping` CSV with `Ego_Vehicle_ID, Source_ID, Original_Vehicle_ID` when merging lengths. Optional `--merge-x-m` and `--diverge-x-m` generate absolute longitudinal distances to measured reference cross-sections.
85
-
86
- ## Risk semantics
87
-
88
- Input includes `Frame, Ego_Vehicle_ID, Time_s, Lane number, Direction, x_center, v_x, Vehicle_Length_m`. Per-vehicle length is retained from the existing package. Net clearance is center distance minus half the sum of both vehicle lengths. TTC/DRAC use the nearest same-lane leader; event-level PET uses the cutting-in vehicle's own half-length for clearance and the follower's own half-length for arrival. Required frame sequences are gap-filled and consecutive.
89
-
90
- TTC < 3 s, PET < 2.5 s or DRAC > 3 m/s^2 indicates high risk. DRAC is capped at 15 m/s^2 by default; `--drac-cap inf` changes that behavior. Missing vehicle lengths fail by default; the legacy explicit fallback option remains available but is not used in the commands above. No-closing TTC is `inf`; unavailable PET is missing; DRAC defaults to zero. Nonpositive clearance and zero longitudinal speed do not have an independent collision-state rule, so `Low Risk` is not proof of safety. Negative event gaps are clipped to zero, and PET-high targets have priority. `Max_Risk_Target_ID` is a legacy name, not a severity ranking over all neighboring vehicles. PET uses future trajectory crossings and is not an online prediction.
91
-
92
- ## Interaction semantics and omitted stages
93
-
94
- Pair input requires `Frame, EV_Vehicle_ID, POV_Vehicle_ID, x_local, y_local, v_rel, cangle`, sorted by Frame with unique directed pair/frame keys. Local distances are meters; scalar relative speed is positive and in m/s. Input pairs must be same-direction and within 50 m. `cangle` is a precomputed binary class (0 or 1), not a continuous angle; its upstream derivation must match the intended methodology.
95
-
96
- PR parameters require `cangle, round_v, rx_plus, rx_minus, ry_plus, ry_minus, bx_plus, bx_minus, by_plus, by_minus`, with positive parameters and unique class/bin keys. Relative speed is rounded to one decimal, followed by nearest-bin lookup within class. Optional `--speed-tolerance` limits lookup distance. Missing parameters or vehicle/lane references fail explicitly.
97
-
98
- All supplied candidate pairs receive `Interaction Strength`, `Is Interacting` and `Interaction Type`; PR > exp(-1) controls only the effective-interaction flag, not retention. No-candidate records use target -1, PR 0, flag 0 and legacy type `Safe`; this means no candidate was supplied, not confirmed traffic safety. Output blocks are not necessarily globally sorted. Pair generation, local projection, MLE fitting, stabilization, detector training/tracking and lane annotation are not supplied by this package.
99
-
100
- ## Verification and reuse
101
-
102
- Synthetic tests check implementation behavior; they do not establish false-track detection accuracy or validate all seven real datasets. Changed screening and lane filling can change downstream trajectories, PET and other semantic outputs. Review representative real data before replacing released results. The package contains no private paths or actual scene calibrations, performs no external upload, and does not grant a code license; authors should select one for publication.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Principal Processing Code/_common.py DELETED
@@ -1,69 +0,0 @@
1
- """Shared CSV validation and non-overwriting output helpers."""
2
- import argparse
3
- import os
4
- from contextlib import contextmanager
5
- from pathlib import Path
6
- import tempfile
7
-
8
- import numpy as np
9
- import pandas as pd
10
-
11
-
12
- def parser(description):
13
- return argparse.ArgumentParser(description=description)
14
-
15
-
16
- def require(df, columns):
17
- missing = set(columns) - set(df.columns)
18
- if missing:
19
- raise ValueError(f"Missing columns: {sorted(missing)}")
20
-
21
-
22
- def numeric(df, columns, integer=False):
23
- require(df, columns)
24
- for col in columns:
25
- values = pd.to_numeric(df[col], errors="raise")
26
- if not np.isfinite(values.to_numpy(dtype=float)).all():
27
- raise ValueError(f"Non-finite values in {col}")
28
- if integer:
29
- if not (values == np.floor(values)).all():
30
- raise ValueError(f"Non-integer values in {col}")
31
- values = values.astype("int64")
32
- df[col] = values
33
-
34
-
35
- def unique(df, keys):
36
- require(df, keys)
37
- if df[keys].isna().any().any() or df.duplicated(keys).any():
38
- raise ValueError(f"Missing or duplicate keys: {keys}")
39
-
40
-
41
- def read_csv(path):
42
- df = pd.read_csv(path, encoding="utf-8-sig")
43
- if df.empty:
44
- raise ValueError(f"Empty input: {path}")
45
- return df
46
-
47
-
48
- @contextmanager
49
- def output_path(path):
50
- path = Path(path)
51
- if path.exists():
52
- raise FileExistsError(f"Output exists; choose a new filename: {path}")
53
- path.parent.mkdir(parents=True, exist_ok=True)
54
- handle, temporary = tempfile.mkstemp(prefix=path.name + ".", dir=path.parent)
55
- os.close(handle)
56
- try:
57
- yield temporary
58
- if path.exists():
59
- raise FileExistsError(path)
60
- os.replace(temporary, path)
61
- finally:
62
- if os.path.exists(temporary):
63
- os.unlink(temporary)
64
-
65
-
66
- def save_csv(df, path):
67
- with output_path(path) as temporary:
68
- df.to_csv(temporary, index=False, encoding="utf-8-sig")
69
- print(f"Saved {len(df):,} rows: {path}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Principal Processing Code/annotate_interactions.py DELETED
@@ -1,123 +0,0 @@
1
- """Annotate all supplied candidate pairs using existing calibrated PR parameters."""
2
- import numpy as np
3
- import pandas as pd
4
-
5
- from _common import numeric, output_path, parser, read_csv, require, unique
6
-
7
-
8
- PARAMETERS = [f"{name}_{side}" for name in ["rx", "ry", "bx", "by"] for side in ["plus", "minus"]]
9
- PAIR_COLUMNS = ["Frame", "EV_Vehicle_ID", "POV_Vehicle_ID", "x_local", "y_local", "v_rel", "cangle"]
10
- SEMANTICS = ["Interaction_Target_ID", "x_local", "y_local", "v_rel", "Interaction Strength",
11
- "Is Interacting", "Interaction Type"]
12
-
13
-
14
- def validate_parameters(params):
15
- params = params.copy()
16
- numeric(params, ["cangle"], integer=True)
17
- numeric(params, ["round_v"] + PARAMETERS)
18
- unique(params, ["cangle", "round_v"])
19
- if not params.cangle.isin([0, 1]).all() or params[PARAMETERS].le(0).any().any():
20
- raise ValueError("cangle must be binary and all PR parameters must be positive")
21
- params["round_v"] = params.round_v.astype(float)
22
- return params.sort_values("round_v")
23
-
24
-
25
- def annotate_pairs(pairs, basic, params, tolerance=None):
26
- pairs = pairs.copy()
27
- numeric(pairs, ["Frame", "EV_Vehicle_ID", "POV_Vehicle_ID", "cangle"], integer=True)
28
- numeric(pairs, ["x_local", "y_local", "v_rel"])
29
- unique(pairs, ["Frame", "EV_Vehicle_ID", "POV_Vehicle_ID"])
30
- if (pairs.EV_Vehicle_ID == pairs.POV_Vehicle_ID).any() or not pairs.cangle.isin([0, 1]).all():
31
- raise ValueError("Invalid pair IDs or cangle; cangle is a binary class, NOT an angle in radians")
32
- if pairs.v_rel.le(0).any() or np.hypot(pairs.x_local, pairs.y_local).gt(50.0 + 1e-6).any():
33
- raise ValueError("Candidate pairs must have nonzero relative speed and be within 50 m")
34
- pairs["round_v"] = pairs.v_rel.round(1).astype(float)
35
- joined = pd.merge_asof(pairs.sort_values("round_v"), params, on="round_v", by="cangle",
36
- direction="nearest", tolerance=tolerance)
37
- if joined[PARAMETERS].isna().any().any():
38
- raise ValueError("Missing calibrated parameters: do not silently discard candidate pairs")
39
- pr_exponent = np.zeros(len(joined))
40
- for axis in ["x", "y"]:
41
- sign = np.sign(joined[f"{axis}_local"])
42
- scale = (1 + sign) / 2 * joined[f"r{axis}_plus"] + (1 - sign) / 2 * joined[f"r{axis}_minus"]
43
- shape = (1 + sign) / 2 * joined[f"b{axis}_plus"] + (1 - sign) / 2 * joined[f"b{axis}_minus"]
44
- pr_exponent += np.abs(joined[f"{axis}_local"] / scale) ** shape
45
- joined["Interaction Strength"] = np.exp(-pr_exponent)
46
- joined["Is Interacting"] = (joined["Interaction Strength"] > np.exp(-1)).astype(int)
47
- lookup = basic.set_index(["Frame", "Ego_Vehicle_ID"])
48
- lanes, directions = [], []
49
- for role in ["EV", "POV"]:
50
- keys = pd.MultiIndex.from_arrays([joined.Frame, joined[f"{role}_Vehicle_ID"]])
51
- values = lookup.reindex(keys)
52
- if values[["Lane number", "Direction"]].isna().any().any():
53
- raise ValueError("Pair vehicle/frame lacks a valid basic trajectory, lane, or direction")
54
- lanes.append(values["Lane number"].to_numpy())
55
- directions.append(values.Direction.to_numpy())
56
- if not np.equal(*directions).all():
57
- raise ValueError("Only same-direction candidate pairs are supported")
58
- joined["Interaction Type"] = np.where(joined.cangle.eq(1), "Lane Changing/Weaving",
59
- np.where(np.equal(*lanes), "Car Following", "Parallel Driving"))
60
- joined = joined.rename(columns={"EV_Vehicle_ID": "Ego_Vehicle_ID", "POV_Vehicle_ID": "Interaction_Target_ID"})
61
- return joined[["Frame", "Ego_Vehicle_ID"] + SEMANTICS]
62
-
63
-
64
- def process(basic, pairs_path, params, output, chunksize=500000, tolerance=None):
65
- basic = basic.copy()
66
- numeric(basic, ["Frame", "Ego_Vehicle_ID"], integer=True)
67
- require(basic, ["Lane number", "Direction", "x_center", "y_center"])
68
- unique(basic, ["Frame", "Ego_Vehicle_ID"])
69
- if "Source_ID" in basic and basic.Source_ID.nunique() != 1:
70
- raise ValueError("Run separately for each source recording")
71
- if set(SEMANTICS) & set(basic.columns):
72
- raise ValueError("Input must be Basic Trajectory data without existing interaction fields")
73
- params = validate_parameters(params)
74
- seen, first, count = set(), True, 0
75
- last_frame, boundary_pairs = None, set()
76
- # CSV blocks are written immediately; no list of all annotated blocks is retained.
77
- with output_path(output) as temporary, pd.read_csv(pairs_path, usecols=PAIR_COLUMNS, chunksize=chunksize) as reader:
78
- for chunk in reader:
79
- if chunk.empty:
80
- continue
81
- numeric(chunk, ["Frame", "EV_Vehicle_ID", "POV_Vehicle_ID"], integer=True)
82
- if not chunk.Frame.is_monotonic_increasing or (last_frame is not None and chunk.Frame.iloc[0] < last_frame):
83
- raise ValueError("Candidate CSV must be sorted by Frame for cross-block duplicate validation")
84
- if last_frame is not None:
85
- overlap = chunk.loc[chunk.Frame.eq(last_frame), ["EV_Vehicle_ID", "POV_Vehicle_ID"]]
86
- if boundary_pairs.intersection(map(tuple, overlap.to_numpy())):
87
- raise ValueError("Duplicate candidate pair across CSV blocks")
88
- tail = chunk.loc[chunk.Frame.eq(chunk.Frame.iloc[-1]), ["EV_Vehicle_ID", "POV_Vehicle_ID"]]
89
- tail_pairs = set(map(tuple, tail.to_numpy()))
90
- boundary_pairs = boundary_pairs | tail_pairs if last_frame == chunk.Frame.iloc[-1] else tail_pairs
91
- last_frame = chunk.Frame.iloc[-1]
92
- annotations = annotate_pairs(chunk, basic, params, tolerance)
93
- seen.update(zip(annotations.Frame, annotations.Ego_Vehicle_ID))
94
- result = annotations.merge(basic, on=["Frame", "Ego_Vehicle_ID"], how="left", validate="many_to_one")
95
- result = result[list(basic.columns) + SEMANTICS]
96
- result.to_csv(temporary, mode="w" if first else "a", header=first, index=False)
97
- first, count = False, count + len(result)
98
- absent = basic.loc[[key not in seen for key in zip(basic.Frame, basic.Ego_Vehicle_ID)]].copy()
99
- absent["Interaction_Target_ID"] = -1
100
- absent[["x_local", "y_local", "v_rel"]] = np.nan
101
- absent["Interaction Strength"], absent["Is Interacting"], absent["Interaction Type"] = 0.0, 0, "Safe"
102
- absent = absent[list(basic.columns) + SEMANTICS]
103
- absent.to_csv(temporary, mode="w" if first else "a", header=first, index=False)
104
- count += len(absent)
105
- print(f"Saved {count:,} rows; all candidate pairs retained regardless of PR threshold")
106
-
107
-
108
- def main():
109
- p = parser(__doc__)
110
- p.add_argument("--input", required=True, help="One-source Basic Trajectory CSV, final metric coordinates")
111
- p.add_argument("--pairs", required=True, help="Existing validated candidate-pair CSV, not generated here")
112
- p.add_argument("--parameters", required=True, help="Existing scenario-specific MLE calibration CSV")
113
- p.add_argument("--output", required=True, help="New Interaction Semantic CSV")
114
- p.add_argument("--chunksize", type=int, default=500000)
115
- p.add_argument("--speed-tolerance", type=float, help="Optional nearest-bin tolerance; omitted preserves source rule")
116
- a = p.parse_args()
117
- if a.chunksize < 1 or (a.speed_tolerance is not None and a.speed_tolerance < 0):
118
- p.error("Invalid chunk size or speed tolerance")
119
- process(read_csv(a.input), a.pairs, read_csv(a.parameters), a.output, a.chunksize, a.speed_tolerance)
120
-
121
-
122
- if __name__ == "__main__":
123
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Principal Processing Code/annotate_risk.py DELETED
@@ -1,120 +0,0 @@
1
- """Source-compatible TTC/DRAC and lane-change-event PET; see documented limitations."""
2
- import warnings
3
-
4
- import numpy as np
5
- import pandas as pd
6
-
7
- from _common import numeric, parser, read_csv, require, save_csv, unique
8
-
9
-
10
- def crossing_time(times, xs, target, start, sign):
11
- indexes = np.flatnonzero(times >= start)
12
- if len(indexes) < 2:
13
- return None
14
- signed = (xs - target) * sign
15
- for k in range(indexes[0], len(times) - 1):
16
- if signed[k] >= 0:
17
- return times[k]
18
- if signed[k + 1] >= 0:
19
- return times[k] - signed[k] / (signed[k + 1] - signed[k]) * (times[k + 1] - times[k])
20
- return None
21
-
22
-
23
- def annotate(df, drac_cap=15.0, fallback_length=None):
24
- df = df.copy()
25
- require(df, ["Lane number", "Direction", "Vehicle_Length_m"])
26
- numeric(df, ["Frame", "Ego_Vehicle_ID"], integer=True)
27
- numeric(df, ["Time_s", "x_center", "v_x"])
28
- unique(df, ["Frame", "Ego_Vehicle_ID"])
29
- if df[["Lane number", "Direction"]].isna().any().any():
30
- raise ValueError("Lane and Direction cannot be missing")
31
- if "Source_ID" in df and df.Source_ID.nunique() != 1:
32
- raise ValueError("Compute risk separately for each source recording")
33
- if drac_cap <= 0 or np.isnan(drac_cap):
34
- raise ValueError("DRAC cap must be positive; use inf for no cap")
35
- lengths = pd.to_numeric(df.Vehicle_Length_m, errors="raise")
36
- if lengths.isna().any():
37
- if fallback_length is None or not np.isfinite(fallback_length) or fallback_length <= 0:
38
- raise ValueError("Missing lengths: supply actual estimates or explicitly opt into a fallback")
39
- warnings.warn(f"Using {fallback_length} m for {lengths.isna().sum()} missing length rows")
40
- lengths = lengths.fillna(fallback_length)
41
- if not np.isfinite(lengths).all() or lengths.le(0).any():
42
- raise ValueError("Lengths must be positive and finite")
43
- df["_length"] = lengths
44
- df = df.sort_values(["Ego_Vehicle_ID", "Frame"]).reset_index(drop=True)
45
- grouped = df.groupby("Ego_Vehicle_ID", sort=False)
46
- if grouped._length.nunique().gt(1).any() or grouped.Direction.nunique().gt(1).any():
47
- raise ValueError("Length and Direction must be constant within each trajectory")
48
- if grouped.Frame.diff().dropna().ne(1).any():
49
- raise ValueError("PET requires gap-filled consecutive trajectory frames")
50
- if grouped.Time_s.diff().dropna().le(0).any() or df.groupby("Frame").Time_s.nunique().gt(1).any():
51
- raise ValueError("Inconsistent physical times")
52
- previous = grouped["Lane number"].shift()
53
- df["_cutin"] = previous.notna() & previous.ne(df["Lane number"])
54
- cache = {vid: (g.Time_s.to_numpy(), g.x_center.to_numpy()) for vid, g in grouped}
55
- parts = []
56
- for _, group in df.groupby(["Frame", "Direction"], sort=False):
57
- group = group.copy().reset_index(drop=True)
58
- n = len(group)
59
- x, v = group.x_center.to_numpy(), group.v_x.to_numpy()
60
- lane, ids = group["Lane number"].to_numpy(), group.Ego_Vehicle_ID.to_numpy()
61
- length, times = group._length.to_numpy(), group.Time_s.to_numpy()
62
- ttc, pet, drac = np.full(n, np.inf), np.full(n, np.nan), np.zeros(n)
63
- target_ttc, target_pet = np.full(n, -1, dtype=np.int64), np.full(n, -1, dtype=np.int64)
64
- for i in range(n):
65
- sign = np.sign(v[i])
66
- if sign == 0:
67
- continue
68
- leaders = np.flatnonzero((lane == lane[i]) & ((x - x[i]) * sign > 0))
69
- if len(leaders):
70
- j = leaders[np.argmin(np.abs(x[leaders] - x[i]))]
71
- clearance = abs(x[j] - x[i]) - (length[i] + length[j]) / 2
72
- closing = abs(v[i]) - abs(v[j])
73
- if clearance > 0 and closing > 0:
74
- ttc[i], drac[i] = clearance / closing, min(closing ** 2 / (2 * clearance), drac_cap)
75
- target_ttc[i] = ids[j]
76
- if group._cutin.iloc[i]:
77
- followers = np.flatnonzero((lane == lane[i]) & ((x[i] - x) * sign > 0))
78
- if not len(followers):
79
- continue
80
- j = followers[np.argmin(np.abs(x[followers] - x[i]))]
81
- clear = crossing_time(*cache[ids[i]], x[i] + sign * length[i] / 2, times[i], sign)
82
- arrive = crossing_time(*cache[ids[j]], x[i] - sign * length[j] / 2, times[i], sign)
83
- if clear is not None and arrive is not None:
84
- value = max(0.0, arrive - clear)
85
- for a, b in [(i, j), (j, i)]:
86
- if np.isnan(pet[a]) or value < pet[a]:
87
- pet[a], target_pet[a] = value, ids[b]
88
- high_pet, high_long = pet < 2.5, (ttc < 3.0) | (drac > 3.0)
89
- target = np.where(high_pet, target_pet,
90
- np.where(high_long, target_ttc, np.where(target_ttc != -1, target_ttc, target_pet)))
91
- group["TTC"], group["PET"], group["DRAC"] = ttc, pet, drac
92
- group["Max_Risk_Target_ID"] = target
93
- group["Risk_Level"] = np.where(high_pet | high_long, "High Risk", "Low Risk")
94
- parts.append(group)
95
- return pd.concat(parts, ignore_index=True).drop(columns=["_length", "_cutin"]).sort_values(
96
- ["Ego_Vehicle_ID", "Frame"]).reset_index(drop=True)
97
-
98
-
99
- def main():
100
- p = parser(__doc__)
101
- p.add_argument("--input", required=True, help="One-source Basic Trajectory CSV with metric lengths")
102
- p.add_argument("--output", required=True, help="New Risk Semantic CSV")
103
- p.add_argument("--fps", type=float, help="Constant source FPS, only if Time_s is absent")
104
- p.add_argument("--drac-cap", type=float, default=15.0, help="Legacy cap in m/s^2; inf changes legacy behavior")
105
- p.add_argument("--fallback-length-m", type=float, help="Explicit legacy imputation, e.g. 5; otherwise fail")
106
- a = p.parse_args()
107
- df = read_csv(a.input)
108
- if "Time_s" not in df:
109
- if a.fps is None or not np.isfinite(a.fps) or a.fps <= 0:
110
- p.error("Provide Time_s or the actual constant --fps; never infer mixed frame rates")
111
- numeric(df, ["Frame"], integer=True)
112
- df["Time_s"] = (df.Frame - df.Frame.min()) / a.fps
113
- elif a.fps is not None:
114
- p.error("Time_s already exists; omit --fps")
115
- print(f"DRAC cap={a.drac_cap}; no-closing TTC=inf; PET is event-level")
116
- save_csv(annotate(df, a.drac_cap, a.fallback_length_m), a.output)
117
-
118
-
119
- if __name__ == "__main__":
120
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Principal Processing Code/calibration_template.json DELETED
@@ -1,57 +0,0 @@
1
- {
2
- "template_only": true,
3
- "master_source": "SOURCE_MASTER",
4
- "origin_px": [
5
- null,
6
- null
7
- ],
8
- "rotation_rad": null,
9
- "reference_segments": [
10
- {
11
- "name": "LONGITUDINAL_REFERENCE_1",
12
- "point_a": [
13
- null,
14
- null
15
- ],
16
- "point_b": [
17
- null,
18
- null
19
- ],
20
- "real_distance_m": null
21
- },
22
- {
23
- "name": "LONGITUDINAL_REFERENCE_2",
24
- "point_a": [
25
- null,
26
- null
27
- ],
28
- "point_b": [
29
- null,
30
- null
31
- ],
32
- "real_distance_m": null
33
- }
34
- ],
35
- "sources": {
36
- "SOURCE_MASTER": {
37
- "validation_src": null,
38
- "validation_master": null
39
- },
40
- "SOURCE_OTHER": {
41
- "src_points": [
42
- [null, null],
43
- [null, null],
44
- [null, null],
45
- [null, null]
46
- ],
47
- "master_points": [
48
- [null, null],
49
- [null, null],
50
- [null, null],
51
- [null, null]
52
- ],
53
- "validation_src": null,
54
- "validation_master": null
55
- }
56
- }
57
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Principal Processing Code/coordinate_transform.py DELETED
@@ -1,100 +0,0 @@
1
- """Source pixels -> master frame -> road-aligned local metric coordinates."""
2
- import json
3
-
4
- import cv2
5
- import numpy as np
6
-
7
- from _common import numeric, parser, read_csv, save_csv, unique
8
-
9
-
10
- class Calibration:
11
- def __init__(self, config, source):
12
- if config.get("template_only", False):
13
- raise ValueError("Fill the calibration template before setting template_only to false")
14
- self.origin = np.asarray(config["origin_px"], dtype=float)
15
- if self.origin.shape != (2,) or not np.isfinite(self.origin).all():
16
- raise ValueError("origin_px must contain two finite coordinates")
17
- if config.get("rotation_rad", 0) != 0:
18
- raise ValueError("This release implements the supplied no-rotation workflow")
19
- ratios = []
20
- for segment in config["reference_segments"]:
21
- distance = np.linalg.norm(np.asarray(segment["point_a"], dtype=float) -
22
- np.asarray(segment["point_b"], dtype=float))
23
- real = float(segment["real_distance_m"])
24
- if not np.isfinite([distance, real]).all() or min(distance, real) <= 0:
25
- raise ValueError("Reference distances must be finite and positive")
26
- ratios.append(real / distance)
27
- if not ratios:
28
- raise ValueError("At least one measured master-frame reference is required")
29
- self.scale = float(np.mean(ratios))
30
- self.source = source
31
- if config["master_source"] not in config["sources"] or source not in config["sources"]:
32
- raise ValueError("master_source and --source must identify entries in sources")
33
- self.master = source == config["master_source"]
34
- entry = config["sources"][source]
35
- if self.master:
36
- self.homography = np.eye(3)
37
- else:
38
- src = np.asarray(entry["src_points"], dtype=np.float32)
39
- dst = np.asarray(entry["master_points"], dtype=np.float32)
40
- if src.shape != dst.shape or src.ndim != 2 or src.shape[1] != 2 or len(src) < 4:
41
- raise ValueError("At least four corresponding 2D control points are required")
42
- if not np.isfinite(src).all() or not np.isfinite(dst).all():
43
- raise ValueError("Non-finite control points")
44
- cv2.setRNGSeed(0)
45
- self.homography, mask = cv2.findHomography(src, dst, cv2.RANSAC, 3.0)
46
- if self.homography is None or mask.sum() < 4:
47
- raise ValueError("Homography estimation failed")
48
- print(f"Source={source}; master={config['master_source']}; scale={self.scale:.10g} m/px")
49
- if entry.get("validation_src") is not None:
50
- check = self.transform(entry["validation_src"])
51
- expected = (np.asarray(entry["validation_master"], dtype=float) - self.origin) * [self.scale, -self.scale]
52
- if check.shape != expected.shape or not np.isfinite(expected).all():
53
- raise ValueError("Invalid independent validation points")
54
- error = np.linalg.norm(check - expected, axis=1)
55
- print(f"Independent checkpoints={len(error)}; RMSE={np.sqrt(np.mean(error ** 2)):.6f} m; max={error.max():.6f} m")
56
- if entry.get("review_blocked", False):
57
- raise ValueError(f"Calibration blocked pending author review: {entry.get('review_note', source)}")
58
-
59
- def transform(self, points):
60
- points = np.asarray(points, dtype=float).reshape(-1, 2)
61
- if not np.isfinite(points).all():
62
- raise ValueError("Non-finite pixel coordinates")
63
- if not self.master:
64
- denominator = points @ self.homography[2, :2] + self.homography[2, 2]
65
- if np.any(np.abs(denominator) < 1e-10):
66
- raise ValueError("Points lie on the homography horizon")
67
- points = cv2.perspectiveTransform(points.astype(np.float32).reshape(-1, 1, 2),
68
- self.homography).reshape(-1, 2).astype(float)
69
- result = (points - self.origin) * [self.scale, -self.scale]
70
- if not np.isfinite(result).all():
71
- raise ValueError("Non-finite transformed coordinates")
72
- return result
73
-
74
-
75
- def load_calibration(path, source):
76
- with open(path, encoding="utf-8") as handle:
77
- return Calibration(json.load(handle), source)
78
-
79
-
80
- def main():
81
- p = parser(__doc__)
82
- p.add_argument("--input", required=True, help="Raw pixel trajectory CSV")
83
- p.add_argument("--calibration", required=True, help="Scene calibration JSON")
84
- p.add_argument("--source", required=True, help="Source video key in the calibration JSON")
85
- p.add_argument("--output", required=True, help="New metric trajectory CSV")
86
- args = p.parse_args()
87
- df = read_csv(args.input)
88
- numeric(df, ["Frame", "Vehicle_ID"], integer=True)
89
- numeric(df, ["x_center_px", "y_center_px"])
90
- unique(df, ["Frame", "Vehicle_ID"])
91
- if "Source_ID" in df and not df.Source_ID.eq(args.source).all():
92
- raise ValueError("Process one source at a time; Source_ID disagrees with --source")
93
- cal = load_calibration(args.calibration, args.source)
94
- df[["x_center", "y_center"]] = cal.transform(df[["x_center_px", "y_center_px"]])
95
- df["Source_ID"] = args.source
96
- save_csv(df, args.output)
97
-
98
-
99
- if __name__ == "__main__":
100
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Principal Processing Code/estimate_vehicle_length.py DELETED
@@ -1,63 +0,0 @@
1
- """Estimate fixed per-vehicle lengths using six-column pixel detections and calibration."""
2
- import numpy as np
3
- import pandas as pd
4
- from _common import numeric, parser, read_csv, require, save_csv, unique
5
- from coordinate_transform import load_calibration
6
-
7
-
8
- def estimate(df, calibration, minimum_frames=5, iqr_factor=1.5):
9
- df = df.copy()
10
- numeric(df, ["Frame", "Vehicle_ID"], integer=True)
11
- unique(df, ["Frame", "Vehicle_ID"])
12
- cols = ["x_center_px", "y_center_px", "width_px", "height_px"]
13
- require(df, cols)
14
- if (not np.isfinite([minimum_frames, iqr_factor]).all() or minimum_frames < 5 or
15
- int(minimum_frames) != minimum_frames or iqr_factor < 0):
16
- raise ValueError("Require integer minimum_frames >= 5 and finite iqr_factor >= 0")
17
- data = df[cols].apply(pd.to_numeric, errors="coerce").to_numpy(float)
18
- x, y, w, h = data.T
19
- valid = np.isfinite(data).all(axis=1) & (w > 0) & (h > 0)
20
- length, width = np.full(len(df), np.nan), np.full(len(df), np.nan)
21
- indexes = np.flatnonzero(valid)
22
- for block in np.array_split(indexes, max(1, int(np.ceil(len(indexes) / 100000)))):
23
- if not len(block):
24
- continue
25
- corners = np.stack([np.column_stack((x[block] + sx * w[block] / 2,
26
- y[block] + sy * h[block] / 2))
27
- for sx, sy in [(-1, -1), (1, -1), (1, 1), (-1, 1)]], axis=1)
28
- metric = calibration.transform(corners.reshape(-1, 2).astype(np.float32)).reshape(-1, 4, 2)
29
- length[block], width[block] = np.ptp(metric, axis=1).T
30
- valid &= np.isfinite(length) & np.isfinite(width) & (length > 0) & (width > 0)
31
- rows = []
32
- for vehicle, indexes in df.groupby("Vehicle_ID", sort=True).indices.items():
33
- selected = indexes[valid[indexes]]
34
- before = len(selected)
35
- if before >= 4:
36
- q1, q3 = np.quantile(length[selected], [0.25, 0.75])
37
- margin = iqr_factor * (q3 - q1)
38
- selected = selected[(length[selected] >= q1 - margin) & (length[selected] <= q3 + margin)]
39
- sufficient = len(selected) >= minimum_frames
40
- rows.append({"Source_ID": calibration.source, "Vehicle_ID": vehicle,
41
- "Vehicle_Length_m": np.quantile(length[selected], 0.25) if sufficient else np.nan,
42
- "BBox_Lateral_Extent_Q25_m": np.quantile(width[selected], 0.25) if sufficient else np.nan,
43
- "Input_Frames": len(indexes), "Valid_Before_IQR": before,
44
- "Retained_Frames": len(selected), "Removed_By_IQR": before - len(selected),
45
- "Quality": "good" if len(selected) >= 20 else "limited" if sufficient else "insufficient"})
46
- return pd.DataFrame(rows)
47
-
48
-
49
- def main():
50
- p = parser(__doc__)
51
- p.add_argument("--input", required=True, help="Six-column raw detection CSV; one source video")
52
- p.add_argument("--calibration", required=True, help="Same scene calibration JSON used for centers")
53
- p.add_argument("--source", required=True, help="Source video key in calibration JSON")
54
- p.add_argument("--output", required=True, help="New per-vehicle metric length and QC CSV")
55
- a = p.parse_args()
56
- df = read_csv(a.input)
57
- if "Source_ID" in df and not df.Source_ID.eq(a.source).all():
58
- raise ValueError("Input must contain only the requested source")
59
- save_csv(estimate(df, load_calibration(a.calibration, a.source)), a.output)
60
-
61
-
62
- if __name__ == "__main__":
63
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Principal Processing Code/filter_trajectory_outliers.py DELETED
@@ -1,66 +0,0 @@
1
- """Metric whole-track screening using the thresholds in Reconstruction(5).py."""
2
- import numpy as np
3
- import pandas as pd
4
- from _common import numeric, parser, read_csv, save_csv, unique
5
-
6
-
7
- def split_tracks(df, fps, min_duration=0.5, pseudo_duration=2.0,
8
- min_displacement=1.0, min_speed=0.5, min_observations=15):
9
- limits = [fps, min_duration, pseudo_duration, min_displacement, min_speed, min_observations]
10
- if not np.isfinite(limits).all() or fps <= 0 or min(limits[1:]) < 0:
11
- raise ValueError("Require positive FPS and finite nonnegative thresholds")
12
- if int(min_observations) != min_observations or min_observations < 2:
13
- raise ValueError("min_observations must be an integer >= 2")
14
- df = df.copy()
15
- numeric(df, ["Frame", "Vehicle_ID"], integer=True)
16
- numeric(df, ["x_center", "y_center"])
17
- if "Source_ID" in df and (df.Source_ID.isna().any() or df.Source_ID.nunique() != 1):
18
- raise ValueError("Process one constant-FPS source recording at a time")
19
- unique(df, ["Frame", "Vehicle_ID"])
20
- rows = []
21
- for vid, group in df.sort_values("Frame").groupby("Vehicle_ID", sort=True):
22
- xy = group[["x_center", "y_center"]].to_numpy(float)
23
- duration = len(group) / fps
24
- extent = float(np.linalg.norm(np.ptp(xy, axis=0)))
25
- path = float(np.linalg.norm(np.diff(xy, axis=0), axis=1).sum())
26
- speed = path / duration
27
- reasons = []
28
- if duration < min_duration:
29
- reasons.append("short_observed_duration")
30
- if len(group) < min_observations:
31
- reasons.append("insufficient_observations")
32
- if duration >= pseudo_duration and extent < min_displacement and speed < min_speed:
33
- reasons.append("suspected_low_motion_track")
34
- rows.append({"Vehicle_ID": vid, "Observation_Count": len(group),
35
- "Observed_Duration_s": duration, "Extent_Diagonal_m": extent,
36
- "Path_Length_m": path, "Mean_Path_Speed_mps": speed,
37
- "Rejected": bool(reasons), "Reason": ";".join(reasons) or "retained"})
38
- columns = ["Vehicle_ID", "Observation_Count", "Observed_Duration_s", "Extent_Diagonal_m",
39
- "Path_Length_m", "Mean_Path_Speed_mps", "Rejected", "Reason"]
40
- audit = pd.DataFrame(rows, columns=columns)
41
- if "Source_ID" in df:
42
- audit.insert(0, "Source_ID", df.Source_ID.iloc[0] if len(df) else None)
43
- reasons = audit.set_index("Vehicle_ID").Reason
44
- mask = df.Vehicle_ID.isin(audit.loc[audit.Rejected.eq(True), "Vehicle_ID"])
45
- rejected = df.loc[mask].copy()
46
- rejected["Rejection_Reason"] = rejected.Vehicle_ID.map(reasons)
47
- return df.loc[~mask].copy(), rejected, audit
48
-
49
-
50
- def main():
51
- p = parser(__doc__)
52
- p.add_argument("--input", required=True, help="One-source METRIC trajectory CSV")
53
- p.add_argument("--fps", type=float, required=True, help="Actual source frame rate")
54
- p.add_argument("--output", required=True, help="New retained metric trajectory CSV")
55
- p.add_argument("--rejected", required=True, help="New rejected-record CSV for review")
56
- p.add_argument("--audit", required=True, help="New per-vehicle screening summary CSV")
57
- a = p.parse_args()
58
- kept, rejected, audit = split_tracks(read_csv(a.input), a.fps)
59
- save_csv(audit, a.audit)
60
- save_csv(rejected, a.rejected)
61
- save_csv(kept, a.output)
62
- print("Review low-motion rejections: genuine stopped vehicles may satisfy this heuristic.")
63
-
64
-
65
- if __name__ == "__main__":
66
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Principal Processing Code/merge_vehicle_lengths.py DELETED
@@ -1,49 +0,0 @@
1
- """Attach fixed lengths using explicit source/local-ID lineage; never guess ID ranks."""
2
- import pandas as pd
3
-
4
- from _common import numeric, parser, read_csv, require, save_csv, unique
5
-
6
-
7
- def attach_lengths(basic, lengths, mapping=None):
8
- basic = basic.copy()
9
- lengths = lengths.copy().rename(columns={"Vehicle_ID": "Original_Vehicle_ID"})
10
- keys = ["Source_ID", "Original_Vehicle_ID"]
11
- require(lengths, keys + ["Vehicle_Length_m"])
12
- numeric(lengths, ["Original_Vehicle_ID"], integer=True)
13
- unique(lengths, keys)
14
- if mapping is not None:
15
- require(mapping, ["Ego_Vehicle_ID"] + keys)
16
- numeric(mapping, ["Ego_Vehicle_ID", "Original_Vehicle_ID"], integer=True)
17
- unique(mapping, ["Ego_Vehicle_ID"])
18
- unique(mapping, keys)
19
- if set(keys) & set(basic):
20
- raise ValueError("Mapping is only needed when basic data lack both lineage columns")
21
- basic = basic.merge(mapping[["Ego_Vehicle_ID"] + keys], on="Ego_Vehicle_ID",
22
- how="left", validate="many_to_one")
23
- require(basic, keys)
24
- numeric(basic, ["Original_Vehicle_ID"], integer=True)
25
- if basic[keys].isna().any().any():
26
- raise ValueError("Incomplete source/vehicle mapping")
27
- if "Vehicle_Length_m" in basic:
28
- raise ValueError("Vehicle_Length_m already exists; explicitly resolve it before merging")
29
- result = basic.merge(lengths[keys + ["Vehicle_Length_m"]], on=keys,
30
- how="left", validate="many_to_one", indicator=True)
31
- if result._merge.ne("both").any():
32
- raise ValueError("Some basic trajectories have no row in the length table")
33
- print(f"Rows with insufficient length estimates: {result.Vehicle_Length_m.isna().sum():,}")
34
- return result.drop(columns="_merge")
35
-
36
-
37
- def main():
38
- p = parser(__doc__)
39
- p.add_argument("--input", required=True, help="Reconstructed basic trajectory CSV")
40
- p.add_argument("--lengths", required=True, help="Per-vehicle length CSV, possibly concatenated across sources")
41
- p.add_argument("--mapping", help="Optional verified Ego_Vehicle_ID/Source_ID/Original_Vehicle_ID mapping CSV")
42
- p.add_argument("--output", required=True, help="New basic trajectory CSV with fixed lengths")
43
- a = p.parse_args()
44
- result = attach_lengths(read_csv(a.input), read_csv(a.lengths), read_csv(a.mapping) if a.mapping else None)
45
- save_csv(result, a.output)
46
-
47
-
48
- if __name__ == "__main__":
49
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Principal Processing Code/reconstruct_trajectories.py DELETED
@@ -1,123 +0,0 @@
1
- """Metric screening, PCHIP/linear gap filling, sEMA and physical kinematics."""
2
- import numpy as np
3
- import pandas as pd
4
- from _common import numeric, parser, read_csv, require, save_csv, unique
5
- from filter_trajectory_outliers import split_tracks
6
-
7
-
8
- def sema(values, fps, window_s=0.6):
9
- values = np.asarray(values, dtype=float)
10
- delta = fps * window_s
11
- if not np.isfinite(delta) or delta <= 0:
12
- raise ValueError("FPS and smoothing window must be positive")
13
- result = np.empty(len(values))
14
- for i in range(len(values)):
15
- radius = int(min(3 * delta, i, len(values) - 1 - i))
16
- weights = np.exp(-np.abs(np.arange(-radius, radius + 1)) / delta)
17
- result[i] = np.dot(values[i - radius:i + radius + 1], weights) / weights.sum()
18
- return result
19
-
20
-
21
- def kinematics(position, dt):
22
- position = np.asarray(position, dtype=float)
23
- velocity, acceleration = np.zeros(len(position)), np.zeros(len(position))
24
- if len(position) < 2:
25
- return velocity, acceleration
26
- velocity[1:-1] = (position[2:] - position[:-2]) / (2 * dt)
27
- velocity[0], velocity[-1] = (position[1] - position[0]) / dt, (position[-1] - position[-2]) / dt
28
- if len(position) > 2:
29
- acceleration[1:-1] = (position[2:] - 2 * position[1:-1] + position[:-2]) / dt ** 2
30
- acceleration[0] = (velocity[1] - velocity[0]) / dt
31
- acceleration[-1] = (velocity[-1] - velocity[-2]) / dt
32
- return velocity, acceleration
33
-
34
-
35
- def fill_lane(series):
36
- if not series.notna().any():
37
- raise ValueError("No lane observations for a vehicle")
38
- return series.ffill().bfill()
39
-
40
-
41
- def interpolate_coordinates(series):
42
- count = series.notna().sum()
43
- if count < 2:
44
- raise ValueError("At least two valid coordinate observations are required")
45
- method = "linear" if count == 2 else "pchip"
46
- return series.interpolate(method=method, limit_direction="both")
47
-
48
-
49
- def reconstruct(df, fps, source, window_s=0.6, id_offset=0, frame_offset=0,
50
- time_offset=0.0, merge_x=None, diverge_x=None, return_audit=False):
51
- if fps <= 0 or not np.isfinite(fps) or not np.isfinite(time_offset):
52
- raise ValueError("Finite positive FPS and finite time offset required")
53
- df = df.copy()
54
- require(df, ["Lane number", "Direction"])
55
- numeric(df, ["Frame", "Vehicle_ID"], integer=True)
56
- numeric(df, ["x_center", "y_center"])
57
- unique(df, ["Frame", "Vehicle_ID"])
58
- if "Source_ID" in df and not df.Source_ID.eq(source).all():
59
- raise ValueError("Reconstruct one constant-FPS source video at a time")
60
- first_frame = df.Frame.min()
61
- df, rejected, audit = split_tracks(df, fps)
62
- parts = []
63
- for vid, group in df.groupby("Vehicle_ID", sort=True):
64
- group = group.sort_values("Frame").set_index("Frame")
65
- if group.Direction.dropna().nunique() != 1 or not group["Lane number"].notna().any():
66
- raise ValueError(f"Missing/changing Direction or missing lanes for vehicle {vid}")
67
- frames = np.arange(group.index.min(), group.index.max() + 1)
68
- expanded = group.reindex(frames)
69
- out = pd.DataFrame({"Source_ID": source, "Original_Vehicle_ID": vid,
70
- "Original_Frame": frames, "Frame": frames + frame_offset,
71
- "Ego_Vehicle_ID": int(vid) + id_offset,
72
- "Time_s": time_offset + (frames - first_frame) / fps})
73
- out["Delta_t_s"] = np.r_[np.nan, np.full(len(frames) - 1, 1 / fps)]
74
- out["Lane number"] = fill_lane(expanded["Lane number"]).to_numpy()
75
- out["Direction"] = expanded.Direction.ffill().bfill().to_numpy()
76
- for axis in ("x", "y"):
77
- filled = interpolate_coordinates(expanded[f"{axis}_center"])
78
- if filled.isna().any():
79
- raise ValueError(f"Unfilled coordinates: vehicle {vid}")
80
- position = sema(filled.to_numpy(), fps, window_s)
81
- out[f"{axis}_center"] = position
82
- out[f"v_{axis}"], out[f"a_{axis}"] = kinematics(position, 1 / fps)
83
- if merge_x is not None:
84
- out["Dist_to_Merge_m"] = np.abs(out.x_center - merge_x)
85
- if diverge_x is not None:
86
- out["Dist_to_Diverge_m"] = np.abs(out.x_center - diverge_x)
87
- parts.append(out)
88
- out = pd.concat(parts, ignore_index=True) if parts else pd.DataFrame()
89
- print(f"Rejected {int(audit.Rejected.sum())} tracks; review audit for reasons; lane filling=ffill/bfill")
90
- if return_audit:
91
- return out, rejected, audit
92
- if out.empty:
93
- raise ValueError("No trajectories remain after screening")
94
- return out
95
-
96
-
97
- def main():
98
- p = parser(__doc__)
99
- p.add_argument("--input", required=True, help="Metric trajectory CSV with lane/direction annotations")
100
- p.add_argument("--output", required=True, help="New reconstructed metric trajectory CSV")
101
- p.add_argument("--source", required=True, help="Source video identifier")
102
- p.add_argument("--fps", required=True, type=float, help="Actual constant source frame rate")
103
- p.add_argument("--rejected", required=True, help="New rejected metric-record CSV for review")
104
- p.add_argument("--audit", required=True, help="New per-vehicle screening summary CSV")
105
- p.add_argument("--window-s", type=float, default=0.6)
106
- p.add_argument("--id-offset", type=int, default=0, help="Explicit offset for unique IDs across sources")
107
- p.add_argument("--frame-offset", type=int, default=0, help="Frame-label offset, not elapsed time")
108
- p.add_argument("--time-offset", type=float, default=0.0, help="Seconds at first input source frame")
109
- p.add_argument("--merge-x-m", type=float, help="Measured merge reference x in the same metric system")
110
- p.add_argument("--diverge-x-m", type=float, help="Measured diverge reference x in the same metric system")
111
- a = p.parse_args()
112
- out, rejected, audit = reconstruct(read_csv(a.input), a.fps, a.source, a.window_s,
113
- a.id_offset, a.frame_offset, a.time_offset,
114
- a.merge_x_m, a.diverge_x_m, return_audit=True)
115
- save_csv(audit, a.audit)
116
- save_csv(rejected, a.rejected)
117
- if out.empty:
118
- raise ValueError("All trajectories rejected; review saved audit; no reconstruction file written")
119
- save_csv(out, a.output)
120
-
121
-
122
- if __name__ == "__main__":
123
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Principal Processing Code/requirements.txt DELETED
@@ -1,4 +0,0 @@
1
- numpy==2.3.5
2
- pandas==2.2.3
3
- scipy==1.17.0
4
- opencv-python-headless==5.0.0.93