InterestingITS commited on
Commit
61c47a0
·
verified ·
1 Parent(s): 4bb98ce

Upload 26 files

Browse files
Processing_Code/README.md ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # U-EASWS processing code
2
+
3
+ The scripts provide coordinate conversion, trajectory reconstruction, vehicle-length estimation, TTC/PET/DRAC annotation, vehicle pairing, balanced sampling, driver-space parameter estimation and interaction annotation. The four measured calibration configurations contain the actual fitting inputs for sixteen source videos. Paths are supplied through command-line arguments.
4
+
5
+ ## Installation
6
+
7
+ Use Python 3.12 and keep the Python files together. Run commands from this directory:
8
+
9
+ ```bash
10
+ python -m venv .venv
11
+ # Activate .venv using the command appropriate to your operating system.
12
+ python -m pip install -r requirements.txt
13
+ ```
14
+
15
+ Every executable script accepts `--help`. Output files must have new names. For commands producing several outputs, all destination paths must be distinct and not already exist.
16
+
17
+ ## Start with the released Basic trajectory files
18
+
19
+ Download a Basic trajectory CSV from the [U-EASWS repository](https://huggingface.co/datasets/InterestingITS/U-EASWS/tree/main) and place it under `data/basic/`. The Basic files already contain `Lane number`, `Direction`, metric positions, velocities and estimated vehicle lengths. Use these fields directly for downstream processing. `configs/basic_manifest.csv` gives the four observation groups and the local filenames used in the examples; if the downloaded filename differs, pass its actual path in `--input` or rename it to the listed local filename without changing its records.
20
+
21
+ The following commands use the existing WS3 Basic file and its recorded lane and direction fields:
22
+
23
+ ```bash
24
+ python annotate_risk.py --input "data/basic/Weaving Segment_3.csv" --output runs/ws3_risk.csv
25
+ python generate_vehicle_pairs.py --input "data/basic/Weaving Segment_3.csv" --output runs/ws3_pairs.csv --audit runs/ws3_pairs_summary.json
26
+ python balance_pair_samples.py --input runs/ws3_pairs.csv --output runs/ws3_balanced.csv --audit runs/ws3_sampling_summary.json --seed 42
27
+ python fit_pr_parameters.py --input runs/ws3_balanced.csv --output runs/ws3_pr_parameters.csv --audit runs/ws3_fit_summary.json --workers 1
28
+ python annotate_interactions.py --input "data/basic/Weaving Segment_3.csv" --pairs runs/ws3_pairs.csv --parameters runs/ws3_pr_parameters.csv --output runs/ws3_interactions.csv
29
+ ```
30
+
31
+ The pair, sample and inference commands operate on the complete observation-group file. Fit parameter groups are defined by `cangle,round_v`. Use the full candidate-pair file for interaction annotation; the balanced subset is for fitting.
32
+
33
+ Risk annotation uses `Time_s` when present. For the released format containing `Delta_t_s`, it reconstructs a shared time reference for each connected sequence of observed frame intervals. This uses the recorded 30/60 fps intervals, including mixed-rate files. Disconnected sequences receive independent `Time_Reference_ID` values and start at `Time_s=0`; elapsed time between such references is not inserted. Trajectories must remain within one reference. An explicit `--fps` is an alternative only for a recording with that constant frame rate.
34
+
35
+ ## Start with source detection records
36
+
37
+ The pixel-to-metric and reconstruction commands are separate entry points for source detection records. Use `configs/source_manifest.csv` to match each `Raw_Data` CSV to the actual source FPS and calibration source key.
38
+
39
+ | Observation group | Master source | Measured configuration |
40
+ | --- | --- | --- |
41
+ | WS1-2 | video4 | [WS1_2.json](calibrations/WS1_2.json) |
42
+ | WS3 | video2 | [WS3.json](calibrations/WS3.json) |
43
+ | WS4-5 | video1 | [WS4_5.json](calibrations/WS4_5.json) |
44
+ | WS6-7 | video2 | [WS6_7.json](calibrations/WS6_7.json) |
45
+
46
+ All supplied JSONs in `calibrations/` contain measured scene values. See [CALIBRATION.md](docs/CALIBRATION.md) for the fields and transformation equations. Raw file suffix `_N` corresponds to `videoN`.
47
+
48
+ For raw reconstruction, supply a source-frame annotation CSV containing `Frame,Vehicle_ID,Lane number,Direction`, keyed by the original detection records, or use metric detections that already contain these fields. The published Basic data provide lane and direction fields under processed `Frame,Ego_Vehicle_ID`. To transfer those fields to raw detections, apply the corresponding source/frame/vehicle mapping to obtain the original keys.
49
+
50
+ The source-frame example below uses WS3/video2 at 30 fps and `data/lanes/WS3_video2_lanes.csv` as the annotation input:
51
+
52
+ ```bash
53
+ python coordinate_transform.py --input data/raw/WS3_raw_detection_data_2.csv --calibration calibrations/WS3.json --source video2 --output runs/ws3_video2_metric.csv
54
+ python attach_lane_annotations.py --input runs/ws3_video2_metric.csv --annotations data/lanes/WS3_video2_lanes.csv --output runs/ws3_video2_metric_with_lanes.csv
55
+ python reconstruct_trajectories.py --input runs/ws3_video2_metric_with_lanes.csv --source video2 --fps 30 --id-offset 0 --frame-offset 0 --time-offset 0 --output runs/ws3_video2_reconstructed.csv --rejected runs/ws3_video2_rejected.csv --audit runs/ws3_video2_screening.csv
56
+ python estimate_vehicle_length.py --input data/raw/WS3_raw_detection_data_2.csv --calibration calibrations/WS3.json --source video2 --output runs/ws3_video2_lengths.csv
57
+ python merge_vehicle_lengths.py --input runs/ws3_video2_reconstructed.csv --lengths runs/ws3_video2_lengths.csv --output runs/ws3_video2_basic.csv
58
+ ```
59
+
60
+ The generated Basic file can then be supplied to the downstream commands above. If the metric detection input already includes source-frame lanes/direction, omit the lane-join command and pass that file to reconstruction.
61
+
62
+ Use one source recording per reconstruction. The example offsets retain source-local IDs and time; supply established offsets explicitly when combining sources. `filter_trajectory_outliers.py` exposes the same screen used inside reconstruction. Measured `--merge-x-m` and `--diverge-x-m` reference coordinates enable the corresponding distance fields.
63
+
64
+ See [INPUT_OUTPUT.md](docs/INPUT_OUTPUT.md) for all input schemas and [METHOD_NOTES.md](docs/METHOD_NOTES.md) for processing rules and numerical settings. Attribution for the reused driver-space code is retained in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).
Processing_Code/THIRD_PARTY_NOTICES.md ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Third-party code notice
2
+
3
+ The driver-space inference routines in `driver_space_model.py` are adapted from [Yiru-Jiao/DriverSpaceInference](https://github.com/Yiru-Jiao/DriverSpaceInference), accompanying Jiao et al. (2023), *Inferring vehicle spacing in urban traffic from trajectory data*. The original implementation used `scipy.misc.derivative`; this version expresses its three-point central second difference directly and retains the supplied inference procedure and settings.
4
+
5
+ The following upstream notice is reproduced for that reused code. It does not assign a new license to the U-EASWS dataset or to the other files in this supplement.
6
+
7
+ ```text
8
+ MIT License
9
+
10
+ Copyright (c) 2022 Yiru Jiao
11
+
12
+ Permission is hereby granted, free of charge, to any person obtaining a copy
13
+ of this software and associated documentation files (the "Software"), to deal
14
+ in the Software without restriction, including without limitation the rights
15
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16
+ copies of the Software, and to permit persons to whom the Software is
17
+ furnished to do so, subject to the following conditions:
18
+
19
+ The above copyright notice and this permission notice shall be included in all
20
+ copies or substantial portions of the Software.
21
+
22
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28
+ SOFTWARE.
29
+ ```
Processing_Code/_common.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 lane_direction(df, allow_missing=False):
42
+ """Validate lane indices and direction labels; reconstruction may fill missing observations."""
43
+ require(df, ["Lane number", "Direction"])
44
+ lanes = pd.to_numeric(df["Lane number"], errors="raise")
45
+ observed = lanes.dropna().to_numpy(dtype=float)
46
+ if not np.isfinite(observed).all() or np.any(observed <= 0) or np.any(observed != np.floor(observed)):
47
+ raise ValueError("Lane number must be a positive integer")
48
+ if not df.Direction.dropna().isin(["Left", "Right"]).all():
49
+ raise ValueError("Direction must be Left or Right")
50
+ if not allow_missing and (lanes.isna().any() or df.Direction.isna().any()):
51
+ raise ValueError("Lane and Direction cannot be missing")
52
+ df["Lane number"] = lanes
53
+
54
+
55
+ def read_csv(path):
56
+ df = pd.read_csv(path, encoding="utf-8-sig")
57
+ if df.empty:
58
+ raise ValueError(f"Empty input: {path}")
59
+ return df
60
+
61
+
62
+ def preflight_outputs(*paths):
63
+ """Reject colliding or existing destinations before a multi-output run."""
64
+ resolved = [Path(path).resolve() for path in paths]
65
+ if len(set(resolved)) != len(resolved):
66
+ raise ValueError("Output destinations must be distinct")
67
+ for path in resolved:
68
+ if path.exists():
69
+ raise FileExistsError(f"Output exists; choose a new filename: {path}")
70
+
71
+
72
+ @contextmanager
73
+ def output_path(path):
74
+ path = Path(path)
75
+ if path.exists():
76
+ raise FileExistsError(f"Output exists; choose a new filename: {path}")
77
+ path.parent.mkdir(parents=True, exist_ok=True)
78
+ handle, temporary = tempfile.mkstemp(prefix=path.name + ".", dir=path.parent)
79
+ os.close(handle)
80
+ try:
81
+ yield temporary
82
+ if path.exists():
83
+ raise FileExistsError(path)
84
+ os.replace(temporary, path)
85
+ finally:
86
+ if os.path.exists(temporary):
87
+ os.unlink(temporary)
88
+
89
+
90
+ def save_csv(df, path):
91
+ with output_path(path) as temporary:
92
+ df.to_csv(temporary, index=False, encoding="utf-8-sig")
93
+ print(f"Saved {len(df):,} rows: {path}")
Processing_Code/annotate_interactions.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 lane_direction, 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
+ lane_direction(basic)
69
+ unique(basic, ["Frame", "Ego_Vehicle_ID"])
70
+ if "Source_ID" in basic and (basic.Source_ID.isna().any() or basic.Source_ID.nunique() != 1):
71
+ raise ValueError("Run separately for each source recording")
72
+ if set(SEMANTICS) & set(basic.columns):
73
+ raise ValueError("Input must be Basic Trajectory data without existing interaction fields")
74
+ params = validate_parameters(params)
75
+ seen, first, count = set(), True, 0
76
+ last_frame, boundary_pairs = None, set()
77
+ # CSV blocks are written immediately; no list of all annotated blocks is retained.
78
+ with output_path(output) as temporary, pd.read_csv(pairs_path, usecols=PAIR_COLUMNS, chunksize=chunksize) as reader:
79
+ for chunk in reader:
80
+ if chunk.empty:
81
+ continue
82
+ numeric(chunk, ["Frame", "EV_Vehicle_ID", "POV_Vehicle_ID"], integer=True)
83
+ if not chunk.Frame.is_monotonic_increasing or (last_frame is not None and chunk.Frame.iloc[0] < last_frame):
84
+ raise ValueError("Candidate CSV must be sorted by Frame for cross-block duplicate validation")
85
+ if last_frame is not None:
86
+ overlap = chunk.loc[chunk.Frame.eq(last_frame), ["EV_Vehicle_ID", "POV_Vehicle_ID"]]
87
+ if boundary_pairs.intersection(map(tuple, overlap.to_numpy())):
88
+ raise ValueError("Duplicate candidate pair across CSV blocks")
89
+ tail = chunk.loc[chunk.Frame.eq(chunk.Frame.iloc[-1]), ["EV_Vehicle_ID", "POV_Vehicle_ID"]]
90
+ tail_pairs = set(map(tuple, tail.to_numpy()))
91
+ boundary_pairs = boundary_pairs | tail_pairs if last_frame == chunk.Frame.iloc[-1] else tail_pairs
92
+ last_frame = chunk.Frame.iloc[-1]
93
+ annotations = annotate_pairs(chunk, basic, params, tolerance)
94
+ seen.update(zip(annotations.Frame, annotations.Ego_Vehicle_ID))
95
+ result = annotations.merge(basic, on=["Frame", "Ego_Vehicle_ID"], how="left", validate="many_to_one")
96
+ result = result[list(basic.columns) + SEMANTICS]
97
+ result.to_csv(temporary, mode="w" if first else "a", header=first, index=False)
98
+ first, count = False, count + len(result)
99
+ absent = basic.loc[[key not in seen for key in zip(basic.Frame, basic.Ego_Vehicle_ID)]].copy()
100
+ absent["Interaction_Target_ID"] = -1
101
+ absent[["x_local", "y_local", "v_rel"]] = np.nan
102
+ absent["Interaction Strength"], absent["Is Interacting"], absent["Interaction Type"] = 0.0, 0, "Safe"
103
+ absent = absent[list(basic.columns) + SEMANTICS]
104
+ absent.to_csv(temporary, mode="w" if first else "a", header=first, index=False)
105
+ count += len(absent)
106
+ print(f"Saved {count:,} rows; all candidate pairs retained regardless of PR threshold")
107
+
108
+
109
+ def main():
110
+ p = parser(__doc__)
111
+ p.add_argument("--input", required=True, help="Released observation-group Basic CSV or single-source Basic CSV, with final metric coordinates")
112
+ p.add_argument("--pairs", required=True, help="Full candidate-pair CSV generated by generate_vehicle_pairs.py")
113
+ p.add_argument("--parameters", required=True, help="Scenario/source PR parameter CSV generated by fit_pr_parameters.py")
114
+ p.add_argument("--output", required=True, help="New Interaction Semantic CSV")
115
+ p.add_argument("--chunksize", type=int, default=500000)
116
+ p.add_argument("--speed-tolerance", type=float, help="Optional nearest-bin tolerance; omitted preserves source rule")
117
+ a = p.parse_args()
118
+ if a.chunksize < 1 or (a.speed_tolerance is not None and a.speed_tolerance < 0):
119
+ p.error("Invalid chunk size or speed tolerance")
120
+ process(read_csv(a.input), a.pairs, read_csv(a.parameters), a.output, a.chunksize, a.speed_tolerance)
121
+
122
+
123
+ if __name__ == "__main__":
124
+ main()
Processing_Code/annotate_risk.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compute TTC/DRAC and lane-change-event PET from metric trajectories."""
2
+ import warnings
3
+
4
+ import numpy as np
5
+ import pandas as pd
6
+
7
+ from _common import lane_direction, numeric, parser, read_csv, require, save_csv, unique
8
+
9
+
10
+ def time_from_intervals(df):
11
+ """Recover recording-relative time from the released frame-interval field."""
12
+ df = df.copy()
13
+ numeric(df, ["Frame", "Ego_Vehicle_ID"], integer=True)
14
+ unique(df, ["Frame", "Ego_Vehicle_ID"])
15
+ require(df, ["Delta_t_s"])
16
+ if "Time_Reference_ID" in df:
17
+ raise ValueError("Resolve existing Time_Reference_ID before deriving a new time reference")
18
+ delta = pd.to_numeric(df.Delta_t_s, errors="raise")
19
+ observed = delta.notna()
20
+ if not np.isfinite(delta[observed]).all() or delta[observed].le(0).any():
21
+ raise ValueError("Observed Delta_t_s values must be finite and positive")
22
+ ordered = df.assign(_delta=delta).sort_values(["Ego_Vehicle_ID", "Frame"])
23
+ differences = ordered.groupby("Ego_Vehicle_ID").Frame.diff()
24
+ if differences.dropna().ne(1).any() or ordered.loc[differences.notna(), "_delta"].isna().any():
25
+ raise ValueError("Require consecutive vehicle frames with Delta_t_s after each first record")
26
+ intervals = df.loc[observed, ["Frame"]].assign(_delta=delta[observed]).groupby("Frame")._delta.agg(["min", "max"])
27
+ if not np.isclose(intervals["min"], intervals["max"], rtol=1e-8, atol=1e-10).all():
28
+ raise ValueError("Conflicting Delta_t_s values for the same processed frame")
29
+ times, references = {}, {}
30
+ previous, elapsed, reference = None, 0.0, -1
31
+ for frame in np.sort(df.Frame.unique()):
32
+ frame = int(frame)
33
+ if previous is None or frame != previous + 1 or frame not in intervals.index:
34
+ reference += 1
35
+ elapsed = 0.0
36
+ else:
37
+ elapsed += float(intervals.loc[frame, "min"])
38
+ times[frame], references[frame] = elapsed, reference
39
+ previous = frame
40
+ df["Time_s"] = df.Frame.map(times)
41
+ df["Time_Reference_ID"] = df.Frame.map(references)
42
+ if df.groupby("Ego_Vehicle_ID").Time_Reference_ID.nunique().gt(1).any():
43
+ raise ValueError("A vehicle spans disconnected time references; inspect its frame/interval mapping")
44
+ return df
45
+
46
+
47
+ def crossing_time(times, xs, target, start, sign):
48
+ indexes = np.flatnonzero(times >= start)
49
+ if len(indexes) < 2:
50
+ return None
51
+ signed = (xs - target) * sign
52
+ for k in range(indexes[0], len(times) - 1):
53
+ if signed[k] >= 0:
54
+ return times[k]
55
+ if signed[k + 1] >= 0:
56
+ return times[k] - signed[k] / (signed[k + 1] - signed[k]) * (times[k + 1] - times[k])
57
+ return None
58
+
59
+
60
+ def annotate(df, drac_cap=15.0, fallback_length=None):
61
+ df = df.copy()
62
+ require(df, ["Lane number", "Direction", "Vehicle_Length_m"])
63
+ lane_direction(df)
64
+ numeric(df, ["Frame", "Ego_Vehicle_ID"], integer=True)
65
+ numeric(df, ["Time_s", "x_center", "v_x"])
66
+ unique(df, ["Frame", "Ego_Vehicle_ID"])
67
+ if df[["Lane number", "Direction"]].isna().any().any():
68
+ raise ValueError("Lane and Direction cannot be missing")
69
+ if "Source_ID" in df and (df.Source_ID.isna().any() or df.Source_ID.nunique() != 1):
70
+ raise ValueError("Compute risk separately for each source recording")
71
+ if drac_cap <= 0 or np.isnan(drac_cap):
72
+ raise ValueError("DRAC cap must be positive; use inf for no cap")
73
+ lengths = pd.to_numeric(df.Vehicle_Length_m, errors="raise")
74
+ if lengths.isna().any():
75
+ if fallback_length is None or not np.isfinite(fallback_length) or fallback_length <= 0:
76
+ raise ValueError("Missing lengths: supply actual estimates or explicitly opt into a fallback")
77
+ warnings.warn(f"Using {fallback_length} m for {lengths.isna().sum()} missing length rows")
78
+ lengths = lengths.fillna(fallback_length)
79
+ if not np.isfinite(lengths).all() or lengths.le(0).any():
80
+ raise ValueError("Lengths must be positive and finite")
81
+ df["_length"] = lengths
82
+ df = df.sort_values(["Ego_Vehicle_ID", "Frame"]).reset_index(drop=True)
83
+ grouped = df.groupby("Ego_Vehicle_ID", sort=False)
84
+ if grouped._length.nunique().gt(1).any() or grouped.Direction.nunique().gt(1).any():
85
+ raise ValueError("Length and Direction must be constant within each trajectory")
86
+ if grouped.Frame.diff().dropna().ne(1).any():
87
+ raise ValueError("PET requires gap-filled consecutive trajectory frames")
88
+ if grouped.Time_s.diff().dropna().le(0).any() or df.groupby("Frame").Time_s.nunique().gt(1).any():
89
+ raise ValueError("Inconsistent physical times")
90
+ previous = grouped["Lane number"].shift()
91
+ df["_cutin"] = previous.notna() & previous.ne(df["Lane number"])
92
+ cache = {vid: (g.Time_s.to_numpy(), g.x_center.to_numpy()) for vid, g in grouped}
93
+ parts = []
94
+ for _, group in df.groupby(["Frame", "Direction"], sort=False):
95
+ group = group.copy().reset_index(drop=True)
96
+ n = len(group)
97
+ x, v = group.x_center.to_numpy(), group.v_x.to_numpy()
98
+ lane, ids = group["Lane number"].to_numpy(), group.Ego_Vehicle_ID.to_numpy()
99
+ length, times = group._length.to_numpy(), group.Time_s.to_numpy()
100
+ ttc, pet, drac = np.full(n, np.inf), np.full(n, np.nan), np.zeros(n)
101
+ target_ttc, target_pet = np.full(n, -1, dtype=np.int64), np.full(n, -1, dtype=np.int64)
102
+ for i in range(n):
103
+ sign = np.sign(v[i])
104
+ if sign == 0:
105
+ continue
106
+ leaders = np.flatnonzero((lane == lane[i]) & ((x - x[i]) * sign > 0))
107
+ if len(leaders):
108
+ j = leaders[np.argmin(np.abs(x[leaders] - x[i]))]
109
+ clearance = abs(x[j] - x[i]) - (length[i] + length[j]) / 2
110
+ closing = abs(v[i]) - abs(v[j])
111
+ if clearance > 0 and closing > 0:
112
+ ttc[i], drac[i] = clearance / closing, min(closing ** 2 / (2 * clearance), drac_cap)
113
+ target_ttc[i] = ids[j]
114
+ if group._cutin.iloc[i]:
115
+ followers = np.flatnonzero((lane == lane[i]) & ((x[i] - x) * sign > 0))
116
+ if not len(followers):
117
+ continue
118
+ j = followers[np.argmin(np.abs(x[followers] - x[i]))]
119
+ clear = crossing_time(*cache[ids[i]], x[i] + sign * length[i] / 2, times[i], sign)
120
+ arrive = crossing_time(*cache[ids[j]], x[i] - sign * length[j] / 2, times[i], sign)
121
+ if clear is not None and arrive is not None:
122
+ value = max(0.0, arrive - clear)
123
+ for a, b in [(i, j), (j, i)]:
124
+ if np.isnan(pet[a]) or value < pet[a]:
125
+ pet[a], target_pet[a] = value, ids[b]
126
+ high_pet, high_long = pet < 2.5, (ttc < 3.0) | (drac > 3.0)
127
+ target = np.where(high_pet, target_pet,
128
+ np.where(high_long, target_ttc, np.where(target_ttc != -1, target_ttc, target_pet)))
129
+ group["TTC"], group["PET"], group["DRAC"] = ttc, pet, drac
130
+ group["Max_Risk_Target_ID"] = target
131
+ group["Risk_Level"] = np.where(high_pet | high_long, "High Risk", "Low Risk")
132
+ parts.append(group)
133
+ return pd.concat(parts, ignore_index=True).drop(columns=["_length", "_cutin"]).sort_values(
134
+ ["Ego_Vehicle_ID", "Frame"]).reset_index(drop=True)
135
+
136
+
137
+ def main():
138
+ p = parser(__doc__)
139
+ p.add_argument("--input", required=True, help="Released observation-group Basic CSV or single-source Basic CSV, with metric lengths")
140
+ p.add_argument("--output", required=True, help="New Risk Semantic CSV")
141
+ p.add_argument("--fps", type=float, help="Explicit constant source FPS; otherwise use Time_s or released Delta_t_s")
142
+ p.add_argument("--drac-cap", type=float, default=15.0, help="DRAC cap in m/s^2 (default: 15)")
143
+ p.add_argument("--fallback-length-m", type=float, help="Optional replacement length in meters for records with missing length")
144
+ a = p.parse_args()
145
+ df = read_csv(a.input)
146
+ if "Time_s" not in df:
147
+ if a.fps is not None:
148
+ if not np.isfinite(a.fps) or a.fps <= 0:
149
+ p.error("Provide a finite positive constant --fps")
150
+ numeric(df, ["Frame"], integer=True)
151
+ df["Time_s"] = (df.Frame - df.Frame.min()) / a.fps
152
+ elif "Delta_t_s" in df:
153
+ df = time_from_intervals(df)
154
+ else:
155
+ p.error("Provide Time_s, released Delta_t_s, or the actual constant --fps")
156
+ elif a.fps is not None:
157
+ p.error("Time_s already exists; omit --fps")
158
+ print(f"DRAC cap={a.drac_cap}; no-closing TTC=inf; PET is event-level")
159
+ save_csv(annotate(df, a.drac_cap, a.fallback_length_m), a.output)
160
+
161
+
162
+ if __name__ == "__main__":
163
+ main()
Processing_Code/attach_lane_annotations.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Join source-frame lane and direction fields by original frame and vehicle keys."""
2
+ from _common import lane_direction, numeric, parser, read_csv, require, save_csv, unique
3
+
4
+
5
+ def attach(metric, annotations):
6
+ metric, annotations = metric.copy(), annotations.copy()
7
+ keys, fields = ["Frame", "Vehicle_ID"], ["Lane number", "Direction"]
8
+ if set(fields) & set(metric.columns):
9
+ raise ValueError("Metric input already has lane/direction fields; explicitly resolve them first")
10
+ for table in (metric, annotations):
11
+ numeric(table, keys, integer=True)
12
+ unique(table, keys)
13
+ require(annotations, fields)
14
+ lane_direction(annotations)
15
+ if not annotations.Direction.isin(["Left", "Right"]).all() or annotations["Lane number"].isna().any():
16
+ raise ValueError("Annotations require valid lane numbers and Left/Right directions")
17
+ if "Source_ID" in metric:
18
+ if metric.Source_ID.isna().any() or metric.Source_ID.nunique() != 1:
19
+ raise ValueError("Attach lanes for one source at a time")
20
+ if "Source_ID" in annotations and not annotations.Source_ID.eq(metric.Source_ID.iloc[0]).all():
21
+ raise ValueError("Annotation source differs from metric source")
22
+ result = metric.merge(annotations[keys + fields], on=keys, how="left", validate="one_to_one", indicator=True)
23
+ if result._merge.ne("both").any():
24
+ raise ValueError("Some metric observations lack verified lane/direction annotations")
25
+ return result.drop(columns="_merge")
26
+
27
+
28
+ def main():
29
+ p = parser(__doc__)
30
+ p.add_argument("--input", required=True, help="One-source metric CSV with original Frame and Vehicle_ID")
31
+ p.add_argument("--annotations", required=True, help="Verified source-frame CSV: Frame,Vehicle_ID,Lane number,Direction")
32
+ p.add_argument("--output", required=True, help="New metric trajectory CSV with lane/direction fields")
33
+ a = p.parse_args()
34
+ save_csv(attach(read_csv(a.input), read_csv(a.annotations)), a.output)
35
+
36
+
37
+ if __name__ == "__main__":
38
+ main()
Processing_Code/balance_pair_samples.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Seeded exact dense-bin sampling and the author's pooled sparse-bin grouping."""
2
+ from collections import Counter, defaultdict
3
+ import json
4
+ from pathlib import Path
5
+ import shutil
6
+ import sqlite3
7
+ import tempfile
8
+ import numpy as np
9
+ import pandas as pd
10
+ from _common import numeric, output_path, parser, unique, preflight_outputs
11
+
12
+ INPUT_COLUMNS = ["Frame", "EV_Vehicle_ID", "POV_Vehicle_ID", "x_local", "y_local", "v_rel", "cangle"]
13
+ OUTPUT_COLUMNS = INPUT_COLUMNS + ["round_v", "Sample_Group_ID"]
14
+
15
+
16
+ def read_chunks(path, chunksize):
17
+ last_frame, boundary = None, set()
18
+ with pd.read_csv(path, usecols=INPUT_COLUMNS, chunksize=chunksize) as reader:
19
+ for chunk in reader:
20
+ numeric(chunk, ["Frame", "EV_Vehicle_ID", "POV_Vehicle_ID", "cangle"], integer=True)
21
+ numeric(chunk, ["x_local", "y_local", "v_rel"])
22
+ unique(chunk, ["Frame", "EV_Vehicle_ID", "POV_Vehicle_ID"])
23
+ if not len(chunk):
24
+ continue
25
+ if not chunk.Frame.is_monotonic_increasing or (last_frame is not None and chunk.Frame.iloc[0] < last_frame):
26
+ raise ValueError("Candidate CSV must be sorted by Frame")
27
+ if last_frame is not None:
28
+ keys = set(map(tuple, chunk.loc[chunk.Frame.eq(last_frame), ["EV_Vehicle_ID", "POV_Vehicle_ID"]].to_numpy()))
29
+ if boundary & keys:
30
+ raise ValueError("Duplicate pair/frame across CSV chunks")
31
+ tail = set(map(tuple, chunk.loc[chunk.Frame.eq(chunk.Frame.iloc[-1]), ["EV_Vehicle_ID", "POV_Vehicle_ID"]].to_numpy()))
32
+ boundary = boundary | tail if last_frame == chunk.Frame.iloc[-1] else tail
33
+ last_frame = chunk.Frame.iloc[-1]
34
+ if not chunk.cangle.isin([0, 1]).all() or chunk.v_rel.le(0).any() or chunk.EV_Vehicle_ID.eq(chunk.POV_Vehicle_ID).any():
35
+ raise ValueError("Require binary cangle, positive relative speed, and distinct vehicle IDs")
36
+ yield chunk
37
+
38
+
39
+ def balance(input_path, output, audit_path, target=50000, max_relative_speed=30., seed=42, chunksize=500000, work_dir=None):
40
+ if target < 1 or int(target) != target or chunksize < 1 or not np.isfinite(max_relative_speed) or max_relative_speed <= 0:
41
+ raise ValueError("Require positive integer target/chunksize and finite positive maximum speed")
42
+ preflight_outputs(output, audit_path)
43
+ if Path(output).resolve() == Path(audit_path).resolve() or Path(audit_path).exists():
44
+ raise FileExistsError("Choose distinct new output and audit filenames")
45
+ source = Path(input_path)
46
+ initial_stat = (source.stat().st_size, source.stat().st_mtime_ns)
47
+ counts, input_rows, excluded = Counter(), 0, 0
48
+ for chunk in read_chunks(source, chunksize):
49
+ input_rows += len(chunk)
50
+ excluded += int(chunk.v_rel.gt(max_relative_speed).sum())
51
+ chunk = chunk.loc[chunk.v_rel.le(max_relative_speed)].copy()
52
+ chunk["round_v"] = np.round(chunk.v_rel, 1)
53
+ counts.update({(int(c), float(v)): int(n) for (c, v), n in chunk.groupby(["cangle", "round_v"]).size().items()})
54
+ if not counts:
55
+ raise ValueError("No eligible candidate records at or below the maximum relative speed")
56
+ if not any(n >= target for n in counts.values()) and not any(sum(n for (c, _), n in counts.items() if c == category) >= target for category in (0, 1)):
57
+ raise ValueError("Insufficient observations to form any complete fitting group; no balanced CSV written")
58
+ rng = np.random.default_rng(seed)
59
+ selected = {key: np.sort(rng.choice(count, target, replace=False)) for key, count in sorted(counts.items()) if count >= target}
60
+ offsets = defaultdict(int)
61
+ groups, dropped_sparse = [], {}
62
+ dense_rows = 0
63
+ if work_dir is not None:
64
+ Path(work_dir).mkdir(parents=True, exist_ok=True)
65
+ with tempfile.TemporaryDirectory(prefix="pair_balance_", dir=work_dir) as temporary_dir:
66
+ dense_path = Path(temporary_dir) / "dense.csv"
67
+ con = sqlite3.connect(Path(temporary_dir) / "sparse.sqlite")
68
+ try:
69
+ con.execute("CREATE TABLE sparse (ordinal INTEGER PRIMARY KEY, Frame INTEGER, EV_Vehicle_ID INTEGER, POV_Vehicle_ID INTEGER, x_local REAL, y_local REAL, v_rel REAL, cangle INTEGER)")
70
+ ordinal = 0
71
+ for chunk in read_chunks(source, chunksize):
72
+ chunk = chunk.loc[chunk.v_rel.le(max_relative_speed)].copy()
73
+ chunk["round_v"] = np.round(chunk.v_rel, 1)
74
+ for key, group in chunk.groupby(["cangle", "round_v"], sort=True):
75
+ key = int(key[0]), float(key[1])
76
+ if key in selected:
77
+ start, stop = offsets[key], offsets[key] + len(group)
78
+ choice = selected[key]
79
+ local = choice[(choice >= start) & (choice < stop)] - start
80
+ part = group.iloc[local].copy()
81
+ part["Sample_Group_ID"] = f"dense_{key[0]}_{int(round(key[1] * 10))}"
82
+ if len(part):
83
+ part[OUTPUT_COLUMNS].to_csv(dense_path, mode="a", header=not dense_path.exists(), index=False)
84
+ dense_rows += len(part)
85
+ offsets[key] = stop
86
+ else:
87
+ records = [(ordinal + i, int(r.Frame), int(r.EV_Vehicle_ID), int(r.POV_Vehicle_ID), float(r.x_local), float(r.y_local), float(r.v_rel), int(r.cangle)) for i, r in enumerate(group[INPUT_COLUMNS].itertuples(index=False))]
88
+ con.executemany("INSERT INTO sparse VALUES (?,?,?,?,?,?,?,?)", records)
89
+ ordinal += len(records)
90
+ con.commit()
91
+ if (source.stat().st_size, source.stat().st_mtime_ns) != initial_stat:
92
+ raise ValueError("Input changed between sampling passes")
93
+ if any(offsets[key] != counts[key] for key in selected) or dense_rows != len(selected) * target:
94
+ raise RuntimeError("Sampling counts changed; refusing an incomplete dense sample")
95
+ for (cangle, speed), size in sorted(counts.items()):
96
+ if (cangle, speed) in selected:
97
+ groups.append({"Sample_Group_ID": f"dense_{cangle}_{int(round(speed * 10))}", "cangle": cangle, "round_v": speed,
98
+ "kind": "dense_rounded_bin", "input_count": size, "output_count": target})
99
+ con.execute("CREATE INDEX sparse_speed ON sparse(cangle,v_rel,ordinal)")
100
+ with output_path(output) as temporary:
101
+ if dense_path.exists():
102
+ shutil.copyfile(dense_path, temporary)
103
+ else:
104
+ pd.DataFrame(columns=OUTPUT_COLUMNS).to_csv(temporary, index=False)
105
+ for category in (0, 1):
106
+ cursor = con.execute("SELECT Frame,EV_Vehicle_ID,POV_Vehicle_ID,x_local,y_local,v_rel,cangle FROM sparse WHERE cangle=? ORDER BY v_rel,ordinal", (category,))
107
+ index = 0
108
+ while True:
109
+ records = cursor.fetchmany(target)
110
+ if len(records) < target:
111
+ dropped_sparse[str(category)] = len(records)
112
+ break
113
+ group = pd.DataFrame.from_records(records, columns=INPUT_COLUMNS)
114
+ group["round_v"] = float(np.round(group.v_rel.mean(), 1))
115
+ group["Sample_Group_ID"] = f"sparse_{category}_{index}"
116
+ group[OUTPUT_COLUMNS].to_csv(temporary, mode="a", header=False, index=False)
117
+ groups.append({"Sample_Group_ID": f"sparse_{category}_{index}", "cangle": category, "round_v": float(group.round_v.iloc[0]),
118
+ "kind": "pooled_sparse_sorted_block", "input_count": target, "output_count": target,
119
+ "v_min": float(group.v_rel.min()), "v_max": float(group.v_rel.max())})
120
+ index += 1
121
+ finally:
122
+ con.close()
123
+ keys = Counter((g["cangle"], g["round_v"]) for g in groups)
124
+ audit = {"input_rows": input_rows, "input_bytes": initial_stat[0], "excluded_above_max_relative_speed": excluded,
125
+ "max_relative_speed_mps": max_relative_speed, "target_samples": target, "seed": seed,
126
+ "dense_sampling": "Exact uniform sampling without replacement; RNG PCG64; deterministic for this row order and seed",
127
+ "sparse_grouping": "Pool nondense bins within category; sort by v_rel then original order; full target-sized blocks; drop final remainder",
128
+ "sparse_remainder_discarded": dropped_sparse, "groups": groups, "output_rows": len(groups) * target,
129
+ "representative_key_collisions": [{"cangle": c, "round_v": v, "group_count": n} for (c, v), n in keys.items() if n > 1],
130
+ "historical_sample_identity": "Original script had no seed. This seeded sample cannot be claimed identical to historical samples."}
131
+ with output_path(audit_path) as temporary:
132
+ Path(temporary).write_text(json.dumps(audit, indent=2, allow_nan=False), encoding="utf-8")
133
+ return audit
134
+
135
+
136
+ def main():
137
+ p = parser(__doc__)
138
+ p.add_argument("--input", required=True, help="Frame-sorted full candidate-pair CSV")
139
+ p.add_argument("--output", required=True, help="New balanced sample CSV; use only for fitting")
140
+ p.add_argument("--audit", required=True, help="New JSON group counts, discarded remainders and key collisions")
141
+ p.add_argument("--target-samples", type=int, default=50000, help="Original production value: 50000")
142
+ p.add_argument("--max-relative-speed", type=float, default=30., help="Original fitting cutoff in m/s; not the annotation cutoff")
143
+ p.add_argument("--seed", type=int, default=42)
144
+ p.add_argument("--chunksize", type=int, default=500000)
145
+ p.add_argument("--work-dir", help="Writable scratch directory for sparse rows; needs disk capacity")
146
+ a = p.parse_args()
147
+ balance(a.input, a.output, a.audit, a.target_samples, a.max_relative_speed, a.seed, a.chunksize, a.work_dir)
148
+
149
+
150
+ if __name__ == "__main__":
151
+ main()
Processing_Code/calibrations/WS1_2.json ADDED
@@ -0,0 +1,861 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "template_only": false,
3
+ "scene_id": "WS1_2",
4
+ "master_source": "video4",
5
+ "origin_px": [
6
+ 0,
7
+ 935.66
8
+ ],
9
+ "rotation_rad": 0,
10
+ "reference_segments": [
11
+ {
12
+ "name": "Longitudinal_1",
13
+ "point_a": [
14
+ 1035.26,
15
+ 786.82
16
+ ],
17
+ "point_b": [
18
+ 1608.77,
19
+ 788.18
20
+ ],
21
+ "real_distance_m": 75.0
22
+ },
23
+ {
24
+ "name": "Longitudinal_2",
25
+ "point_a": [
26
+ 1037.48,
27
+ 815.6
28
+ ],
29
+ "point_b": [
30
+ 1610.47,
31
+ 816.82
32
+ ],
33
+ "real_distance_m": 75.0
34
+ }
35
+ ],
36
+ "sources": {
37
+ "video1": {
38
+ "src_points": [
39
+ [
40
+ 10.47,
41
+ 568.92
42
+ ],
43
+ [
44
+ 573.57,
45
+ 598.92
46
+ ],
47
+ [
48
+ 1181.65,
49
+ 617.19
50
+ ],
51
+ [
52
+ 1804.54,
53
+ 629.72
54
+ ],
55
+ [
56
+ 2342.39,
57
+ 628.12
58
+ ],
59
+ [
60
+ 2676.28,
61
+ 571.96
62
+ ],
63
+ [
64
+ 157.27,
65
+ 745.63
66
+ ],
67
+ [
68
+ 906.15,
69
+ 745.27
70
+ ],
71
+ [
72
+ 1662.34,
73
+ 746.97
74
+ ],
75
+ [
76
+ 2462.1,
77
+ 748.09
78
+ ],
79
+ [
80
+ 7.62,
81
+ 914.35
82
+ ],
83
+ [
84
+ 582.98,
85
+ 895.6
86
+ ],
87
+ [
88
+ 1183.89,
89
+ 872.57
90
+ ],
91
+ [
92
+ 1858.88,
93
+ 868.35
94
+ ],
95
+ [
96
+ 2374.96,
97
+ 879.15
98
+ ],
99
+ [
100
+ 2683.75,
101
+ 925.31
102
+ ],
103
+ [
104
+ 872.47,
105
+ 607.48
106
+ ],
107
+ [
108
+ 1480.3,
109
+ 629.84
110
+ ],
111
+ [
112
+ 2082.22,
113
+ 630.8
114
+ ],
115
+ [
116
+ 2644.72,
117
+ 579.09
118
+ ],
119
+ [
120
+ 567.9,
121
+ 744.9
122
+ ],
123
+ [
124
+ 1274.73,
125
+ 746.22
126
+ ],
127
+ [
128
+ 1993.25,
129
+ 747.2
130
+ ],
131
+ [
132
+ 831.64,
133
+ 887.64
134
+ ],
135
+ [
136
+ 1516.24,
137
+ 867.87
138
+ ],
139
+ [
140
+ 2167.66,
141
+ 868.46
142
+ ]
143
+ ],
144
+ "master_points": [
145
+ [
146
+ 102.09,
147
+ 586.15
148
+ ],
149
+ [
150
+ 644.25,
151
+ 614.95
152
+ ],
153
+ [
154
+ 1227.79,
155
+ 632.47
156
+ ],
157
+ [
158
+ 1825.63,
159
+ 644.42
160
+ ],
161
+ [
162
+ 2341.49,
163
+ 641.29
164
+ ],
165
+ [
166
+ 2662.02,
167
+ 586.6
168
+ ],
169
+ [
170
+ 242.69,
171
+ 755.11
172
+ ],
173
+ [
174
+ 961.97,
175
+ 755.3
176
+ ],
177
+ [
178
+ 1688.42,
179
+ 756.36
180
+ ],
181
+ [
182
+ 2456.58,
183
+ 756.89
184
+ ],
185
+ [
186
+ 98.47,
187
+ 918.12
188
+ ],
189
+ [
190
+ 650.68,
191
+ 899.53
192
+ ],
193
+ [
194
+ 1230.18,
195
+ 877.68
196
+ ],
197
+ [
198
+ 1877.52,
199
+ 872.45
200
+ ],
201
+ [
202
+ 2373.04,
203
+ 882.52
204
+ ],
205
+ [
206
+ 2671.45,
207
+ 926.97
208
+ ],
209
+ [
210
+ 931.28,
211
+ 622.65
212
+ ],
213
+ [
214
+ 1514.32,
215
+ 644.23
216
+ ],
217
+ [
218
+ 2092.39,
219
+ 644.72
220
+ ],
221
+ [
222
+ 2632.33,
223
+ 594.6
224
+ ],
225
+ [
226
+ 646.84,
227
+ 754.54
228
+ ],
229
+ [
230
+ 1316.54,
231
+ 755.53
232
+ ],
233
+ [
234
+ 2006.33,
235
+ 756.37
236
+ ],
237
+ [
238
+ 888.66,
239
+ 891.8
240
+ ],
241
+ [
242
+ 1547.9,
243
+ 872.41
244
+ ],
245
+ [
246
+ 2174.38,
247
+ 872.54
248
+ ]
249
+ ]
250
+ },
251
+ "video2": {
252
+ "src_points": [
253
+ [
254
+ 8.25,
255
+ 578.85
256
+ ],
257
+ [
258
+ 551.09,
259
+ 605.76
260
+ ],
261
+ [
262
+ 1179.97,
263
+ 624.57
264
+ ],
265
+ [
266
+ 1804.47,
267
+ 636.7
268
+ ],
269
+ [
270
+ 2344.73,
271
+ 633.92
272
+ ],
273
+ [
274
+ 2680.1,
275
+ 577.17
276
+ ],
277
+ [
278
+ 155.9,
279
+ 755.19
280
+ ],
281
+ [
282
+ 905.04,
283
+ 754.24
284
+ ],
285
+ [
286
+ 1662.77,
287
+ 754.43
288
+ ],
289
+ [
290
+ 2465.16,
291
+ 754.74
292
+ ],
293
+ [
294
+ 7.62,
295
+ 924.63
296
+ ],
297
+ [
298
+ 580.44,
299
+ 905.23
300
+ ],
301
+ [
302
+ 1182.69,
303
+ 881.15
304
+ ],
305
+ [
306
+ 1860.24,
307
+ 875.75
308
+ ],
309
+ [
310
+ 2376.93,
311
+ 886.25
312
+ ],
313
+ [
314
+ 2662.96,
315
+ 930.09
316
+ ],
317
+ [
318
+ 870.49,
319
+ 614.76
320
+ ],
321
+ [
322
+ 1479.74,
323
+ 636.53
324
+ ],
325
+ [
326
+ 2083.32,
327
+ 636.96
328
+ ],
329
+ [
330
+ 507.44,
331
+ 754.79
332
+ ],
333
+ [
334
+ 1273.77,
335
+ 753.85
336
+ ],
337
+ [
338
+ 1925.63,
339
+ 753.58
340
+ ],
341
+ [
342
+ 850.72,
343
+ 895.65
344
+ ],
345
+ [
346
+ 1433.37,
347
+ 877.76
348
+ ],
349
+ [
350
+ 2098.21,
351
+ 875.49
352
+ ]
353
+ ],
354
+ "master_points": [
355
+ [
356
+ 102.16,
357
+ 586.01
358
+ ],
359
+ [
360
+ 625.0,
361
+ 613.37
362
+ ],
363
+ [
364
+ 1227.91,
365
+ 632.55
366
+ ],
367
+ [
368
+ 1825.41,
369
+ 643.8
370
+ ],
371
+ [
372
+ 2341.61,
373
+ 642.12
374
+ ],
375
+ [
376
+ 2661.95,
377
+ 586.75
378
+ ],
379
+ [
380
+ 242.75,
381
+ 755.35
382
+ ],
383
+ [
384
+ 962.14,
385
+ 755.59
386
+ ],
387
+ [
388
+ 1688.69,
389
+ 756.14
390
+ ],
391
+ [
392
+ 2456.29,
393
+ 757.19
394
+ ],
395
+ [
396
+ 99.46,
397
+ 917.73
398
+ ],
399
+ [
400
+ 650.75,
401
+ 899.84
402
+ ],
403
+ [
404
+ 1230.13,
405
+ 877.74
406
+ ],
407
+ [
408
+ 1877.69,
409
+ 872.57
410
+ ],
411
+ [
412
+ 2372.66,
413
+ 883.12
414
+ ],
415
+ [
416
+ 2645.67,
417
+ 924.27
418
+ ],
419
+ [
420
+ 931.42,
421
+ 622.78
422
+ ],
423
+ [
424
+ 1514.57,
425
+ 643.66
426
+ ],
427
+ [
428
+ 2091.7,
429
+ 644.89
430
+ ],
431
+ [
432
+ 578.93,
433
+ 754.78
434
+ ],
435
+ [
436
+ 1316.34,
437
+ 755.26
438
+ ],
439
+ [
440
+ 1939.14,
441
+ 755.85
442
+ ],
443
+ [
444
+ 909.56,
445
+ 890.88
446
+ ],
447
+ [
448
+ 1468.43,
449
+ 874.3
450
+ ],
451
+ [
452
+ 2105.57,
453
+ 873.03
454
+ ]
455
+ ]
456
+ },
457
+ "video3": {
458
+ "src_points": [
459
+ [
460
+ 13.09,
461
+ 579.88
462
+ ],
463
+ [
464
+ 563.15,
465
+ 608.49
466
+ ],
467
+ [
468
+ 1174.57,
469
+ 625.36
470
+ ],
471
+ [
472
+ 1801.76,
473
+ 637.5
474
+ ],
475
+ [
476
+ 2342.99,
477
+ 634.21
478
+ ],
479
+ [
480
+ 2679.14,
481
+ 577.19
482
+ ],
483
+ [
484
+ 144.65,
485
+ 756.34
486
+ ],
487
+ [
488
+ 898.55,
489
+ 755.6
490
+ ],
491
+ [
492
+ 1659.17,
493
+ 755.23
494
+ ],
495
+ [
496
+ 2396.58,
497
+ 754.16
498
+ ],
499
+ [
500
+ 13.13,
501
+ 926.9
502
+ ],
503
+ [
504
+ 567.39,
505
+ 907.6
506
+ ],
507
+ [
508
+ 1177.53,
509
+ 882.3
510
+ ],
511
+ [
512
+ 1809.59,
513
+ 876.45
514
+ ],
515
+ [
516
+ 2344.29,
517
+ 881.82
518
+ ],
519
+ [
520
+ 2661.15,
521
+ 929.86
522
+ ]
523
+ ],
524
+ "master_points": [
525
+ [
526
+ 115.95,
527
+ 586.43
528
+ ],
529
+ [
530
+ 644.56,
531
+ 615.25
532
+ ],
533
+ [
534
+ 1227.64,
535
+ 632.69
536
+ ],
537
+ [
538
+ 1825.66,
539
+ 644.96
540
+ ],
541
+ [
542
+ 2341.81,
543
+ 642.25
544
+ ],
545
+ [
546
+ 2662.84,
547
+ 586.43
548
+ ],
549
+ [
550
+ 242.41,
551
+ 755.05
552
+ ],
553
+ [
554
+ 962.0,
555
+ 755.54
556
+ ],
557
+ [
558
+ 1688.74,
559
+ 755.82
560
+ ],
561
+ [
562
+ 2393.73,
563
+ 756.5
564
+ ],
565
+ [
566
+ 114.87,
567
+ 917.34
568
+ ],
569
+ [
570
+ 645.33,
571
+ 899.7
572
+ ],
573
+ [
574
+ 1230.48,
575
+ 877.69
576
+ ],
577
+ [
578
+ 1831.81,
579
+ 872.44
580
+ ],
581
+ [
582
+ 2343.46,
583
+ 878.69
584
+ ],
585
+ [
586
+ 2645.85,
587
+ 924.36
588
+ ]
589
+ ]
590
+ },
591
+ "video4": {},
592
+ "video5": {
593
+ "src_points": [
594
+ [
595
+ 4.95,
596
+ 581.58
597
+ ],
598
+ [
599
+ 613.77,
600
+ 611.65
601
+ ],
602
+ [
603
+ 1223.2,
604
+ 631.11
605
+ ],
606
+ [
607
+ 1827.78,
608
+ 642.88
609
+ ],
610
+ [
611
+ 2349.89,
612
+ 640.93
613
+ ],
614
+ [
615
+ 2673.07,
616
+ 586.28
617
+ ],
618
+ [
619
+ 225.48,
620
+ 754.66
621
+ ],
622
+ [
623
+ 954.47,
624
+ 755.52
625
+ ],
626
+ [
627
+ 1689.35,
628
+ 756.27
629
+ ],
630
+ [
631
+ 2514.17,
632
+ 757.58
633
+ ],
634
+ [
635
+ 11.77,
636
+ 922.01
637
+ ],
638
+ [
639
+ 572.27,
640
+ 903.47
641
+ ],
642
+ [
643
+ 1225.88,
644
+ 878.5
645
+ ],
646
+ [
647
+ 1879.98,
648
+ 874.28
649
+ ],
650
+ [
651
+ 2333.58,
652
+ 877.51
653
+ ],
654
+ [
655
+ 2681.35,
656
+ 929.45
657
+ ]
658
+ ],
659
+ "master_points": [
660
+ [
661
+ 24.13,
662
+ 583.58
663
+ ],
664
+ [
665
+ 625.28,
666
+ 613.47
667
+ ],
668
+ [
669
+ 1227.53,
670
+ 632.5
671
+ ],
672
+ [
673
+ 1825.86,
674
+ 644.08
675
+ ],
676
+ [
677
+ 2341.71,
678
+ 641.96
679
+ ],
680
+ [
681
+ 2661.85,
682
+ 587.08
683
+ ],
684
+ [
685
+ 241.82,
686
+ 755.15
687
+ ],
688
+ [
689
+ 962.17,
690
+ 755.59
691
+ ],
692
+ [
693
+ 1688.6,
694
+ 756.22
695
+ ],
696
+ [
697
+ 2504.68,
698
+ 756.55
699
+ ],
700
+ [
701
+ 30.47,
702
+ 920.61
703
+ ],
704
+ [
705
+ 584.63,
706
+ 902.04
707
+ ],
708
+ [
709
+ 1230.34,
710
+ 877.4
711
+ ],
712
+ [
713
+ 1876.76,
714
+ 872.78
715
+ ],
716
+ [
717
+ 2326.66,
718
+ 875.95
719
+ ],
720
+ [
721
+ 2671.26,
722
+ 927.29
723
+ ]
724
+ ]
725
+ },
726
+ "video6": {
727
+ "src_points": [
728
+ [
729
+ 13.47,
730
+ 579.34
731
+ ],
732
+ [
733
+ 621.39,
734
+ 608.89
735
+ ],
736
+ [
737
+ 1230.64,
738
+ 627.12
739
+ ],
740
+ [
741
+ 1835.5,
742
+ 638.97
743
+ ],
744
+ [
745
+ 2358.41,
746
+ 636.54
747
+ ],
748
+ [
749
+ 2681.94,
750
+ 580.67
751
+ ],
752
+ [
753
+ 234.77,
754
+ 752.77
755
+ ],
756
+ [
757
+ 962.56,
758
+ 752.6
759
+ ],
760
+ [
761
+ 1696.59,
762
+ 752.99
763
+ ],
764
+ [
765
+ 2522.72,
766
+ 752.64
767
+ ],
768
+ [
769
+ 16.33,
770
+ 920.06
771
+ ],
772
+ [
773
+ 647.08,
774
+ 898.74
775
+ ],
776
+ [
777
+ 1233.7,
778
+ 875.45
779
+ ],
780
+ [
781
+ 1913.18,
782
+ 870.4
783
+ ],
784
+ [
785
+ 2359.41,
786
+ 875.25
787
+ ],
788
+ [
789
+ 2665.59,
790
+ 922.17
791
+ ]
792
+ ],
793
+ "master_points": [
794
+ [
795
+ 23.98,
796
+ 583.01
797
+ ],
798
+ [
799
+ 625.19,
800
+ 613.22
801
+ ],
802
+ [
803
+ 1227.39,
804
+ 632.54
805
+ ],
806
+ [
807
+ 1825.91,
808
+ 644.4
809
+ ],
810
+ [
811
+ 2341.93,
812
+ 641.67
813
+ ],
814
+ [
815
+ 2662.25,
816
+ 586.87
817
+ ],
818
+ [
819
+ 241.76,
820
+ 754.95
821
+ ],
822
+ [
823
+ 962.09,
824
+ 755.59
825
+ ],
826
+ [
827
+ 1688.44,
828
+ 756.39
829
+ ],
830
+ [
831
+ 2504.33,
832
+ 756.6
833
+ ],
834
+ [
835
+ 25.91,
836
+ 920.55
837
+ ],
838
+ [
839
+ 650.36,
840
+ 899.96
841
+ ],
842
+ [
843
+ 1230.32,
844
+ 877.47
845
+ ],
846
+ [
847
+ 1902.25,
848
+ 872.42
849
+ ],
850
+ [
851
+ 2343.24,
852
+ 877.9
853
+ ],
854
+ [
855
+ 2645.78,
856
+ 924.65
857
+ ]
858
+ ]
859
+ }
860
+ }
861
+ }
Processing_Code/calibrations/WS3.json ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "template_only": false,
3
+ "scene_id": "WS3",
4
+ "master_source": "video2",
5
+ "origin_px": [
6
+ 0,
7
+ 1186.58
8
+ ],
9
+ "rotation_rad": 0,
10
+ "reference_segments": [
11
+ {
12
+ "name": "Longitudinal_1",
13
+ "point_a": [
14
+ 1973.37,
15
+ 1066.24
16
+ ],
17
+ "point_b": [
18
+ 2458.45,
19
+ 1065.63
20
+ ],
21
+ "real_distance_m": 45.0
22
+ },
23
+ {
24
+ "name": "Longitudinal_2",
25
+ "point_a": [
26
+ 1889.07,
27
+ 1066.44
28
+ ],
29
+ "point_b": [
30
+ 2526.23,
31
+ 1065.54
32
+ ],
33
+ "real_distance_m": 60.0
34
+ }
35
+ ],
36
+ "sources": {
37
+ "video1": {
38
+ "src_points": [
39
+ [
40
+ 99.23,
41
+ 768.95
42
+ ],
43
+ [
44
+ 895.6,
45
+ 771.98
46
+ ],
47
+ [
48
+ 1470.46,
49
+ 772.33
50
+ ],
51
+ [
52
+ 2036.64,
53
+ 774.03
54
+ ],
55
+ [
56
+ 2493.1,
57
+ 775.63
58
+ ],
59
+ [
60
+ 439.07,
61
+ 819.22
62
+ ],
63
+ [
64
+ 1213.69,
65
+ 819.97
66
+ ],
67
+ [
68
+ 1794.76,
69
+ 823.52
70
+ ],
71
+ [
72
+ 2227.04,
73
+ 822.36
74
+ ],
75
+ [
76
+ 99.62,
77
+ 868.63
78
+ ],
79
+ [
80
+ 848.89,
81
+ 868.79
82
+ ],
83
+ [
84
+ 1469.25,
85
+ 871.77
86
+ ],
87
+ [
88
+ 2041.45,
89
+ 873.67
90
+ ],
91
+ [
92
+ 2582.4,
93
+ 875.31
94
+ ]
95
+ ],
96
+ "master_points": [
97
+ [
98
+ 250.51,
99
+ 1021.43
100
+ ],
101
+ [
102
+ 1242.84,
103
+ 1022.3
104
+ ],
105
+ [
106
+ 1972.84,
107
+ 1021.88
108
+ ],
109
+ [
110
+ 2700.84,
111
+ 1023.02
112
+ ],
113
+ [
114
+ 3292.41,
115
+ 1025.09
116
+ ],
117
+ [
118
+ 658.89,
119
+ 1086.21
120
+ ],
121
+ [
122
+ 1644.91,
123
+ 1085.26
124
+ ],
125
+ [
126
+ 2381.57,
127
+ 1087.7
128
+ ],
129
+ [
130
+ 2945.6,
131
+ 1086.42
132
+ ],
133
+ [
134
+ 251.18,
135
+ 1148.96
136
+ ],
137
+ [
138
+ 1183.17,
139
+ 1148.41
140
+ ],
141
+ [
142
+ 1971.09,
143
+ 1151.12
144
+ ],
145
+ [
146
+ 2706.15,
147
+ 1153.33
148
+ ],
149
+ [
150
+ 3406.3,
151
+ 1152.97
152
+ ]
153
+ ]
154
+ },
155
+ "video2": {},
156
+ "video3": {
157
+ "src_points": [
158
+ [
159
+ 53.03,
160
+ 1036.01
161
+ ],
162
+ [
163
+ 1029.74,
164
+ 1037.77
165
+ ],
166
+ [
167
+ 1748.41,
168
+ 1040.53
169
+ ],
170
+ [
171
+ 2586.88,
172
+ 1040.77
173
+ ],
174
+ [
175
+ 3462.61,
176
+ 1043.58
177
+ ],
178
+ [
179
+ 3815.7,
180
+ 1044.81
181
+ ],
182
+ [
183
+ 595.36,
184
+ 1101.92
185
+ ],
186
+ [
187
+ 1431.17,
188
+ 1101.72
189
+ ],
190
+ [
191
+ 2242.9,
192
+ 1104.18
193
+ ],
194
+ [
195
+ 3044.11,
196
+ 1114.2
197
+ ],
198
+ [
199
+ 3643.8,
200
+ 1111.43
201
+ ],
202
+ [
203
+ 22.41,
204
+ 1169.68
205
+ ],
206
+ [
207
+ 1028.21,
208
+ 1164.39
209
+ ],
210
+ [
211
+ 1833.46,
212
+ 1169.24
213
+ ],
214
+ [
215
+ 2666.48,
216
+ 1173.33
217
+ ],
218
+ [
219
+ 3484.12,
220
+ 1181.29
221
+ ],
222
+ [
223
+ 3815.17,
224
+ 1207.3
225
+ ]
226
+ ],
227
+ "master_points": [
228
+ [
229
+ 102.5,
230
+ 1021.39
231
+ ],
232
+ [
233
+ 1089.7,
234
+ 1022.35
235
+ ],
236
+ [
237
+ 1803.92,
238
+ 1022.38
239
+ ],
240
+ [
241
+ 2627.2,
242
+ 1022.25
243
+ ],
244
+ [
245
+ 3475.8,
246
+ 1023.66
247
+ ],
248
+ [
249
+ 3814.67,
250
+ 1024.4
251
+ ],
252
+ [
253
+ 659.31,
254
+ 1085.76
255
+ ],
256
+ [
257
+ 1490.1,
258
+ 1085.58
259
+ ],
260
+ [
261
+ 2292.23,
262
+ 1087.24
263
+ ],
264
+ [
265
+ 3073.29,
266
+ 1095.64
267
+ ],
268
+ [
269
+ 3650.65,
270
+ 1088.52
271
+ ],
272
+ [
273
+ 66.58,
274
+ 1156.41
275
+ ],
276
+ [
277
+ 1087.53,
278
+ 1148.21
279
+ ],
280
+ [
281
+ 1889.36,
282
+ 1150.39
283
+ ],
284
+ [
285
+ 2706.68,
286
+ 1152.82
287
+ ],
288
+ [
289
+ 3496.95,
290
+ 1158.35
291
+ ],
292
+ [
293
+ 3814.49,
294
+ 1184.0
295
+ ]
296
+ ]
297
+ }
298
+ }
299
+ }
Processing_Code/calibrations/WS4_5.json ADDED
@@ -0,0 +1,489 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "template_only": false,
3
+ "scene_id": "WS4_5",
4
+ "master_source": "video1",
5
+ "origin_px": [
6
+ 71.23,
7
+ 1467.28
8
+ ],
9
+ "rotation_rad": 0,
10
+ "reference_segments": [
11
+ {
12
+ "name": "Longitudinal_1",
13
+ "point_a": [
14
+ 1177.46,
15
+ 1166.23
16
+ ],
17
+ "point_b": [
18
+ 1882.83,
19
+ 1168.11
20
+ ],
21
+ "real_distance_m": 75
22
+ },
23
+ {
24
+ "name": "Longitudinal_2",
25
+ "point_a": [
26
+ 1251.59,
27
+ 1265.04
28
+ ],
29
+ "point_b": [
30
+ 1959.74,
31
+ 1268.91
32
+ ],
33
+ "real_distance_m": 75
34
+ }
35
+ ],
36
+ "sources": {
37
+ "video2": {
38
+ "src_points": [
39
+ [
40
+ 282.4,
41
+ 1083.76
42
+ ],
43
+ [
44
+ 1350.58,
45
+ 1133.24
46
+ ],
47
+ [
48
+ 1914.41,
49
+ 1132.36
50
+ ],
51
+ [
52
+ 2601.59,
53
+ 1131.64
54
+ ],
55
+ [
56
+ 3281.37,
57
+ 1132.82
58
+ ],
59
+ [
60
+ 3643.54,
61
+ 1132.83
62
+ ],
63
+ [
64
+ 309.71,
65
+ 1282.26
66
+ ],
67
+ [
68
+ 1149.19,
69
+ 1283.07
70
+ ],
71
+ [
72
+ 2072.06,
73
+ 1284.81
74
+ ],
75
+ [
76
+ 2962.76,
77
+ 1285.08
78
+ ],
79
+ [
80
+ 3686.2,
81
+ 1284.84
82
+ ],
83
+ [
84
+ 319.54,
85
+ 1472.86
86
+ ],
87
+ [
88
+ 1276.31,
89
+ 1434.92
90
+ ],
91
+ [
92
+ 2003.94,
93
+ 1438.48
94
+ ],
95
+ [
96
+ 2656.03,
97
+ 1439.66
98
+ ],
99
+ [
100
+ 3250.06,
101
+ 1439.73
102
+ ],
103
+ [
104
+ 3482.58,
105
+ 1443.4
106
+ ]
107
+ ],
108
+ "master_points": [
109
+ [
110
+ 283.23,
111
+ 1025.48
112
+ ],
113
+ [
114
+ 1324.96,
115
+ 1077.47
116
+ ],
117
+ [
118
+ 1872.95,
119
+ 1078.31
120
+ ],
121
+ [
122
+ 2539.47,
123
+ 1080.47
124
+ ],
125
+ [
126
+ 3200.08,
127
+ 1083.99
128
+ ],
129
+ [
130
+ 3558.61,
131
+ 1085.11
132
+ ],
133
+ [
134
+ 309.33,
135
+ 1219.71
136
+ ],
137
+ [
138
+ 1129.26,
139
+ 1223.25
140
+ ],
141
+ [
142
+ 2026.23,
143
+ 1228.28
144
+ ],
145
+ [
146
+ 2894.39,
147
+ 1230.51
148
+ ],
149
+ [
150
+ 3601.22,
151
+ 1233.79
152
+ ],
153
+ [
154
+ 318.77,
155
+ 1407.11
156
+ ],
157
+ [
158
+ 1252.8,
159
+ 1371.47
160
+ ],
161
+ [
162
+ 1960.45,
163
+ 1376.41
164
+ ],
165
+ [
166
+ 2594.64,
167
+ 1380
168
+ ],
169
+ [
170
+ 3171.19,
171
+ 1381.96
172
+ ],
173
+ [
174
+ 3399.45,
175
+ 1387.03
176
+ ]
177
+ ]
178
+ },
179
+ "video1": {},
180
+ "video3": {
181
+ "src_points": [
182
+ [
183
+ 111.89,
184
+ 888.03
185
+ ],
186
+ [
187
+ 1009.2,
188
+ 924.54
189
+ ],
190
+ [
191
+ 1546.84,
192
+ 928.53
193
+ ],
194
+ [
195
+ 2169.63,
196
+ 928.31
197
+ ],
198
+ [
199
+ 2897.01,
200
+ 911.78
201
+ ],
202
+ [
203
+ 3593.18,
204
+ 920.77
205
+ ],
206
+ [
207
+ 246.71,
208
+ 1076.62
209
+ ],
210
+ [
211
+ 1086.61,
212
+ 1075.66
213
+ ],
214
+ [
215
+ 2012.03,
216
+ 1076.62
217
+ ],
218
+ [
219
+ 2908.65,
220
+ 1075.09
221
+ ],
222
+ [
223
+ 3431.95,
224
+ 1073.11
225
+ ],
226
+ [
227
+ 250.41,
228
+ 1271.35
229
+ ],
230
+ [
231
+ 990.31,
232
+ 1240.16
233
+ ],
234
+ [
235
+ 1853.17,
236
+ 1232.62
237
+ ],
238
+ [
239
+ 1532.06,
240
+ 1232.65
241
+ ],
242
+ [
243
+ 2542.81,
244
+ 1233.41
245
+ ],
246
+ [
247
+ 3237.07,
248
+ 1232.65
249
+ ],
250
+ [
251
+ 3431.3,
252
+ 1240.78
253
+ ]
254
+ ],
255
+ "master_points": [
256
+ [
257
+ 183.34,
258
+ 1034.3
259
+ ],
260
+ [
261
+ 1056.61,
262
+ 1075.66
263
+ ],
264
+ [
265
+ 1575.82,
266
+ 1081.98
267
+ ],
268
+ [
269
+ 2177.79,
270
+ 1083.7
271
+ ],
272
+ [
273
+ 2880.28,
274
+ 1071.53
275
+ ],
276
+ [
277
+ 3560.32,
278
+ 1084.26
279
+ ],
280
+ [
281
+ 309.16,
282
+ 1218.79
283
+ ],
284
+ [
285
+ 1129.44,
286
+ 1222.59
287
+ ],
288
+ [
289
+ 2026.58,
290
+ 1228.14
291
+ ],
292
+ [
293
+ 2895.08,
294
+ 1230.8
295
+ ],
296
+ [
297
+ 3400.6,
298
+ 1231.59
299
+ ],
300
+ [
301
+ 312.15,
302
+ 1406.85
303
+ ],
304
+ [
305
+ 1034.15,
306
+ 1382.44
307
+ ],
308
+ [
309
+ 1870.45,
310
+ 1377.35
311
+ ],
312
+ [
313
+ 1560.1,
314
+ 1376.09
315
+ ],
316
+ [
317
+ 2537.04,
318
+ 1381.76
319
+ ],
320
+ [
321
+ 3206.63,
322
+ 1382.99
323
+ ],
324
+ [
325
+ 3400.02,
326
+ 1394.54
327
+ ]
328
+ ]
329
+ },
330
+ "video4": {
331
+ "src_points": [
332
+ [
333
+ 124.98,
334
+ 859.07
335
+ ],
336
+ [
337
+ 667.79,
338
+ 898.55
339
+ ],
340
+ [
341
+ 1324.23,
342
+ 908.2
343
+ ],
344
+ [
345
+ 1900.5,
346
+ 908.43
347
+ ],
348
+ [
349
+ 2600.46,
350
+ 906.77
351
+ ],
352
+ [
353
+ 3292.53,
354
+ 908.92
355
+ ],
356
+ [
357
+ 3641.38,
358
+ 902.11
359
+ ],
360
+ [
361
+ 261.39,
362
+ 1051.6
363
+ ],
364
+ [
365
+ 1118.67,
366
+ 1052.53
367
+ ],
368
+ [
369
+ 2059.55,
370
+ 1055.59
371
+ ],
372
+ [
373
+ 2966.08,
374
+ 1055.86
375
+ ],
376
+ [
377
+ 3486.28,
378
+ 1054.7
379
+ ],
380
+ [
381
+ 263.12,
382
+ 1249.4
383
+ ],
384
+ [
385
+ 882.59,
386
+ 1210.01
387
+ ],
388
+ [
389
+ 1396.07,
390
+ 1209.25
391
+ ],
392
+ [
393
+ 1988.76,
394
+ 1211.67
395
+ ],
396
+ [
397
+ 2503.03,
398
+ 1212.3
399
+ ],
400
+ [
401
+ 3192.14,
402
+ 1213.17
403
+ ],
404
+ [
405
+ 3493.46,
406
+ 1218.08
407
+ ]
408
+ ],
409
+ "master_points": [
410
+ [
411
+ 182.96,
412
+ 1035.48
413
+ ],
414
+ [
415
+ 700.18,
416
+ 1074.87
417
+ ],
418
+ [
419
+ 1325.07,
420
+ 1084.28
421
+ ],
422
+ [
423
+ 1872.61,
424
+ 1086.1
425
+ ],
426
+ [
427
+ 2539.62,
428
+ 1086.86
429
+ ],
430
+ [
431
+ 3200.64,
432
+ 1090.94
433
+ ],
434
+ [
435
+ 3545.83,
436
+ 1084.64
437
+ ],
438
+ [
439
+ 309.55,
440
+ 1218.61
441
+ ],
442
+ [
443
+ 1128.81,
444
+ 1222.71
445
+ ],
446
+ [
447
+ 2026.52,
448
+ 1228.68
449
+ ],
450
+ [
451
+ 2894,
452
+ 1230.57
453
+ ],
454
+ [
455
+ 3393.61,
456
+ 1231.28
457
+ ],
458
+ [
459
+ 312.19,
460
+ 1407.41
461
+ ],
462
+ [
463
+ 903.14,
464
+ 1372.32
465
+ ],
466
+ [
467
+ 1392.33,
468
+ 1372.92
469
+ ],
470
+ [
471
+ 1958.69,
472
+ 1377.12
473
+ ],
474
+ [
475
+ 2450.49,
476
+ 1379.83
477
+ ],
478
+ [
479
+ 3110.47,
480
+ 1382.55
481
+ ],
482
+ [
483
+ 3400.79,
484
+ 1386.85
485
+ ]
486
+ ]
487
+ }
488
+ }
489
+ }
Processing_Code/calibrations/WS6_7.json ADDED
@@ -0,0 +1,355 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "template_only": false,
3
+ "scene_id": "WS6_7",
4
+ "master_source": "video2",
5
+ "origin_px": [
6
+ 0,
7
+ 1449.51
8
+ ],
9
+ "rotation_rad": 0,
10
+ "reference_segments": [
11
+ {
12
+ "name": "Longitudinal_1",
13
+ "point_a": [
14
+ 1559.24,
15
+ 903.47
16
+ ],
17
+ "point_b": [
18
+ 2396.81,
19
+ 903.44
20
+ ],
21
+ "real_distance_m": 84.0
22
+ },
23
+ {
24
+ "name": "Longitudinal_2",
25
+ "point_a": [
26
+ 1669.47,
27
+ 1340.23
28
+ ],
29
+ "point_b": [
30
+ 2557.03,
31
+ 1343.46
32
+ ],
33
+ "real_distance_m": 90.0
34
+ }
35
+ ],
36
+ "sources": {
37
+ "video1": {
38
+ "src_points": [
39
+ [
40
+ 371.16,
41
+ 979.47
42
+ ],
43
+ [
44
+ 849.23,
45
+ 979.7
46
+ ],
47
+ [
48
+ 1515.27,
49
+ 972.62
50
+ ],
51
+ [
52
+ 2299.22,
53
+ 978.37
54
+ ],
55
+ [
56
+ 2842.26,
57
+ 970.61
58
+ ],
59
+ [
60
+ 3538.8,
61
+ 965.71
62
+ ],
63
+ [
64
+ 556.57,
65
+ 1120.12
66
+ ],
67
+ [
68
+ 1466.6,
69
+ 1118.78
70
+ ],
71
+ [
72
+ 2529.87,
73
+ 1121.04
74
+ ],
75
+ [
76
+ 3319.47,
77
+ 1123.42
78
+ ],
79
+ [
80
+ 561.26,
81
+ 1403.9
82
+ ],
83
+ [
84
+ 1507.6,
85
+ 1410.02
86
+ ],
87
+ [
88
+ 2617.82,
89
+ 1418.19
90
+ ],
91
+ [
92
+ 3353.05,
93
+ 1415.47
94
+ ],
95
+ [
96
+ 289.17,
97
+ 1555.08
98
+ ],
99
+ [
100
+ 843.21,
101
+ 1552.11
102
+ ],
103
+ [
104
+ 1567.16,
105
+ 1563.49
106
+ ],
107
+ [
108
+ 2401.03,
109
+ 1563.12
110
+ ],
111
+ [
112
+ 3053.21,
113
+ 1564.79
114
+ ],
115
+ [
116
+ 3469.06,
117
+ 1566.26
118
+ ]
119
+ ],
120
+ "master_points": [
121
+ [
122
+ 369.1,
123
+ 820.01
124
+ ],
125
+ [
126
+ 852.57,
127
+ 818.04
128
+ ],
129
+ [
130
+ 1521.82,
131
+ 809.18
132
+ ],
133
+ [
134
+ 2302.29,
135
+ 813.16
136
+ ],
137
+ [
138
+ 2843.29,
139
+ 809.51
140
+ ],
141
+ [
142
+ 3533.01,
143
+ 807.73
144
+ ],
145
+ [
146
+ 555.57,
147
+ 964.33
148
+ ],
149
+ [
150
+ 1470.17,
151
+ 960.93
152
+ ],
153
+ [
154
+ 2532.24,
155
+ 961.46
156
+ ],
157
+ [
158
+ 3318.53,
159
+ 964.47
160
+ ],
161
+ [
162
+ 559.45,
163
+ 1246.38
164
+ ],
165
+ [
166
+ 1509.9,
167
+ 1251.52
168
+ ],
169
+ [
170
+ 2621.12,
171
+ 1259.6
172
+ ],
173
+ [
174
+ 3350.41,
175
+ 1261.89
176
+ ],
177
+ [
178
+ 284.07,
179
+ 1403.27
180
+ ],
181
+ [
182
+ 845.99,
183
+ 1392.05
184
+ ],
185
+ [
186
+ 1573.01,
187
+ 1400.54
188
+ ],
189
+ [
190
+ 2403.39,
191
+ 1403.61
192
+ ],
193
+ [
194
+ 3053.87,
195
+ 1405.14
196
+ ],
197
+ [
198
+ 3466.14,
199
+ 1407.13
200
+ ]
201
+ ]
202
+ },
203
+ "video2": {},
204
+ "video3": {
205
+ "src_points": [
206
+ [
207
+ 287.25,
208
+ 706.82
209
+ ],
210
+ [
211
+ 877.94,
212
+ 708.98
213
+ ],
214
+ [
215
+ 1789.5,
216
+ 701.12
217
+ ],
218
+ [
219
+ 2613.72,
220
+ 704.35
221
+ ],
222
+ [
223
+ 3564.36,
224
+ 701.84
225
+ ],
226
+ [
227
+ 481.25,
228
+ 908.53
229
+ ],
230
+ [
231
+ 1372.38,
232
+ 891.49
233
+ ],
234
+ [
235
+ 2314.9,
236
+ 887.75
237
+ ],
238
+ [
239
+ 3155.69,
240
+ 886.32
241
+ ],
242
+ [
243
+ 480.42,
244
+ 1258.86
245
+ ],
246
+ [
247
+ 1366.04,
248
+ 1256.11
249
+ ],
250
+ [
251
+ 2255.64,
252
+ 1251.11
253
+ ],
254
+ [
255
+ 3287.08,
256
+ 1248.97
257
+ ],
258
+ [
259
+ 275.03,
260
+ 1443.64
261
+ ],
262
+ [
263
+ 897.57,
264
+ 1436.03
265
+ ],
266
+ [
267
+ 1784.97,
268
+ 1441.79
269
+ ],
270
+ [
271
+ 2672.7,
272
+ 1439.48
273
+ ],
274
+ [
275
+ 3792.64,
276
+ 1434.99
277
+ ]
278
+ ],
279
+ "master_points": [
280
+ [
281
+ 720.77,
282
+ 810.29
283
+ ],
284
+ [
285
+ 1190.83,
286
+ 815.42
287
+ ],
288
+ [
289
+ 1918.23,
290
+ 812.05
291
+ ],
292
+ [
293
+ 2580.09,
294
+ 813.52
295
+ ],
296
+ [
297
+ 3354.95,
298
+ 814.01
299
+ ],
300
+ [
301
+ 875.92,
302
+ 970.77
303
+ ],
304
+ [
305
+ 1581.82,
306
+ 960.8
307
+ ],
308
+ [
309
+ 2336.81,
310
+ 961.31
311
+ ],
312
+ [
313
+ 3020.61,
314
+ 962.88
315
+ ],
316
+ [
317
+ 877.43,
318
+ 1247.96
319
+ ],
320
+ [
321
+ 1574.72,
322
+ 1251.15
323
+ ],
324
+ [
325
+ 2283.57,
326
+ 1252.43
327
+ ],
328
+ [
329
+ 3116.04,
330
+ 1255.51
331
+ ],
332
+ [
333
+ 717.62,
334
+ 1391.54
335
+ ],
336
+ [
337
+ 1208.25,
338
+ 1392.35
339
+ ],
340
+ [
341
+ 1909.67,
342
+ 1402.43
343
+ ],
344
+ [
345
+ 2616.24,
346
+ 1404.26
347
+ ],
348
+ [
349
+ 3527.05,
350
+ 1407.92
351
+ ]
352
+ ]
353
+ }
354
+ }
355
+ }
Processing_Code/configs/basic_manifest.csv ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Scene_ID,Basic_File
2
+ WS1_2,data/basic/Weaving Segments_1_2.csv
3
+ WS3,data/basic/Weaving Segment_3.csv
4
+ WS4_5,data/basic/Weaving Segments_4_5.csv
5
+ WS6_7,data/basic/Weaving Segments_6_7.csv
Processing_Code/configs/source_manifest.csv ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Scene_ID,Source_ID,Raw_File,FPS,Calibration_File,Master_Source
2
+ WS1_2,video1,data/raw/WS1_2_raw_detection_data_1.csv,60,calibrations/WS1_2.json,video4
3
+ WS1_2,video2,data/raw/WS1_2_raw_detection_data_2.csv,60,calibrations/WS1_2.json,video4
4
+ WS1_2,video3,data/raw/WS1_2_raw_detection_data_3.csv,60,calibrations/WS1_2.json,video4
5
+ WS1_2,video4,data/raw/WS1_2_raw_detection_data_4.csv,60,calibrations/WS1_2.json,video4
6
+ WS1_2,video5,data/raw/WS1_2_raw_detection_data_5.csv,60,calibrations/WS1_2.json,video4
7
+ WS1_2,video6,data/raw/WS1_2_raw_detection_data_6.csv,60,calibrations/WS1_2.json,video4
8
+ WS3,video1,data/raw/WS3_raw_detection_data_1.csv,60,calibrations/WS3.json,video2
9
+ WS3,video2,data/raw/WS3_raw_detection_data_2.csv,30,calibrations/WS3.json,video2
10
+ WS3,video3,data/raw/WS3_raw_detection_data_3.csv,30,calibrations/WS3.json,video2
11
+ WS4_5,video1,data/raw/WS4_5_raw_detection_data_1.csv,30,calibrations/WS4_5.json,video1
12
+ WS4_5,video2,data/raw/WS4_5_raw_detection_data_2.csv,30,calibrations/WS4_5.json,video1
13
+ WS4_5,video3,data/raw/WS4_5_raw_detection_data_3.csv,30,calibrations/WS4_5.json,video1
14
+ WS4_5,video4,data/raw/WS4_5_raw_detection_data_4.csv,30,calibrations/WS4_5.json,video1
15
+ WS6_7,video1,data/raw/WS6_7_raw_detection_data_1.csv,30,calibrations/WS6_7.json,video2
16
+ WS6_7,video2,data/raw/WS6_7_raw_detection_data_2.csv,30,calibrations/WS6_7.json,video2
17
+ WS6_7,video3,data/raw/WS6_7_raw_detection_data_3.csv,30,calibrations/WS6_7.json,video2
Processing_Code/coordinate_transform.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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("Use a measured scene calibration with template_only=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("rotation_rad must be 0 for the supplied road-aligned coordinate conversion")
19
+ ratios = []
20
+ self.references = []
21
+ for segment in config["reference_segments"]:
22
+ a = np.asarray(segment["point_a"], dtype=float)
23
+ b = np.asarray(segment["point_b"], dtype=float)
24
+ if a.shape != (2,) or b.shape != (2,) or not np.isfinite([a, b]).all():
25
+ raise ValueError("Reference endpoints must each contain two finite pixel coordinates")
26
+ distance = np.linalg.norm(a - b)
27
+ real = float(segment["real_distance_m"])
28
+ if not np.isfinite([distance, real]).all() or min(distance, real) <= 0:
29
+ raise ValueError("Reference distances must be finite and positive")
30
+ ratios.append(real / distance)
31
+ self.references.append({"name": segment.get("name", ""), "pixel_distance": float(distance),
32
+ "real_distance_m": real, "scale_m_per_px": float(real / distance)})
33
+ if not ratios:
34
+ raise ValueError("At least one measured master-frame reference is required")
35
+ self.scale = float(np.mean(ratios))
36
+ self.source = source
37
+ if config["master_source"] not in config["sources"] or source not in config["sources"]:
38
+ raise ValueError("master_source and --source must identify entries in sources")
39
+ self.master = source == config["master_source"]
40
+ entry = config["sources"][source]
41
+ self.diagnostics = {"source": source, "master_source": config["master_source"],
42
+ "scale_m_per_px": self.scale, "references": self.references,
43
+ "control_points": [], "validation_points": [],
44
+ "review_blocked": bool(entry.get("review_blocked", False))}
45
+ if self.master:
46
+ self.homography = np.eye(3)
47
+ else:
48
+ src = np.asarray(entry["src_points"], dtype=np.float32)
49
+ dst = np.asarray(entry["master_points"], dtype=np.float32)
50
+ if src.shape != dst.shape or src.ndim != 2 or src.shape[1] != 2 or len(src) < 4:
51
+ raise ValueError("At least four corresponding 2D control points are required")
52
+ if not np.isfinite(src).all() or not np.isfinite(dst).all():
53
+ raise ValueError("Non-finite control points")
54
+ if any(np.linalg.matrix_rank(np.column_stack([p, np.ones(len(p))])) < 3 for p in (src, dst)):
55
+ raise ValueError("Control points must not all be collinear")
56
+ cv2.setRNGSeed(0)
57
+ self.homography, mask = cv2.findHomography(src, dst, cv2.RANSAC, 3.0)
58
+ if self.homography is None or mask is None or mask.sum() < 4:
59
+ raise ValueError("Homography estimation failed")
60
+ if not np.isfinite(self.homography).all() or np.linalg.matrix_rank(self.homography) != 3:
61
+ raise ValueError("Non-finite or singular homography")
62
+ predicted = cv2.perspectiveTransform(src.reshape(-1, 1, 2), self.homography).reshape(-1, 2)
63
+ errors = np.linalg.norm(predicted - dst, axis=1)
64
+ self.diagnostics["inlier_ratio"] = float(mask.mean())
65
+ self.diagnostics["control_points"] = [
66
+ {"point": int(i + 1), "source_px": a.tolist(), "master_px": b.tolist(),
67
+ "predicted_master_px": c.tolist(), "error_px": float(e),
68
+ "error_m": float(e * self.scale), "inlier": bool(m)}
69
+ for i, (a, b, c, e, m) in enumerate(zip(src, dst, predicted, errors, mask.ravel()))]
70
+ self.diagnostics["control_rmse_px"] = float(np.sqrt(np.mean(errors ** 2)))
71
+ print(f"Source={source}; master={config['master_source']}; scale={self.scale:.10g} m/px")
72
+ self.diagnostics["homography"] = self.homography.tolist()
73
+ validation_src, validation_master = entry.get("validation_src"), entry.get("validation_master")
74
+ if (validation_src is None) != (validation_master is None):
75
+ raise ValueError("Supply both validation_src and validation_master, or leave both null")
76
+ if validation_src is not None:
77
+ points = np.asarray(validation_src, dtype=float)
78
+ expected_points = np.asarray(validation_master, dtype=float)
79
+ if points.ndim != 2 or points.shape[1:] != (2,) or len(points) == 0 or points.shape != expected_points.shape:
80
+ raise ValueError("Independent validation points must be nonempty matched Nx2 arrays")
81
+ check = self.transform(points)
82
+ expected = (expected_points - self.origin) * [self.scale, -self.scale]
83
+ if check.shape != expected.shape or not np.isfinite(expected).all():
84
+ raise ValueError("Invalid independent validation points")
85
+ error = np.linalg.norm(check - expected, axis=1)
86
+ self.diagnostics["validation_rmse_m"] = float(np.sqrt(np.mean(error ** 2)))
87
+ self.diagnostics["validation_max_m"] = float(error.max())
88
+ self.diagnostics["validation_points"] = [
89
+ {"point": i + 1, "source_px": a.tolist(), "master_px": b.tolist(), "error_m": float(e)}
90
+ for i, (a, b, e) in enumerate(zip(points, expected_points, error))]
91
+ print(f"Independent checkpoints={len(error)}; RMSE={np.sqrt(np.mean(error ** 2)):.6f} m; max={error.max():.6f} m")
92
+ if entry.get("review_blocked", False):
93
+ raise ValueError(f"Selected source calibration is disabled by its configuration: {entry.get('review_note', source)}")
94
+
95
+ def transform(self, points):
96
+ points = np.asarray(points, dtype=float).reshape(-1, 2)
97
+ if not np.isfinite(points).all():
98
+ raise ValueError("Non-finite pixel coordinates")
99
+ if not self.master:
100
+ denominator = points @ self.homography[2, :2] + self.homography[2, 2]
101
+ if np.any(np.abs(denominator) < 1e-10):
102
+ raise ValueError("Points lie on the homography horizon")
103
+ points = cv2.perspectiveTransform(points.astype(np.float32).reshape(-1, 1, 2),
104
+ self.homography).reshape(-1, 2).astype(float)
105
+ result = (points - self.origin) * [self.scale, -self.scale]
106
+ if not np.isfinite(result).all():
107
+ raise ValueError("Non-finite transformed coordinates")
108
+ return result
109
+
110
+
111
+ def load_calibration(path, source):
112
+ with open(path, encoding="utf-8") as handle:
113
+ return Calibration(json.load(handle), source)
114
+
115
+
116
+ def main():
117
+ p = parser(__doc__)
118
+ p.add_argument("--input", required=True, help="Raw pixel trajectory CSV")
119
+ p.add_argument("--calibration", required=True, help="Scene calibration JSON")
120
+ p.add_argument("--source", required=True, help="Source video key in the calibration JSON")
121
+ p.add_argument("--output", required=True, help="New metric trajectory CSV")
122
+ args = p.parse_args()
123
+ df = read_csv(args.input)
124
+ numeric(df, ["Frame", "Vehicle_ID"], integer=True)
125
+ numeric(df, ["x_center_px", "y_center_px"])
126
+ unique(df, ["Frame", "Vehicle_ID"])
127
+ if "Source_ID" in df and not df.Source_ID.eq(args.source).all():
128
+ raise ValueError("Process one source at a time; Source_ID disagrees with --source")
129
+ cal = load_calibration(args.calibration, args.source)
130
+ df[["x_center", "y_center"]] = cal.transform(df[["x_center_px", "y_center_px"]])
131
+ df["Source_ID"] = args.source
132
+ save_csv(df, args.output)
133
+
134
+
135
+ if __name__ == "__main__":
136
+ main()
Processing_Code/data/README.md ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Input file placement
2
+
3
+ For downstream processing, place the existing Basic trajectory CSVs under `basic/`, using the filenames in `../configs/basic_manifest.csv` or pass the actual path explicitly. These files already contain processed vehicle IDs, lanes, directions, positions, velocities and lengths. The README gives the direct risk/pairing/sampling/inference/interaction commands.
4
+
5
+ For source detection processing, place the raw detection CSVs under `raw/` using `../configs/source_manifest.csv`. A raw reconstruction lane input belongs under `lanes/` and has `Frame,Vehicle_ID,Lane number,Direction` keyed by original source records. To transfer lane and direction labels from a Basic file, apply the corresponding source/frame/vehicle mapping to the original detection keys.
6
+
7
+ The processing commands create new files under `runs/` relative to the code directory. Each file's generating command and downstream consumer are listed in the README and `../docs/INPUT_OUTPUT.md`.
8
+
9
+ All commands accept explicit paths. For combining sources or joining processed IDs, use the established source/frame/vehicle correspondence and offsets.
Processing_Code/docs/CALIBRATION.md ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Scene calibration configurations
2
+
3
+ ## Files and source keys
4
+
5
+ | Configuration | Source keys | Master source |
6
+ | --- | --- | --- |
7
+ | `WS1_2.json` | video1-video6 | video4 |
8
+ | `WS3.json` | video1-video3 | video2 |
9
+ | `WS4_5.json` | video1-video4 | video1 |
10
+ | `WS6_7.json` | video1-video3 | video2 |
11
+
12
+ Use the scene JSON and the `--source videoN` value associated with the raw CSV in `configs/source_manifest.csv`. Pixel centers and bounding-box corners must use the same image coordinate view as the control points. Source-image coordinates are mapped into the scene's master-image frame before metric conversion.
13
+
14
+ ## Configuration fields
15
+
16
+ | Field | Meaning and units |
17
+ | --- | --- |
18
+ | `template_only` | `false` for the supplied actual scene configurations |
19
+ | `scene_id` | Observation-group identifier |
20
+ | `master_source` | Source key defining the master-image coordinate frame |
21
+ | `origin_px` | Two-element `[x,y]` origin in master-image pixels |
22
+ | `rotation_rad` | Zero for the supplied road-aligned workflow |
23
+ | `reference_segments` | Measured segments expressed in master-image pixels and meters |
24
+ | `reference_segments[].point_a`, `point_b` | Two-element pixel endpoints in the master image |
25
+ | `reference_segments[].real_distance_m` | Positive measured length in meters |
26
+ | `sources.videoN.src_points` | Nx2 source-image fitting control points, in pixels |
27
+ | `sources.videoN.master_points` | Matched Nx2 master-image fitting control points, in pixels |
28
+
29
+ The master source has an empty source entry because its image frame is already the master frame. Non-master fitting arrays must have equal lengths, at least four point pairs and noncollinear finite coordinates.
30
+
31
+ ## Transformation
32
+
33
+ For each measured reference segment, calculate its real length divided by its pixel length. The metric scale is the arithmetic mean of these ratios, in meters per pixel.
34
+
35
+ For a non-master source, `coordinate_transform.py` estimates the source-to-master homography from the matched fitting points using RANSAC with a 3-pixel threshold and RNG seed 0. For a master source, the source-to-master transform is the identity. After mapping a pixel point to master coordinates `(u,v)`, the output is:
36
+
37
+ ```text
38
+ x = (u - origin_px[0]) * scale
39
+ y = (origin_px[1] - v) * scale
40
+ ```
41
+
42
+ Image coordinates follow the pixel convention, with y increasing downwards. Metric x follows the aligned road axis and metric y increases upwards. Both output coordinates are in meters. Vehicle centers and all four bounding-box corners use this same transformation.
43
+
44
+ ## Usage
45
+
46
+ ```bash
47
+ python coordinate_transform.py --input data/raw/WS3_raw_detection_data_2.csv --calibration calibrations/WS3.json --source video2 --output runs/ws3_video2_metric.csv
48
+ python estimate_vehicle_length.py --input data/raw/WS3_raw_detection_data_2.csv --calibration calibrations/WS3.json --source video2 --output runs/ws3_video2_lengths.csv
49
+ ```
50
+
51
+ Malformed endpoints, nonpositive reference distances, unmatched point arrays, degenerate homographies and points on a homography horizon produce explicit errors. The supplied scene JSONs provide the fitting values used by the processing commands.
Processing_Code/docs/INPUT_OUTPUT.md ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Input and output contracts
2
+
3
+ Paths below describe relative file locations and examples. Use command-line arguments to specify input and output files. Original inputs are read only; existing output files are not overwritten. Keep the image view used for pixel centers and bounding-box corners identical to the view used for their calibration.
4
+
5
+ | Stage | Existing input to supply | Output and next consumer |
6
+ | --- | --- | --- |
7
+ | Coordinate conversion | One named `data/raw/SCENE_raw_detection_data_N.csv`, actual scene JSON and matching `videoN` | Original fields plus `Source_ID,x_center,y_center` in meters. Input remains one observed frame/vehicle per row. |
8
+ | Lane join | Metric output plus a source-frame annotation CSV containing `Frame,Vehicle_ID,Lane number,Direction` | Metric rows with `Lane number,Direction`, joined one-to-one using the original source `Frame,Vehicle_ID` keys. |
9
+ | Reconstruction | Metric centers with lanes/direction, actual FPS and explicit offsets | One row for every reconstructed source frame/vehicle, plus separate rejected rows and per-vehicle screening measurements. |
10
+ | Length estimation | Original six-column source detections and same scene/source calibration | One row per original vehicle: fixed length, bbox lateral diagnostic, frame counts and quality. |
11
+ | Length joining | Reconstructed trajectories with lineage and a length table; otherwise an existing verified ID mapping | Basic trajectories with one fixed `Vehicle_Length_m` per final vehicle. QC fields stay in the separate length table. |
12
+ | Risk | Released Basic with valid lengths, lanes, direction and Time_s or Delta_t_s | Frame-wise TTC/DRAC, event-frame PET, risk target and risk level. Delta_t_s input additionally receives Time_s and Time_Reference_ID. |
13
+ | Pair generation | One released observation-group Basic CSV, or one source-labelled reconstructed Basic CSV, with meter positions and velocities | Frame-sorted **directed** candidate pairs and a JSON runtime summary. |
14
+ | Balanced fitting samples | Full frame-sorted candidate pairs | `Frame,EV_Vehicle_ID,POV_Vehicle_ID,x_local,y_local,v_rel,cangle,round_v,Sample_Group_ID`; the group summary records sample counts and discarded remainders. The fitting subset contains the listed fields. |
15
+ | Parameter inference | Balanced fitting subset; default minimum and maximum used per category/speed key are 50000 | Parameter CSV with one accepted result per category/speed group; a separate JSON records group status and sample counts. The run stops if a requested group fails its acceptance checks. |
16
+ | Interaction annotation | Original Basic, **full** candidate pairs and completed scenario/source-appropriate PR parameter CSV | Basic fields plus pair-relative states, PR, interaction flag and type; a repeated ego/frame can represent several targets. |
17
+
18
+ ## Required fields
19
+
20
+ - Raw detections: `Frame,Vehicle_ID,x_center_px,y_center_px,width_px,height_px`. Integers for Frame and ID; pixel units for centers and box dimensions; unique source-local `(Frame,Vehicle_ID)`. Each manifest row binds this local key to its scene/source.
21
+ - Lane annotation: `Frame,Vehicle_ID,Lane number,Direction`. Keys must refer to the original source frames/IDs before reconstruction; one record per observed key, complete coverage; direction is `Left` or `Right`. Optional Source_ID must agree with the metric source. Apply the corresponding identifier mapping when transferring processed Basic annotations to the original detection keys.
22
+ - Reconstruction output lineage: `Source_ID,Original_Vehicle_ID,Original_Frame,Frame,Ego_Vehicle_ID`. `Time_s` is seconds from the input recording origin plus explicit time offset; `Delta_t_s` is blank at each track start and 1/FPS thereafter. The example commands use zero offsets and therefore retain a source-local reference.
23
+ - Kinematics: `x_center,y_center` m; `v_x,v_y` m/s; `a_x,a_y` m/s². The reconstruction outputs smoothed positions under x_center/y_center. Positions use road-aligned local metric coordinates obtained by master-image registration and measured scale conversion.
24
+ - Length output: `Source_ID,Vehicle_ID,Vehicle_Length_m,BBox_Lateral_Extent_Q25_m,Input_Frames,Valid_Before_IQR,Retained_Frames,Removed_By_IQR,Quality`. Vehicle_Length_m is missing if fewer than five frames survive. Quality is good at >=20 retained frames, limited at 5–19, insufficient otherwise.
25
+ - Optional processed-ID mapping: `Ego_Vehicle_ID,Source_ID,Original_Vehicle_ID`; both final ID and source/original identity map one-to-one. Compress frame-wise mapping rows only after verifying consistency.
26
+ - Required pair fields: `Frame,EV_Vehicle_ID,POV_Vehicle_ID,x_local,y_local,v_rel,cangle`. x_local/y_local are local X/Y components in meters, v_rel is a positive scalar in m/s, and cangle is **binary**, not degrees. The generator also writes signed `cangle_deg`, `Distance_m`, and `Angle_Defined` fields.
27
+ - PR parameters: `cangle,round_v,rx_plus,rx_minus,ry_plus,ry_minus,bx_plus,bx_minus,by_plus,by_minus`. Category/speed key unique; all eight parameters positive. Additional fit-status fields are allowed.
28
+
29
+ ## Calibration fields and source matching
30
+
31
+ Each measured JSON includes `master_source`, the two-coordinate `origin_px`, `rotation_rad=0`, two measured `reference_segments`, and `sources`. Each non-master source contains matched Nx2 fitting arrays `src_points` and `master_points`. The master source defines the reference view and uses the identity source-to-master mapping. Use the measured files in `calibrations/` for the supplied recordings. Field meanings and units are detailed in `CALIBRATION.md`.
32
+
33
+ The sixteen filename/source mappings and frame rates are listed in `configs/source_manifest.csv`. Process one source per run. For combined sources, provide established offsets with `--id-offset`, `--frame-offset`, and `--time-offset`. Use source-frame annotation keys for the lane join; apply any final-ID mapping only at the appropriate later stage. Measured `--merge-x-m` and `--diverge-x-m` values must use the same metric frame as the trajectories.
34
+
35
+ ## Error behavior and outputs
36
+
37
+ Invalid numeric values, duplicate identity keys, source disagreements and missing required fields fail explicitly. Invalid frame-level bounding boxes are excluded and counted by the length estimator. A length table can contain a vehicle with a missing estimate, but a missing vehicle mapping fails. The main risk example uses the existing per-vehicle lengths. Fitting samples use relative speeds up to 30 m/s and complete sparse blocks; runtime summaries record excluded observations and block remainders.
38
+
39
+ All supplied candidate pairs remain eligible for final annotation, including those excluded from **fitting** by the speed cutoff. Parameter lookup selects the nearest fitted relative-speed bin within each angle category, with no default maximum speed difference, including at the fitted-range boundaries. Set `--speed-tolerance` to require a bin within a specified speed difference; an unmatched lookup raises an error.
40
+
41
+ ## Released Basic input and time references
42
+
43
+ The primary downstream input is the released observation-group Basic CSV, with `Ego_Vehicle_ID,Frame,Delta_t_s,x_center,y_center,v_x,v_y,a_x,a_y,Direction,Lane number,Dist_to_Merge_m,Dist_to_Diverge_m,Vehicle_Length_m`. This entry point uses the lane and direction fields already present in the Basic file. The pair generator uses metric centers and velocities directly; annotation uses the existing processed IDs, lane and direction fields.
44
+
45
+ For risk input without `Time_s`, positive `Delta_t_s` values define the elapsed time into the corresponding processed frame. Values for the same frame must agree. Each vehicle must have consecutive frames and a positive interval after its first record. The time builder accumulates these intervals across connected frames. A missing incoming interval or a gap in observed frames starts a new time reference at zero. `Time_Reference_ID` identifies that reference, and each vehicle must belong to one reference. This represents local sequence time without assigning an unobserved interval between recordings. Existing `Time_s` input retains its supplied reference; explicit `--fps` retains the constant-rate option.
46
+
47
+ The Basic files use processed `Ego_Vehicle_ID,Frame`; raw detections use source-local `Vehicle_ID,Frame`. A source-frame annotation CSV for reconstruction is keyed by the original detection records. Transferring Basic labels uses the corresponding source/frame/vehicle mapping.
Processing_Code/docs/METHOD_NOTES.md ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Processing methods and numerical settings
2
+
3
+ ## Coordinates and vehicle length
4
+
5
+ Source-image points are mapped to the master image by RANSAC homography with a 3-pixel threshold. Metric conversion subtracts the master-image origin, applies the mean measured distance/pixel scale, and reverses image y. The supplied configurations use no additional rotation. See `CALIBRATION.md`.
6
+
7
+ Vehicle-length estimation constructs the four corners of each pixel bounding box, transforms them with the same calibration, and takes the longitudinal maximum-minus-minimum as a frame-level length candidate. Invalid and nonpositive candidates are removed. A 1.5-IQR filter is applied when at least four candidates exist. The 25th percentile is assigned as the fixed vehicle length when at least five candidates remain. The separate length table records retained counts and the quality category: good for at least 20 frames, limited for 5-19, and insufficient below five.
8
+
9
+ ## Trajectory screening and reconstruction
10
+
11
+ Tracks are sorted chronologically. Screening uses the observed record count divided by FPS, with a minimum duration of 0.5 s and at least 15 observations. A track with duration at least 2 s, extent diagonal below 1 m and mean path speed below 0.5 m/s is rejected by the low-motion rule. Mean path speed is accumulated path distance divided by the observed-count duration. Rejected records and screening measurements are written separately.
12
+
13
+ Coordinate interpolation uses a linear method for two observations and PCHIP for three or more; screening is performed before interpolation. Lane values are filled forwards and then backwards. Symmetric exponential moving averaging uses a 0.6 s window; the supplied reconstruction calculates velocities and accelerations from the smoothed positions. `Frame`, `Time_s` and source lineage are retained with the offsets passed to the command.
14
+
15
+ ## Vehicle pairing and local coordinates
16
+
17
+ Use one released observation-group Basic CSV per run, or one source recording for source-labelled inputs. Within each frame and travel direction, candidate vehicle pairs satisfy `0.5 m <= center distance < 50 m`. The pair list is directed, so both orientations of an eligible pair are represented. Position difference is POV minus EV; velocity difference is EV minus POV. The relative-velocity direction defines local +Y and its right perpendicular defines local +X. Pairs with exactly zero relative speed are excluded.
18
+
19
+ The signed heading angle is `-atan2(cross(vEV,vPOV),dot(vEV,vPOV))` in degrees. The binary class is `cangle=1` for `5 <= abs(angle) <= 175` degrees and 0 otherwise. When either individual velocity is zero, `Angle_Defined=false`; the implemented atan2(0,0)=0 convention is retained. Distances are meters and relative speeds are m/s.
20
+
21
+ ## Balanced fitting samples
22
+
23
+ Fitting first excludes relative speeds above 30 m/s, separates the angle categories and rounds relative speed to one decimal. Dense speed bins are sampled uniformly without replacement to 50000 pair-frame observations with seed 42 by default. Sparse bins within each category are pooled, sorted by actual speed and divided into complete 50000-row blocks. Each complete block receives its mean speed rounded to one decimal; the final incomplete block is discarded. Runtime group summaries record counts and representative-speed labels.
24
+
25
+ Inference groups by `cangle,round_v`. Coincident representative labels are combined, with a seeded downsample to 50000 observations when necessary. `Sample_Group_ID` retains the sampling-block label. The complete candidate list is used for final annotation, while the balanced subset is used for fitting.
26
+
27
+ ## Driver-space parameter estimation
28
+
29
+ The inference procedure follows Jiao et al. (2023a), *Inferring vehicle spacing in urban traffic from trajectory data*, Section 2.3, equation (8) and Algorithm 1: [doi:10.1016/j.trc.2023.104289](https://doi.org/10.1016/j.trc.2023.104289).
30
+
31
+ The adopted adjusted log-likelihood objective is:
32
+
33
+ ```text
34
+ J = sum(log(1 + epsilon - PR_i)), epsilon = 1e-4
35
+ ```
36
+
37
+ At each iteration, the four directional scale parameters are selected by grid search minimizing their individual second finite differences of J. The grid step is 0.1 m and the second-difference step is 0.5 m. Conditional on the updated scales, the four shape parameters are estimated by constrained maximum likelihood estimation within the adopted likelihood formulation: L-BFGS-B minimizes -J subject to beta >= 2. The scale update uses the curvature criterion; MLE refers to the conditional shape update.
38
+
39
+ The supplied fitting entrypoint uses width=2.0 m, length=5.0 m and the 0.5th percentile for initialization. These are model initialization settings. Beta starts at 2, search bounds are determined from conditional spacing subsets, and parameter values are rounded to one decimal. The initial percentile setting is passed to `np.percentile`. The default `max_iter` value is 50, and the iteration-limit check uses `iteration > max_iter`.
40
+
41
+ The iteration stops when rounded parameter vectors converge. For recurring vectors, the implemented cycle-resolution rule chooses the smallest summed approximate shape-parameter p-values. The runtime summary records each group's optimization status and sample counts. Bounds, parameter finiteness, sample size and optimizer status are checked before the complete parameter table is written.
42
+
43
+ Jiao et al. (2023b), *Identifying Vehicle Interaction at Urban Intersections: A Comparison of Proximity Resistance, Time-to-Collision, and Post-Encroachment-Time*, Section II-A, describes PR-based interaction identification and refers to the same parameter-inference framework: [doi:10.1109/ITSC57777.2023.10422682](https://doi.org/10.1109/ITSC57777.2023.10422682).
44
+
45
+ ## Risk and interaction annotation
46
+
47
+ Risk annotation uses per-vehicle length estimates and the trajectory lane, direction and time fields. TTC and DRAC use the selected same-lane leader; DRAC is capped at 15 m/s². Cut-in PET is evaluated from future crossing times at the detected event frame, with negative values clipped to zero and the existing per-vehicle/frame event selection retained. Command options specify any explicit missing-length fallback.
48
+
49
+ Interaction annotation uses all eligible candidate pairs, the appropriate fitted parameter table and the full Basic trajectories. It writes PR and interaction type for all candidates. `PR > exp(-1)` controls the effective-interaction flag. The nearest-speed parameter lookup follows the supplied rule; `--speed-tolerance` can impose an explicit matching tolerance. A repeated ego/frame may have several target vehicles. Records without an eligible candidate use the existing `Safe` type label.
50
+
51
+ ## Reading the released Basic timing format
52
+
53
+ The Basic files carry `Delta_t_s` in seconds and may combine 30 fps and 60 fps sequences. Risk annotation can derive the time coordinate directly from those frame intervals. Nonmissing intervals must be positive, finite and consistent among all vehicles at the same frame. Per-vehicle frames must be consecutive, with an interval on each record after its first. The time coordinate accumulates the common frame intervals within each connected sequence; disconnected sequences get separate Time_Reference_ID values and zero-based local Time_s. Every vehicle must stay in one time reference. PET compares vehicle times that share the same event frame and time reference. The TTC, DRAC and PET formulas are unchanged.
Processing_Code/driver_space_model.py ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Driver-space inference adapted from Yiru-Jiao/DriverSpaceInference.
2
+ See THIRD_PARTY_NOTICES.md and docs/METHOD_NOTES.md for attribution and settings.
3
+ """
4
+ import numpy as np
5
+ import pandas as pd
6
+ from scipy import optimize
7
+ from scipy.stats import t
8
+ import warnings
9
+
10
+ class drspace:
11
+ """The class is used to estimate parameters of driver space from vehicle pair samples."""
12
+
13
+ def __init__(self, samples, eps=1e-4, width=2, length=4, percentile=0.5):
14
+
15
+ # //Extract input variables
16
+ self.width = width
17
+ self.length = length
18
+ self.samples = samples
19
+ self.corrcoef_xy = np.corrcoef(self.samples.x, self.samples.y)[1, 0]
20
+ self.percentile = percentile
21
+
22
+ # //Initialize parameters
23
+ self.epsilon = eps
24
+ self.bx_plus = 2
25
+ self.bx_minus = 2
26
+ self.by_plus = 2
27
+ self.by_minus = 2
28
+
29
+ try:
30
+ self.ry_plus = max(self.length / 2, np.percentile(
31
+ self.samples.y[(self.samples.y >= 0) & (abs(self.samples.x) < self.width / 2)], self.percentile))
32
+ except:
33
+ self.ry_plus = self.length / 2
34
+ try:
35
+ self.ry_minus = max(self.length / 2, np.percentile(
36
+ -self.samples.y[(self.samples.y < 0) & (abs(self.samples.x) < self.width / 2)], self.percentile))
37
+ except:
38
+ self.ry_minus = self.length / 2
39
+ try:
40
+ self.rx_plus = max(self.width / 2, np.percentile(self.samples.x[(self.samples.x > 0) & (
41
+ self.samples.y <= max(self.length / 2, self.ry_plus / 2)) & (self.samples.y >= -max(
42
+ self.length / 2, self.ry_minus / 2))], self.percentile))
43
+ except:
44
+ self.rx_plus = self.width / 2
45
+ try:
46
+ self.rx_minus = max(self.width / 2, np.percentile(-self.samples.x[
47
+ (self.samples.x < 0) & (self.samples.y <= max(self.length / 2, self.ry_plus / 2)) & (
48
+ self.samples.y >= -max(self.length / 2, self.ry_minus / 2))], self.percentile))
49
+ except:
50
+ self.rx_minus = self.width / 2
51
+
52
+ # Log likelihood
53
+
54
+ ## Log likelihood to all parameters
55
+ def LogL(self, para):
56
+ rx_plus, rx_minus, ry_plus, ry_minus, bx_plus, bx_minus, by_plus, by_minus = para
57
+
58
+ rx = (1 + np.sign(self.x)) / 2 * rx_plus + (1 - np.sign(self.x)) / 2 * rx_minus
59
+ bx = (1 + np.sign(self.x)) / 2 * bx_plus + (1 - np.sign(self.x)) / 2 * bx_minus
60
+ ry = (1 + np.sign(self.y)) / 2 * ry_plus + (1 - np.sign(self.y)) / 2 * ry_minus
61
+ by = (1 + np.sign(self.y)) / 2 * by_plus + (1 - np.sign(self.y)) / 2 * by_minus
62
+
63
+ elements = np.log(
64
+ 1 + self.epsilon - np.exp(-np.power(np.absolute(self.x / rx), bx) - np.power(np.absolute(self.y / ry), by)))
65
+
66
+ return sum(elements)
67
+
68
+ ## Log likelihood to rx_plus
69
+ def LogL_rx_plus(self, rx_plus):
70
+ rx = (1 + np.sign(self.x)) / 2 * rx_plus + (1 - np.sign(self.x)) / 2 * self.rx_minus
71
+ bx = (1 + np.sign(self.x)) / 2 * self.bx_plus + (1 - np.sign(self.x)) / 2 * self.bx_minus
72
+ ry = (1 + np.sign(self.y)) / 2 * self.ry_plus + (1 - np.sign(self.y)) / 2 * self.ry_minus
73
+ by = (1 + np.sign(self.y)) / 2 * self.by_plus + (1 - np.sign(self.y)) / 2 * self.by_minus
74
+
75
+ elements = np.log(
76
+ 1 + self.epsilon - np.exp(-np.power(np.absolute(self.x / rx), bx) - np.power(np.absolute(self.y / ry), by)))
77
+
78
+ return sum(elements)
79
+
80
+ ## Second-order derivative of the Log likelihood to rx_plus
81
+ def LogL_rx_plus_prime2(self, rx_plus):
82
+ dx = 0.5
83
+ return (self.LogL_rx_plus(rx_plus + dx) - 2 * self.LogL_rx_plus(rx_plus) + self.LogL_rx_plus(rx_plus - dx)) / (
84
+ dx ** 2)
85
+
86
+ ## Log likelihood to rx_minus
87
+ def LogL_rx_minus(self, rx_minus):
88
+ rx = (1 + np.sign(self.x)) / 2 * self.rx_plus + (1 - np.sign(self.x)) / 2 * rx_minus
89
+ bx = (1 + np.sign(self.x)) / 2 * self.bx_plus + (1 - np.sign(self.x)) / 2 * self.bx_minus
90
+ ry = (1 + np.sign(self.y)) / 2 * self.ry_plus + (1 - np.sign(self.y)) / 2 * self.ry_minus
91
+ by = (1 + np.sign(self.y)) / 2 * self.by_plus + (1 - np.sign(self.y)) / 2 * self.by_minus
92
+
93
+ elements = np.log(
94
+ 1 + self.epsilon - np.exp(-np.power(np.absolute(self.x / rx), bx) - np.power(np.absolute(self.y / ry), by)))
95
+
96
+ return sum(elements)
97
+
98
+ ## Second-order derivative of the Log likelihood to rx_minus
99
+ def LogL_rx_minus_prime2(self, rx_minus):
100
+ dx = 0.5
101
+ return (self.LogL_rx_minus(rx_minus + dx) - 2 * self.LogL_rx_minus(rx_minus) + self.LogL_rx_minus(
102
+ rx_minus - dx)) / (dx ** 2)
103
+
104
+ ## Log likelihood to ry_plus
105
+ def LogL_ry_plus(self, ry_plus):
106
+ rx = (1 + np.sign(self.x)) / 2 * self.rx_plus + (1 - np.sign(self.x)) / 2 * self.rx_minus
107
+ bx = (1 + np.sign(self.x)) / 2 * self.bx_plus + (1 - np.sign(self.x)) / 2 * self.bx_minus
108
+ ry = (1 + np.sign(self.y)) / 2 * ry_plus + (1 - np.sign(self.y)) / 2 * self.ry_minus
109
+ by = (1 + np.sign(self.y)) / 2 * self.by_plus + (1 - np.sign(self.y)) / 2 * self.by_minus
110
+
111
+ elements = np.log(
112
+ 1 + self.epsilon - np.exp(-np.power(np.absolute(self.x / rx), bx) - np.power(np.absolute(self.y / ry), by)))
113
+
114
+ return sum(elements)
115
+
116
+ ## Second-order derivative of the Log likelihood to ry_plus
117
+ def LogL_ry_plus_prime2(self, ry_plus):
118
+ dx = 0.5
119
+ return (self.LogL_ry_plus(ry_plus + dx) - 2 * self.LogL_ry_plus(ry_plus) + self.LogL_ry_plus(ry_plus - dx)) / (
120
+ dx ** 2)
121
+
122
+ ## Log likelihood to ry_minus
123
+ def LogL_ry_minus(self, ry_minus):
124
+ rx = (1 + np.sign(self.x)) / 2 * self.rx_plus + (1 - np.sign(self.x)) / 2 * self.rx_minus
125
+ bx = (1 + np.sign(self.x)) / 2 * self.bx_plus + (1 - np.sign(self.x)) / 2 * self.bx_minus
126
+ ry = (1 + np.sign(self.y)) / 2 * self.ry_plus + (1 - np.sign(self.y)) / 2 * ry_minus
127
+ by = (1 + np.sign(self.y)) / 2 * self.by_plus + (1 - np.sign(self.y)) / 2 * self.by_minus
128
+
129
+ elements = np.log(
130
+ 1 + self.epsilon - np.exp(-np.power(np.absolute(self.x / rx), bx) - np.power(np.absolute(self.y / ry), by)))
131
+
132
+ return sum(elements)
133
+
134
+ ## Second-order derivative of the Log likelihood to ry_minus
135
+ def LogL_ry_minus_prime2(self, ry_minus):
136
+ dx = 0.5
137
+ return (self.LogL_ry_minus(ry_minus + dx) - 2 * self.LogL_ry_minus(ry_minus) + self.LogL_ry_minus(
138
+ ry_minus - dx)) / (dx ** 2)
139
+
140
+ ## Negative Log likelihood to betas
141
+ def NLogL_betas(self, para):
142
+ bx_plus, bx_minus, by_plus, by_minus = para
143
+
144
+ rx = (1 + np.sign(self.x)) / 2 * self.rx_plus + (1 - np.sign(self.x)) / 2 * self.rx_minus
145
+ bx = (1 + np.sign(self.x)) / 2 * bx_plus + (1 - np.sign(self.x)) / 2 * bx_minus
146
+ ry = (1 + np.sign(self.y)) / 2 * self.ry_plus + (1 - np.sign(self.y)) / 2 * self.ry_minus
147
+ by = (1 + np.sign(self.y)) / 2 * by_plus + (1 - np.sign(self.y)) / 2 * by_minus
148
+
149
+ elements = np.log(
150
+ 1 + self.epsilon - np.exp(-np.power(np.absolute(self.x / rx), bx) - np.power(np.absolute(self.y / ry), by)))
151
+
152
+ return -sum(elements)
153
+
154
+ # Optimize betas
155
+ def optimize_betas(self, initial_guess):
156
+ betas = optimize.minimize(self.NLogL_betas,
157
+ x0=initial_guess,
158
+ method='L-BFGS-B',
159
+ bounds=((2, np.inf), (2, np.inf), (2, np.inf), (2, np.inf)),
160
+ jac=None,
161
+ tol=None,
162
+ options={'disp': None,
163
+ 'maxcor': 10,
164
+ 'ftol': 2.220446049250313e-09,
165
+ 'gtol': 1e-05,
166
+ 'eps': 1e-08,
167
+ 'maxfun': 15000,
168
+ 'maxiter': 15000,
169
+ 'iprint': - 1,
170
+ 'maxls': 25,
171
+ 'finite_diff_rel_step': None})
172
+ return betas
173
+
174
+ # Inference
175
+ def Inference(self, max_iter=50, workers=1):
176
+
177
+ self.inference_status = "running"
178
+ self.inference_error = None
179
+ self.optimizer_failures = []
180
+ self.completed_iterations = 0
181
+
182
+ parameters = np.zeros((2, 8))
183
+ stderr_betas = np.zeros((0, 4))
184
+ pvalue_betas = np.zeros((0, 4))
185
+ parameters[1, :] = [self.rx_plus, self.rx_minus, self.ry_plus, self.ry_minus, self.bx_plus, self.bx_minus,
186
+ self.by_plus, self.by_minus]
187
+
188
+ self.x = self.samples.x.values
189
+ self.y = self.samples.y.values
190
+ self.v = self.samples.v.values
191
+
192
+ try:
193
+ # Lower seraching bounds
194
+ percentage = 0.0005 + (0.002 * self.v.mean()) ** 2
195
+ candidates = self.samples.y[(self.samples.y >= 0) & (abs(self.samples.x) < self.width / 2)]
196
+ y_plus_llimit = max(self.length / 2,
197
+ candidates.nsmallest(max(10, int(len(candidates) * percentage))).nlargest(
198
+ 10).mean() * 0.7) - 0.5
199
+ candidates = (-self.samples.y[(self.samples.y < 0) & (abs(self.samples.x) < self.width / 2)])
200
+ y_minus_llimit = max(self.length / 2,
201
+ candidates.nsmallest(max(10, int(len(candidates) * percentage))).nlargest(
202
+ 10).mean() * 0.7) - 0.5
203
+ x_plus_llimit = 1.2
204
+ x_minus_llimit = 1.2
205
+
206
+ # Upper seraching bounds
207
+ conditionx = (self.samples.x < x_plus_llimit) & (self.samples.x > -x_minus_llimit)
208
+ percentage = 0.2 + 0.001 * self.v.mean() ** 2.8
209
+ candidates = self.samples.y[conditionx & (self.samples.y > 0)]
210
+ y_plus_ulimit = candidates.nsmallest(int(len(candidates) * percentage)).nlargest(10).mean()
211
+ candidates = -self.samples.y[conditionx & (self.samples.y < 0)]
212
+ y_minus_ulimit = candidates.nsmallest(int(len(candidates) * percentage)).nlargest(10).mean()
213
+ x_plus_ulimit = 7.
214
+ x_minus_ulimit = 7.
215
+
216
+ x_plus_llimit, x_minus_llimit, y_plus_llimit, y_minus_llimit = np.floor(
217
+ np.array([x_plus_llimit, x_minus_llimit, y_plus_llimit, y_minus_llimit]) * 10) / 10
218
+ x_plus_ulimit, x_minus_ulimit, y_plus_ulimit, y_minus_ulimit = np.ceil(
219
+ np.array([x_plus_ulimit, x_minus_ulimit, y_plus_ulimit, y_minus_ulimit]) * 10) / 10
220
+ limits = np.array(
221
+ [x_plus_llimit, x_plus_ulimit, x_minus_llimit, x_minus_ulimit, y_plus_llimit, y_plus_ulimit,
222
+ y_minus_llimit, y_minus_ulimit])
223
+ if not np.isfinite(limits).all() or np.any(limits[::2] > limits[1::2]):
224
+ raise ValueError("Invalid data-derived search bounds; inspect conditional spacing samples")
225
+
226
+ iteration = 0
227
+ while np.any(parameters[-1] != parameters[-2]):
228
+
229
+ # ====== 进度显示 ======
230
+ print(
231
+ f"\r[正在推演] 收敛计算中... 当前轮次: {iteration + 1} / 最大限制 {max_iter} (优化器正在寻找最优解)",
232
+ end="", flush=True)
233
+
234
+ # //Stop when reaching the maximum number of iterations
235
+ if iteration > max_iter:
236
+ self.inference_status = "iteration_limit"
237
+ parameters = np.vstack((parameters, np.ones((1, 8)) * np.nan))
238
+ stderr_betas = np.vstack((stderr_betas, np.ones((1, 4)) * np.nan))
239
+ pvalue_betas = np.vstack((pvalue_betas, np.ones((1, 4)) * np.nan))
240
+ print("\n[警告] 达到最大迭代次数,推演提前结束。")
241
+ warnings.warn('Max. iterations reached', RuntimeWarning)
242
+ break
243
+
244
+ # //Stop when several sets of values repeat and select the set of values with the smallest sum of p-values
245
+ array2check = np.all(np.equal(np.array([parameters[-1], ] * len(parameters[:-1])), parameters[:-1]),
246
+ axis=1)
247
+ if np.any(array2check):
248
+ self.inference_status = "cycle_resolved_by_legacy_p_values"
249
+ repeated_parameters = parameters[np.where(array2check)[0][0]:-1]
250
+ repeated_stderrs = stderr_betas[-len(repeated_parameters) - 1:-1]
251
+ repeated_pvals = pvalue_betas[-len(repeated_parameters) - 1:-1]
252
+ idx_chosen = np.argmin(repeated_pvals.sum(axis=1))
253
+ parameters = np.vstack((parameters, repeated_parameters[idx_chosen]))
254
+ stderr_betas = np.vstack((stderr_betas, repeated_stderrs[idx_chosen]))
255
+ pvalue_betas = np.vstack((pvalue_betas, repeated_pvals[idx_chosen]))
256
+ break
257
+
258
+ self.rx_plus, self.rx_minus, self.ry_plus, self.ry_minus = np.round(
259
+ [self.rx_plus, self.rx_minus, self.ry_plus, self.ry_minus], 1)
260
+ rx_plus = optimize.brute(self.LogL_rx_plus_prime2, (slice(x_plus_llimit, x_plus_ulimit + 0.1, 0.1),),
261
+ finish=None, workers=workers)
262
+ rx_minus = optimize.brute(self.LogL_rx_minus_prime2,
263
+ (slice(x_minus_llimit, x_minus_ulimit + 0.1, 0.1),), finish=None,
264
+ workers=workers)
265
+ ry_plus = optimize.brute(self.LogL_ry_plus_prime2, (slice(y_plus_llimit, y_plus_ulimit + 0.1, 0.1),),
266
+ finish=None, workers=workers)
267
+ ry_minus = optimize.brute(self.LogL_ry_minus_prime2,
268
+ (slice(y_minus_llimit, y_minus_ulimit + 0.1, 0.1),), finish=None,
269
+ workers=workers)
270
+ self.rx_plus, self.rx_minus, self.ry_plus, self.ry_minus = [rx_plus, rx_minus, ry_plus, ry_minus]
271
+
272
+ betas = self.optimize_betas([self.bx_plus, self.bx_minus, self.by_plus, self.by_minus])
273
+ if not betas.success:
274
+ self.optimizer_failures.append(str(betas.message))
275
+ self.bx_plus, self.bx_minus, self.by_plus, self.by_minus = np.round(betas.x, 1)
276
+
277
+ stderr = np.sqrt(np.diag(betas.hess_inv.todense()))
278
+ tstat = betas.x / stderr
279
+ pval = (1 - t.cdf(np.absolute(tstat), len(self.x) - 1)) * 2
280
+
281
+ parameters = np.vstack((parameters,
282
+ [self.rx_plus, self.rx_minus, self.ry_plus, self.ry_minus, self.bx_plus,
283
+ self.bx_minus, self.by_plus, self.by_minus]))
284
+ stderr_betas = np.vstack((stderr_betas, stderr))
285
+ pvalue_betas = np.vstack((pvalue_betas, pval))
286
+
287
+ iteration += 1
288
+ self.completed_iterations = iteration
289
+
290
+ # 循环结束后清空进度条提示
291
+ if self.inference_status == "running":
292
+ self.inference_status = "converged_rounded_parameters"
293
+ print(f"\nInference status={self.inference_status}; iterations={iteration}")
294
+
295
+ except Exception as e:
296
+ self.inference_status = "failed"
297
+ self.inference_error = str(e)
298
+ print(f"\n[错误] 推演过程中断: {e}")
299
+ limits = np.ones(8) * np.nan
300
+ parameters = np.vstack((parameters, np.ones((1, 8)) * np.nan))
301
+ stderr_betas = np.vstack((stderr_betas, np.ones((1, 4)) * np.nan))
302
+ pvalue_betas = np.vstack((pvalue_betas, np.ones((1, 4)) * np.nan))
303
+
304
+ return (limits, parameters[-1].copy(), stderr_betas[-1].copy(), pvalue_betas[-1].copy())
Processing_Code/estimate_vehicle_length.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()
Processing_Code/filter_trajectory_outliers.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Screen complete metric trajectories by duration, observation count and motion thresholds."""
2
+ import numpy as np
3
+ import pandas as pd
4
+ from _common import numeric, parser, read_csv, save_csv, unique, preflight_outputs
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
+ preflight_outputs(a.output, a.rejected, a.audit)
59
+ kept, rejected, audit = split_tracks(read_csv(a.input), a.fps)
60
+ save_csv(audit, a.audit)
61
+ save_csv(rejected, a.rejected)
62
+ save_csv(kept, a.output)
63
+ print("Review low-motion rejections: genuine stopped vehicles may satisfy this heuristic.")
64
+
65
+
66
+ if __name__ == "__main__":
67
+ main()
Processing_Code/fit_pr_parameters.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fit driver-space parameters by group and record per-group runtime summaries."""
2
+ import json
3
+ from pathlib import Path
4
+ import numpy as np
5
+ import pandas as pd
6
+ from _common import numeric, output_path, parser, read_csv, require, save_csv, preflight_outputs
7
+ from driver_space_model import drspace
8
+ from annotate_interactions import validate_parameters
9
+
10
+
11
+ def fit_groups(df, output, audit_path, width=2., length=5., percentile=0.5, minimum_samples=50000,
12
+ maximum_samples=50000, max_iter=50, workers=1, seed=42):
13
+ preflight_outputs(output, audit_path)
14
+ df = df.copy()
15
+ require(df, ["cangle", "round_v", "x_local", "y_local", "v_rel"])
16
+ numeric(df, ["cangle"], integer=True)
17
+ numeric(df, ["round_v", "x_local", "y_local", "v_rel"])
18
+ if not df.cangle.isin([0, 1]).all() or df.v_rel.le(0).any():
19
+ raise ValueError("Require binary cangle and positive relative speed")
20
+ if (not np.isfinite([width, length, percentile]).all() or min(width, length) <= 0 or not 0 <= percentile <= 100
21
+ or minimum_samples < 1 or maximum_samples < minimum_samples or workers < 1 or max_iter < 0):
22
+ raise ValueError("Invalid inference settings")
23
+ if Path(output).resolve() == Path(audit_path).resolve() or Path(audit_path).exists():
24
+ raise FileExistsError("Choose distinct new parameter and audit files")
25
+ if Path(output).exists():
26
+ raise FileExistsError(output)
27
+ records, results = [], []
28
+ for (category, speed), group in df.groupby(["cangle", "round_v"], sort=True):
29
+ record = {"cangle": int(category), "round_v": float(speed), "available_samples": len(group),
30
+ "sample_group_ids": sorted(group.Sample_Group_ID.astype(str).unique().tolist()) if "Sample_Group_ID" in group else None}
31
+ if len(group) < minimum_samples:
32
+ record.update(status="insufficient_samples", used_samples=0)
33
+ records.append(record)
34
+ continue
35
+ samples = group[["x_local", "y_local", "v_rel"]].rename(columns={"x_local": "x", "y_local": "y", "v_rel": "v"})
36
+ if len(samples) > maximum_samples:
37
+ samples = samples.sample(n=maximum_samples, random_state=seed)
38
+ model = drspace(samples, width=width, length=length, percentile=percentile)
39
+ limits, parameters, standard_errors, p_values = model.Inference(max_iter=max_iter, workers=workers)
40
+ status = getattr(model, "inference_status", "unknown")
41
+ optimizer_failures = getattr(model, "optimizer_failures", [])
42
+ accepted = (status in ["converged_rounded_parameters", "cycle_resolved_by_legacy_p_values"]
43
+ and not optimizer_failures and np.isfinite(parameters).all() and np.all(parameters > 0))
44
+ record.update(status=status, accepted=bool(accepted), used_samples=len(samples),
45
+ iterations=int(getattr(model, "completed_iterations", 0)),
46
+ error=getattr(model, "inference_error", None), optimizer_failures=optimizer_failures,
47
+ bounds=np.asarray(limits).tolist(), parameters=np.asarray(parameters).tolist())
48
+ # The parameter CSV contains fitted values, sample sizes and fit status.
49
+ if accepted:
50
+ results.append({"cangle": int(category), "round_v": float(speed)})
51
+ results[-1].update(dict(zip(["rx_plus", "rx_minus", "ry_plus", "ry_minus", "bx_plus", "bx_minus", "by_plus", "by_minus"], parameters)))
52
+ results[-1].update(sample_size=len(samples), Fit_Status=status, Fit_Method="author_legacy_hybrid")
53
+ records.append(record)
54
+ complete = bool(records) and len(results) == len(records)
55
+ audit = {"complete": complete, "method": "Alternating curvature-grid scale updates and constrained conditional maximum-likelihood shape updates",
56
+ "width_m": width, "length_m": length, "initial_percentile": percentile,
57
+ "minimum_samples": minimum_samples, "maximum_samples": maximum_samples, "max_iter": max_iter, "workers": workers,
58
+ "downsample_seed": seed, "groups": records,
59
+ "uncertainty_note": "Approximate inverse-Hessian p-values are used to select among recurring parameter vectors; the parameter CSV reports fitted values, sample size and fit status."}
60
+ # Serialize nonfinite runtime-summary values as JSON null.
61
+ def clean(value):
62
+ if isinstance(value, dict): return {k: clean(v) for k, v in value.items()}
63
+ if isinstance(value, list): return [clean(v) for v in value]
64
+ return None if isinstance(value, float) and not np.isfinite(value) else value
65
+ with output_path(audit_path) as temporary:
66
+ Path(temporary).write_text(json.dumps(clean(audit), indent=2, allow_nan=False), encoding="utf-8")
67
+ if not complete:
68
+ raise ValueError("One or more inference groups failed or were undersized; audit saved; no parameter CSV published")
69
+ result = pd.DataFrame(results)
70
+ validate_parameters(result)
71
+ save_csv(result, output)
72
+ return result
73
+
74
+
75
+ def main():
76
+ p = parser(__doc__)
77
+ p.add_argument("--input", required=True, help="Balanced fitting CSV generated by balance_pair_samples.py")
78
+ p.add_argument("--output", required=True, help="New complete parameter CSV, compatible with annotate_interactions.py")
79
+ p.add_argument("--audit", required=True, help="New JSON with per-group status and sample counts")
80
+ p.add_argument("--width-m", type=float, default=2., help="Driver-space model width setting in meters")
81
+ p.add_argument("--length-m", type=float, default=5., help="Driver-space model length setting in meters")
82
+ p.add_argument("--initial-percentile", type=float, default=0.5, help="Initial np.percentile value: 0.5 selects the 0.5th percentile")
83
+ p.add_argument("--minimum-samples", type=int, default=50000)
84
+ p.add_argument("--maximum-samples", type=int, default=50000)
85
+ p.add_argument("--max-iter", type=int, default=50)
86
+ p.add_argument("--workers", type=int, default=1, help="Number of inference workers; default is 1")
87
+ p.add_argument("--seed", type=int, default=42)
88
+ a = p.parse_args()
89
+ fit_groups(read_csv(a.input), a.output, a.audit, a.width_m, a.length_m, a.initial_percentile,
90
+ a.minimum_samples, a.maximum_samples, a.max_iter, a.workers, a.seed)
91
+
92
+
93
+ if __name__ == "__main__":
94
+ main()
Processing_Code/generate_vehicle_pairs.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generate directed same-direction pairs and the author's relative-velocity local coordinates."""
2
+ import json
3
+ from pathlib import Path
4
+ import numpy as np
5
+ import pandas as pd
6
+ from scipy.spatial import cKDTree
7
+ from _common import numeric, output_path, parser, read_csv, require, unique, preflight_outputs
8
+
9
+ PAIR_COLUMNS = ["Frame", "EV_Vehicle_ID", "POV_Vehicle_ID", "x_local", "y_local", "v_rel", "cangle",
10
+ "cangle_deg", "Distance_m", "Angle_Defined"]
11
+
12
+
13
+ def iter_pairs(basic, distance_threshold=50.0, min_distance=0.5, x_column="x_center", y_column="y_center", audit=None):
14
+ basic = basic.copy()
15
+ if not np.isfinite([distance_threshold, min_distance]).all() or not 0 <= min_distance < distance_threshold:
16
+ raise ValueError("Require 0 <= min_distance < distance_threshold")
17
+ numeric(basic, ["Frame", "Ego_Vehicle_ID"], integer=True)
18
+ numeric(basic, [x_column, y_column, "v_x", "v_y"])
19
+ require(basic, ["Direction"])
20
+ unique(basic, ["Frame", "Ego_Vehicle_ID"])
21
+ if not basic.Direction.isin(["Left", "Right"]).all():
22
+ raise ValueError("Direction must be Left or Right")
23
+ if "Source_ID" in basic and (basic.Source_ID.isna().any() or basic.Source_ID.nunique() != 1):
24
+ raise ValueError("Process one synchronized source recording at a time")
25
+ if "Time_s" in basic:
26
+ numeric(basic, ["Time_s"])
27
+ if basic.groupby("Frame").Time_s.nunique().gt(1).any():
28
+ raise ValueError("A frame must represent a single physical time")
29
+ stats = audit if audit is not None else {}
30
+ stats.update(input_rows=len(basic), output_pairs=0, zero_relative_velocity_pairs=0, undefined_heading_angle_pairs=0,
31
+ max_distance_m=distance_threshold, max_distance_inclusive=False, min_distance_m=min_distance,
32
+ min_distance_inclusive=True, position_difference="POV-EV", velocity_difference="EV-POV")
33
+ for (frame, direction), group in basic.groupby(["Frame", "Direction"], sort=True):
34
+ if len(group) < 2:
35
+ continue
36
+ group = group.sort_values("Ego_Vehicle_ID")
37
+ xy = group[[x_column, y_column]].to_numpy(float)
38
+ undirected = cKDTree(xy).query_pairs(distance_threshold, output_type="ndarray")
39
+ if not len(undirected):
40
+ continue
41
+ indexes = np.concatenate([undirected, undirected[:, ::-1]])
42
+ i, j = indexes.T
43
+ delta = xy[j] - xy[i]
44
+ distance = np.linalg.norm(delta, axis=1)
45
+ velocity = group[["v_x", "v_y"]].to_numpy(float)
46
+ dv = velocity[i] - velocity[j]
47
+ relative = np.linalg.norm(dv, axis=1)
48
+ eligible = (distance >= min_distance) & (distance < distance_threshold)
49
+ stats["zero_relative_velocity_pairs"] += int((eligible & (relative == 0)).sum())
50
+ keep = eligible & (relative != 0)
51
+ i, j, delta, dv, distance, relative = i[keep], j[keep], delta[keep], dv[keep], distance[keep], relative[keep]
52
+ if not len(i):
53
+ continue
54
+ vi, vj = velocity[i], velocity[j]
55
+ cross = vi[:, 0] * vj[:, 1] - vj[:, 0] * vi[:, 1]
56
+ dot = np.sum(vi * vj, axis=1)
57
+ angle = -np.degrees(np.arctan2(cross, dot))
58
+ defined = (np.linalg.norm(vi, axis=1) > 0) & (np.linalg.norm(vj, axis=1) > 0)
59
+ # Preserve the uploaded atan2(0,0)=0 convention; expose the undefined heading explicitly.
60
+ stats["undefined_heading_angle_pairs"] += int((~defined).sum())
61
+ ids = group.Ego_Vehicle_ID.to_numpy()
62
+ out = pd.DataFrame({"Frame": frame, "EV_Vehicle_ID": ids[i], "POV_Vehicle_ID": ids[j],
63
+ "x_local": (dv[:, 1] * delta[:, 0] - dv[:, 0] * delta[:, 1]) / relative,
64
+ "y_local": np.sum(dv * delta, axis=1) / relative,
65
+ "v_rel": relative, "cangle": ((np.abs(angle) >= 5) & (np.abs(angle) <= 175)).astype(int),
66
+ "cangle_deg": angle, "Distance_m": distance, "Angle_Defined": defined})
67
+ stats["output_pairs"] += len(out)
68
+ yield out.sort_values(["EV_Vehicle_ID", "POV_Vehicle_ID"]).reset_index(drop=True)
69
+
70
+
71
+ def generate_pairs(basic, **kwargs):
72
+ parts = list(iter_pairs(basic, **kwargs))
73
+ return pd.concat(parts, ignore_index=True) if parts else pd.DataFrame(columns=PAIR_COLUMNS)
74
+
75
+
76
+ def main():
77
+ p = parser(__doc__)
78
+ p.add_argument("--input", required=True, help="Released observation-group Basic CSV or single-source Basic CSV; positions in meters")
79
+ p.add_argument("--output", required=True, help="New frame-sorted directed pair CSV")
80
+ p.add_argument("--audit", required=True, help="New JSON counts and conventions")
81
+ p.add_argument("--x-column", default="x_center", help="Metric longitudinal coordinate column; x_reconstructed for older reconstruction tables")
82
+ p.add_argument("--y-column", default="y_center", help="Metric lateral coordinate column; y_reconstructed for older reconstruction tables")
83
+ p.add_argument("--max-distance-m", type=float, default=50.)
84
+ p.add_argument("--min-distance-m", type=float, default=0.5, help="Minimum center-distance cutoff in meters")
85
+ a = p.parse_args()
86
+ preflight_outputs(a.output, a.audit)
87
+ if Path(a.audit).resolve() == Path(a.output).resolve() or Path(a.audit).exists():
88
+ raise FileExistsError("Choose distinct new output and audit filenames")
89
+ stats = {}
90
+ with output_path(a.output) as temporary:
91
+ first = True
92
+ for part in iter_pairs(read_csv(a.input), a.max_distance_m, a.min_distance_m, a.x_column, a.y_column, stats):
93
+ part.to_csv(temporary, mode="w" if first else "a", header=first, index=False)
94
+ first = False
95
+ if first:
96
+ pd.DataFrame(columns=PAIR_COLUMNS).to_csv(temporary, index=False)
97
+ with output_path(a.audit) as temporary:
98
+ Path(temporary).write_text(json.dumps(stats, indent=2, allow_nan=False), encoding="utf-8")
99
+
100
+
101
+ if __name__ == "__main__":
102
+ main()
Processing_Code/merge_vehicle_lengths.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Join fixed length estimates using explicit source and original vehicle identifiers."""
2
+ import pandas as pd
3
+ import numpy as np
4
+
5
+ from _common import numeric, parser, read_csv, require, save_csv, unique
6
+
7
+
8
+ def attach_lengths(basic, lengths, mapping=None):
9
+ basic = basic.copy()
10
+ lengths = lengths.copy().rename(columns={"Vehicle_ID": "Original_Vehicle_ID"})
11
+ keys = ["Source_ID", "Original_Vehicle_ID"]
12
+ require(lengths, keys + ["Vehicle_Length_m"])
13
+ numeric(lengths, ["Original_Vehicle_ID"], integer=True)
14
+ lengths["Vehicle_Length_m"] = pd.to_numeric(lengths["Vehicle_Length_m"], errors="raise")
15
+ known = lengths.Vehicle_Length_m.dropna()
16
+ if not np.isfinite(known).all() or known.le(0).any():
17
+ raise ValueError("Known Vehicle_Length_m values must be positive and finite; missing estimates may remain blank")
18
+ unique(lengths, keys)
19
+ if mapping is not None:
20
+ require(mapping, ["Ego_Vehicle_ID"] + keys)
21
+ numeric(mapping, ["Ego_Vehicle_ID", "Original_Vehicle_ID"], integer=True)
22
+ unique(mapping, ["Ego_Vehicle_ID"])
23
+ unique(mapping, keys)
24
+ if set(keys) & set(basic):
25
+ raise ValueError("Mapping is only needed when basic data lack both lineage columns")
26
+ basic = basic.merge(mapping[["Ego_Vehicle_ID"] + keys], on="Ego_Vehicle_ID",
27
+ how="left", validate="many_to_one")
28
+ require(basic, keys)
29
+ numeric(basic, ["Original_Vehicle_ID"], integer=True)
30
+ if basic[keys].isna().any().any():
31
+ raise ValueError("Incomplete source/vehicle mapping")
32
+ if "Ego_Vehicle_ID" in basic:
33
+ numeric(basic, ["Ego_Vehicle_ID"], integer=True)
34
+ lineage = basic[["Ego_Vehicle_ID"] + keys].drop_duplicates()
35
+ if lineage.Ego_Vehicle_ID.duplicated().any() or lineage.duplicated(keys).any():
36
+ raise ValueError("Ego_Vehicle_ID and source/original vehicle identity must map one-to-one")
37
+ if "Vehicle_Length_m" in basic:
38
+ raise ValueError("Vehicle_Length_m already exists; explicitly resolve it before merging")
39
+ result = basic.merge(lengths[keys + ["Vehicle_Length_m"]], on=keys,
40
+ how="left", validate="many_to_one", indicator=True)
41
+ if result._merge.ne("both").any():
42
+ raise ValueError("Some basic trajectories have no row in the length table")
43
+ print(f"Rows with insufficient length estimates: {result.Vehicle_Length_m.isna().sum():,}")
44
+ return result.drop(columns="_merge")
45
+
46
+
47
+ def main():
48
+ p = parser(__doc__)
49
+ p.add_argument("--input", required=True, help="Reconstructed basic trajectory CSV")
50
+ p.add_argument("--lengths", required=True, help="Per-vehicle length CSV, possibly concatenated across sources")
51
+ p.add_argument("--mapping", help="Optional verified Ego_Vehicle_ID/Source_ID/Original_Vehicle_ID mapping CSV")
52
+ p.add_argument("--output", required=True, help="New basic trajectory CSV with fixed lengths")
53
+ a = p.parse_args()
54
+ result = attach_lengths(read_csv(a.input), read_csv(a.lengths), read_csv(a.mapping) if a.mapping else None)
55
+ save_csv(result, a.output)
56
+
57
+
58
+ if __name__ == "__main__":
59
+ main()
Processing_Code/reconstruct_trajectories.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 lane_direction, numeric, parser, read_csv, require, save_csv, unique, preflight_outputs
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
+ lane_direction(df, allow_missing=True)
56
+ numeric(df, ["Frame", "Vehicle_ID"], integer=True)
57
+ numeric(df, ["x_center", "y_center"])
58
+ unique(df, ["Frame", "Vehicle_ID"])
59
+ if "Source_ID" in df and not df.Source_ID.eq(source).all():
60
+ raise ValueError("Reconstruct one constant-FPS source video at a time")
61
+ first_frame = df.Frame.min()
62
+ df, rejected, audit = split_tracks(df, fps)
63
+ parts = []
64
+ for vid, group in df.groupby("Vehicle_ID", sort=True):
65
+ group = group.sort_values("Frame").set_index("Frame")
66
+ if group.Direction.dropna().nunique() != 1 or not group["Lane number"].notna().any():
67
+ raise ValueError(f"Missing/changing Direction or missing lanes for vehicle {vid}")
68
+ if not group.Direction.dropna().isin(["Left", "Right"]).all():
69
+ raise ValueError(f"Direction must be Left or Right for vehicle {vid}")
70
+ frames = np.arange(group.index.min(), group.index.max() + 1)
71
+ expanded = group.reindex(frames)
72
+ out = pd.DataFrame({"Source_ID": source, "Original_Vehicle_ID": vid,
73
+ "Original_Frame": frames, "Frame": frames + frame_offset,
74
+ "Ego_Vehicle_ID": int(vid) + id_offset,
75
+ "Time_s": time_offset + (frames - first_frame) / fps})
76
+ out["Delta_t_s"] = np.r_[np.nan, np.full(len(frames) - 1, 1 / fps)]
77
+ out["Lane number"] = fill_lane(expanded["Lane number"]).to_numpy()
78
+ out["Direction"] = expanded.Direction.ffill().bfill().to_numpy()
79
+ for axis in ("x", "y"):
80
+ filled = interpolate_coordinates(expanded[f"{axis}_center"])
81
+ if filled.isna().any():
82
+ raise ValueError(f"Unfilled coordinates: vehicle {vid}")
83
+ position = sema(filled.to_numpy(), fps, window_s)
84
+ out[f"{axis}_center"] = position
85
+ out[f"v_{axis}"], out[f"a_{axis}"] = kinematics(position, 1 / fps)
86
+ if merge_x is not None:
87
+ out["Dist_to_Merge_m"] = np.abs(out.x_center - merge_x)
88
+ if diverge_x is not None:
89
+ out["Dist_to_Diverge_m"] = np.abs(out.x_center - diverge_x)
90
+ parts.append(out)
91
+ out = pd.concat(parts, ignore_index=True) if parts else pd.DataFrame()
92
+ print(f"Rejected {int(audit.Rejected.sum())} tracks; review audit for reasons; lane filling=ffill/bfill")
93
+ if return_audit:
94
+ return out, rejected, audit
95
+ if out.empty:
96
+ raise ValueError("No trajectories remain after screening")
97
+ return out
98
+
99
+
100
+ def main():
101
+ p = parser(__doc__)
102
+ p.add_argument("--input", required=True, help="Metric trajectory CSV with lane/direction annotations")
103
+ p.add_argument("--output", required=True, help="New reconstructed metric trajectory CSV")
104
+ p.add_argument("--source", required=True, help="Source video identifier")
105
+ p.add_argument("--fps", required=True, type=float, help="Actual constant source frame rate")
106
+ p.add_argument("--rejected", required=True, help="New rejected metric-record CSV for review")
107
+ p.add_argument("--audit", required=True, help="New per-vehicle screening summary CSV")
108
+ p.add_argument("--window-s", type=float, default=0.6)
109
+ p.add_argument("--id-offset", type=int, default=0, help="Explicit offset for unique IDs across sources")
110
+ p.add_argument("--frame-offset", type=int, default=0, help="Frame-label offset, not elapsed time")
111
+ p.add_argument("--time-offset", type=float, default=0.0, help="Seconds at first input source frame")
112
+ p.add_argument("--merge-x-m", type=float, help="Measured merge reference x in the same metric system")
113
+ p.add_argument("--diverge-x-m", type=float, help="Measured diverge reference x in the same metric system")
114
+ a = p.parse_args()
115
+ preflight_outputs(a.output, a.rejected, a.audit)
116
+ out, rejected, audit = reconstruct(read_csv(a.input), a.fps, a.source, a.window_s,
117
+ a.id_offset, a.frame_offset, a.time_offset,
118
+ a.merge_x_m, a.diverge_x_m, return_audit=True)
119
+ save_csv(audit, a.audit)
120
+ save_csv(rejected, a.rejected)
121
+ if out.empty:
122
+ raise ValueError("All trajectories rejected; review saved audit; no reconstruction file written")
123
+ save_csv(out, a.output)
124
+
125
+
126
+ if __name__ == "__main__":
127
+ main()
Processing_Code/requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ numpy==2.3.5
2
+ pandas==2.2.3
3
+ scipy==1.17.0
4
+ opencv-python-headless==5.0.0.93