# U-EASWS principal processing code 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. ## Installation Python 3.12 is used for testing. Keep the Python files together and install the dependencies: ```bash python -m pip install -r requirements.txt ``` 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. ## Files and processing order | File | Required input | Output | | --- | --- | --- | | `coordinate_transform.py` | Source pixel trajectories and completed calibration JSON | Metric centers with source identity | | `reconstruct_trajectories.py` | Metric centers with verified lane/direction annotations and source FPS | Screened, gap-filled, smoothed trajectories; rejected records; per-vehicle audit | | `filter_trajectory_outliers.py` | Metric centers and FPS | The same screening as reconstruction, available independently | | `estimate_vehicle_length.py` | Six-column raw detections and the same calibration | Fixed per-vehicle lengths and quality fields | | `merge_vehicle_lengths.py` | Reconstructed trajectories and per-vehicle lengths | Basic trajectories with `Vehicle_Length_m` | | `annotate_risk.py` | Basic trajectories with timing and per-vehicle lengths | TTC, PET, DRAC and risk labels | | `annotate_interactions.py` | Basic trajectories, precomputed candidate pairs and calibrated PR parameters | Candidate-pair interaction annotations | | `_common.py` | Shared helper | CSV validation and output handling | | `calibration_template.json` | User-supplied measurements | Configuration structure without scene-specific measurements | 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. ```bash python coordinate_transform.py --input RAW_DETECTION_DATA.csv --calibration SCENE_CALIBRATION.json --source SOURCE_VIDEO_KEY --output METRIC_TRAJECTORIES.csv 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 python estimate_vehicle_length.py --input RAW_DETECTION_DATA.csv --calibration SCENE_CALIBRATION.json --source SOURCE_VIDEO_KEY --output VEHICLE_LENGTH_ESTIMATES.csv python merge_vehicle_lengths.py --input RECONSTRUCTED_TRAJECTORIES.csv --lengths VEHICLE_LENGTH_ESTIMATES.csv --output BASIC_TRAJECTORY_DATA.csv python annotate_risk.py --input BASIC_TRAJECTORY_DATA.csv --output RISK_SEMANTIC_DATA.csv python annotate_interactions.py --input BASIC_TRAJECTORY_DATA.csv --pairs CANDIDATE_PAIRS.csv --parameters PR_PARAMETERS.csv --output INTERACTION_SEMANTIC_DATA.csv ``` `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. ## Six-column vehicle-length input 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. 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. 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. ## Calibration template The JSON contains no actual scene coordinates, distances or source mappings. Copy it for each scene and fill: - `master_source`: reference source key, also present under `sources`. - `origin_px`: `[x, y]` of the physical origin in the master image. - `reference_segments`: master-image endpoints and measured physical distance in meters; at least one valid segment. - `sources`: actual source keys; each non-master source needs at least four nondegenerate corresponding `src_points` and `master_points`, in matching order. - `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. - `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. 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. 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. ## Screening and reconstruction 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). | Rule | Condition for rejecting a whole vehicle track | | --- | --- | | Short observed duration | N/FPS < 0.5 s | | Too few observations | N < 15 | | Suspected low-motion track | N/FPS >= 2 s AND extent diagonal < 1 m AND mean path speed < 0.5 m/s | 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`. 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. 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. 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. `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. ## Risk semantics 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. 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. ## Interaction semantics and omitted stages 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. 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. 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. ## Verification and reuse 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.