Analysis
Generated by docs/scripts/make_api_pages.py.
Analyses on pipeline output: data quality, surrounding vehicles, statistics and traffic quantities.
analysis.quality: reconstruction and lane-assignment quality measures.analysis.interactions: surrounding vehicles and neighbours of every trajectory point.analysis.statistics: bootstrap confidence intervals, agreement measures and paired tests.analysis.traffic: macroscopic quantities (Edie).
Per-step neighbours on any lane column, built on analysis.interactions.surroundings.compute_surroundings.
The merge analysis runs on lanes from different sources (pipeline, provider, map, lane drop). The neighbours are
taken from compute_surroundings on the analysis frame's own (cleaned) lane column, keyed by the integer grid
step tk (10 Hz), so that *_left of a vehicle on lane 0 is the vehicle ahead of / behind it on lane 1, with
the pipeline's tie rule (a vehicle exactly level counts as rear neighbour). This replaces the per-frame search of
the earlier field merge table.
step_surroundings
step_surroundings(traj: DataFrame) -> pd.DataFrame
Find the neighbours of every row of an analysis frame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
traj
|
DataFrame
|
Analysis frame ( |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
Frame indexed by |
DataFrame
|
positions of |
DataFrame
|
surroundings columns of |
neighbour_on_lane
neighbour_on_lane(sur_row: Series | None, subject_lane: int, target_lane: int, side: str) -> str | None
Return the vehicle ahead of or behind a subject on a given lane.
Only the subject's own lane and its two neighbour lanes are known.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sur_row
|
Series | None
|
Row of |
required |
subject_lane
|
int
|
Lane of the subject. |
required |
target_lane
|
int
|
Lane on which the neighbour is looked for. |
required |
side
|
str
|
|
required |
Returns:
| Type | Description |
|---|---|
str | None
|
The neighbour's ID; None without a row, for a lane farther than one away or when there is no neighbour. |
Surrounding vehicles of every trajectory point: the six neighbours on the own and the two adjacent lanes.
compute_surroundings
compute_surroundings(df: DataFrame, datetime_col: str = C.TIME, time_col_seconds: str | None = None, lane_col: str = C.LANE, x_col: str = C.POS_LON, v_col: str = C.SPEED, id_col: str = C.ID, length_col: str = C.LENGTH, default_length_m: float = C.DEFAULT_VEHICLE_LENGTH_M, tie_tolerance_m: float = C.SIDE_BY_SIDE_TOLERANCE_M) -> pd.DataFrame
Find the surrounding vehicles of every trajectory point.
For each vehicle and timestamp, identifies the closest lead and following vehicle in the same lane and the two
adjacent lanes, yielding six surrounding positions: front, rear, front_left, rear_left,
front_right, rear_right. By convention *_left is lane + 1 and *_right lane - 1, so vehicles in
lane 1 see lane-0 (auxiliary-lane) vehicles as right neighbours. "Front" is the direction of increasing
pos_lon (the direction of travel after the alignment step).
Uses pandas.merge_asof on the longitudinal position axis, grouped by the exact timestamp and the lane, so
neighbours are only taken from the same instant. The input must therefore be time-synchronous across vehicles,
e.g. the output of resample_to_output_grid. Each (id, time) pair must be unique. Unassigned points
(lane -1) get no neighbours and are nobody's neighbour.
Tie rule: a vehicle in an adjacent lane whose pos_lon differs from the subject's by at most
tie_tolerance_m (i.e. exactly side by side) is a rear neighbour, never a front one; its
clearance_rear_* is then negative, which signals the overlap. In the same lane such a tie is a conflict and
is excluded, as is the subject itself.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Trajectory points with vehicle ID, timestamp, lane, longitudinal position and speed ( |
required |
datetime_col
|
str
|
Name of the datetime timestamp column. |
TIME
|
time_col_seconds
|
str | None
|
Optional name of a time column to use as the time key instead of |
None
|
lane_col
|
str
|
Column containing integer lane IDs. |
LANE
|
x_col
|
str
|
Longitudinal position column [m]. |
POS_LON
|
v_col
|
str
|
Speed column [km/h]. |
SPEED
|
id_col
|
str
|
Vehicle identity column. |
ID
|
length_col
|
str
|
Vehicle bounding-box length column [m]. If missing, it is filled with |
LENGTH
|
default_length_m
|
float
|
Vehicle length used when |
DEFAULT_VEHICLE_LENGTH_M
|
tie_tolerance_m
|
float
|
Longitudinal distance up to which an adjacent-lane vehicle counts as side by side (rear neighbour) [m]. |
SIDE_BY_SIDE_TOLERANCE_M
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
A copy of the input, sorted by time and ID, with 24 additional columns (6 positions x 4 measures; the |
DataFrame
|
surroundings columns of |
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Realistic degradation of clean ground-truth trajectories.
Provider-cleaned datasets such as exiD are smoother than raw drone trajectories, so lane-assignment accuracy on them is an optimistic upper bound. Their lane labels stay valid when measurement errors are added to the positions (the true lane does not change), so degrading the positions with a measured error model gives realistic test data with ground truth.
Error model (ErrorModel, parameters from a measured error-model JSON file
or from the configuration):
- Autocorrelated noise, longitudinal and lateral to the direction of
travel, each an AR(1) process
e_t = phi e_{t-1} + sqrt(1 - phi^2) sigma w_twithphi = exp(-dt / tau)(standard deviationsigma, correlation timetauin seconds, so the result does not depend on the sampling rate). - Outlier bursts: at
outlier_rate_per_sper second of track, a burst ofoutlier_burst_sseconds in which the position jumps byoutlier_amplitude_malong the direction of travel (random sign). - Fragmentation (optional): gaps of
gap_length_satgaps_per_track_hour; the samples inside are removed. - Perspective offset (optional): HGVs are displaced laterally by
kappa_hgv * (d - d_c), withdthe lateral position relative to a reference line.
All random numbers come from numpy.random.default_rng(seed); the same
seed gives the same degraded data.
ErrorModel
dataclass
ErrorModel(sigma_lat_m: float = 0.037, tau_lat_s: float = 1.5, sigma_lon_m: float = 0.37, tau_lon_s: float = 25.8, outlier_rate_per_s: float = 0.12, outlier_burst_s: float = 0.25, outlier_amplitude_m: float = 0.08, gaps_per_track_hour: float = 0.0, gap_length_s: float = 0.0, kappa_hgv: float = 0.0, d_c_m: float = 50.0)
Parameters of the degradation (lengths in m, times in s).
Attributes:
| Name | Type | Description |
|---|---|---|
sigma_lat_m |
float
|
Standard deviation of the lateral AR(1) noise [m]. |
tau_lat_s |
float
|
Correlation time of the lateral noise [s]. |
sigma_lon_m |
float
|
Standard deviation of the longitudinal AR(1) noise [m]. |
tau_lon_s |
float
|
Correlation time of the longitudinal noise [s]. |
outlier_rate_per_s |
float
|
Outlier bursts per second of track [1/s]. |
outlier_burst_s |
float
|
Duration of one burst [s]. |
outlier_amplitude_m |
float
|
Longitudinal jump during a burst [m]. |
gaps_per_track_hour |
float
|
Fragmentation gaps per hour of track [1/h]. |
gap_length_s |
float
|
Duration of one gap [s]. |
kappa_hgv |
float
|
Perspective coefficient of the lateral HGV offset [-]; 0 disables it. |
d_c_m |
float
|
Lateral position without perspective offset [m]. |
from_json
classmethod
from_json(path: PathLike, perspective: bool = False, d_c_m: float | None = None) -> ErrorModel
Build the model from a measured error-model JSON file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
PathLike
|
The JSON file with |
required |
perspective
|
bool
|
Take |
False
|
d_c_m
|
float | None
|
Lateral position without offset [m]; the class default when None. |
None
|
Returns:
| Type | Description |
|---|---|
ErrorModel
|
The model. |
to_dict
to_dict() -> dict[str, float]
Return the parameters as a plain dict.
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
Field name -> value, in the units of the attributes (e.g. for writing the model to JSON). |
ar1_noise
ar1_noise(n: int, dt_s: float, sigma: float, tau_s: float, rng: Generator) -> FloatArray
Draw stationary AR(1) noise with a given standard deviation and correlation time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of samples. |
required |
dt_s
|
float
|
Sampling interval [s]. |
required |
sigma
|
float
|
Standard deviation (unit of the result, here [m]). |
required |
tau_s
|
float
|
Correlation time [s]; 0 or less gives white noise. |
required |
rng
|
Generator
|
Random generator. |
required |
Returns:
| Type | Description |
|---|---|
FloatArray
|
The |
degrade
degrade(gdf: GeoDataFrame, model: ErrorModel, seed: int = 0, ref_line: LineString | None = None, fragmentation: bool = False, perspective: bool = False) -> gpd.GeoDataFrame
Apply the error model to clean trajectories of one direction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gdf
|
GeoDataFrame
|
Planar trajectories ( |
required |
model
|
ErrorModel
|
Error parameters. |
required |
seed
|
int
|
Random seed. |
0
|
ref_line
|
LineString | None
|
Reference line of the direction; needed for the perspective offset (lateral position |
None
|
fragmentation
|
bool
|
Remove the samples inside gaps. |
False
|
perspective
|
bool
|
Displace HGVs laterally by |
False
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
A copy sorted by |
GeoDataFrame
|
and without the samples inside gaps; other columns, including ground-truth labels, unchanged. |
summarise_noise
summarise_noise(clean: GeoDataFrame, degraded: GeoDataFrame) -> dict[str, float]
Summarise the displacement added by degrade (for tests and reports).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
clean
|
GeoDataFrame
|
The clean planar trajectories ( |
required |
degraded
|
GeoDataFrame
|
The degraded trajectories ( |
required |
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the rows are not aligned, i.e. the lengths or the |
Event-level data-quality gate for gap-acceptance, lane-change and follower analyses, and the site-level rates.
Main functions: evaluate_gate (pass or fail per event and analysis, with the reason), track_ends (where the
tracks begin and end, and whether that is legitimate) and spawn_vanish_rates (track starts and ends inside the
view per vehicle-km). They take the output of the pipeline (TrackFrame: id, datum, pos_lon,
pos_lat, lane_fixed, lane_confidence, acceleration, id_front, length; is_bridge of
stitched data) and its lane-change events (EventFrame), so they apply to every dataset the pipeline reads.
An analysis needs several vehicles over a time window each (GATE_ANALYSES: the subject, the lead and lag in the
target lane, the lag's own leader). An event passes if every required vehicle passes every criterion:
- observed: positions over the whole window, no gap above
max_gap_s, at mostmax_bridged_shareof the window bridged; a track that begins or ends inside the window at the edge of the view or of a ramp (track_ends) makes the event censored (not usable, not failed), anywhere else it is a track end (failed); - no identity switch: no jump of the vehicle length above
max_length_jump_m; - no phantom: no other vehicle appears or vanishes within
phantom_range_mof the subject, in its lane or the target lane, inside the window and away from the view edges; - the thresholds of the reference datasets, for every role with values: lateral sweep within 10 s at most
max_lateral_sweep_m, max |a| and max |jerk| at mostmax_abs_acc/max_abs_jerk, at leastmin_confident_shareof the samples withlane_confidence >= min_confidence.
Criteria 1-3 are judged first; the reason of a failure is the first failing role and criterion in that order, so that
a structural failure (a track end, a phantom) is not hidden behind a kinematic one. A partner that does not exist
(no leader) is absent if the road ahead (behind) within absent_range_m is in view, else not observed (the event
is censored); an absent partner is a valid observation (an infinite gap), except for a partner that defines the
analysis (a follower reaction needs a follower): the event is then not applicable.
The thresholds and their sources are in trajlab/config/analysis/gate_thresholds.yaml (read_gate_thresholds).
On the reference datasets the gate passes 92-100 % of the usable events of highD and exiD and 62-78 % of NGSIM
(docs/datasets/i24_motion.md).
GateThresholds
dataclass
GateThresholds(max_gap_s: float, max_bridged_share: float, view_edge_m: float, ramp_edge_m: float, phantom_range_m: float, absent_range_m: float, max_lateral_sweep_m: float, max_length_jump_m: float, min_confidence: float, min_confident_share: float, max_abs_acc: float, max_abs_jerk: float)
Thresholds of the gate (read_gate_thresholds; sources in gate_thresholds.yaml).
Attributes:
| Name | Type | Description |
|---|---|---|
max_gap_s |
float
|
Longest time between two positions that counts as observed [s]. |
max_bridged_share |
float
|
Largest share of a window bridged by a stitching. |
view_edge_m |
float
|
A track begins or ends at the edge of the view within this distance of it [m]. |
ramp_edge_m |
float
|
A track begins (ends) at a ramp within this distance of an on-ramp (off-ramp) zone start (end) [m]. |
phantom_range_m |
float
|
Range around the subject in which an appearing or vanishing vehicle breaks the scene [m]. |
absent_range_m |
float
|
Range ahead of (behind) the subject that must be in view for a missing partner to be absent [m]. |
max_lateral_sweep_m |
float
|
Largest lateral sweep within |
max_length_jump_m |
float
|
Largest jump of the vehicle length in a window [m]. |
min_confidence |
float
|
A sample is lane-confident from this |
min_confident_share |
float
|
Smallest share of lane-confident samples in a window. |
max_abs_acc |
float
|
Largest |acceleration| in a window [m/s^2]. |
max_abs_jerk |
float
|
Largest |jerk| in a window [m/s^3]. |
GateRole
dataclass
GateRole(name: str, start: tuple[Anchor, float], end: tuple[Anchor, float], required: bool = True, defines: bool = False)
A vehicle an analysis needs, and its window relative to the event's times.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
|
start |
tuple[Anchor, float]
|
Window start: the event time it refers to ( |
end |
tuple[Anchor, float]
|
Window end, likewise. |
required |
bool
|
The event fails if the vehicle fails a criterion of observation (else its values are reported). |
defines |
bool
|
The analysis needs this vehicle to exist: if it is absent, the event is not applicable. |
GateAnalysis
dataclass
GateAnalysis(kind: str, roles: tuple[GateRole, ...] = tuple())
The event kind of one analysis ("merge", "lane_change" or "any") and its roles.
Attributes:
| Name | Type | Description |
|---|---|---|
kind |
str
|
Event kind the analysis reads: |
roles |
tuple[GateRole, ...]
|
The vehicles the analysis must observe and over which window each. |
read_gate_thresholds
read_gate_thresholds(path: Path | str | None = None) -> GateThresholds
Read the thresholds of the gate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path | str | None
|
YAML file with one entry per field of |
None
|
Returns:
| Type | Description |
|---|---|
GateThresholds
|
The thresholds. |
detect_gate_events
detect_gate_events(events: DataFrame) -> pd.DataFrame
Select the lane changes the gate judges: merges (lane 0 to lane 1) and changes between main lanes.
Changes without a lateral start or a crossing, and changes the pipeline places at the end of a track at the end
of the road (near_road_end), are left out.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
events
|
DataFrame
|
Pipeline events ( |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
The selected events with |
track_ends
track_ends(tracks: DataFrame, view: tuple[float, float], *, entry_zones: Sequence[tuple[float, float]] = (), exit_zones: Sequence[tuple[float, float]] = (), ramp_max_lane: int = 1, thresholds: GateThresholds | None = None) -> pd.DataFrame
Return the first and last position of every track, and whether it lies at the edge of the view or of a ramp.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tracks
|
DataFrame
|
Pipeline output ( |
required |
view
|
tuple[float, float]
|
Observed |
required |
entry_zones
|
Sequence[tuple[float, float]]
|
|
()
|
exit_zones
|
Sequence[tuple[float, float]]
|
Of off-ramp zones: an end on lane 0 or 1 within |
()
|
ramp_max_lane
|
int
|
Highest lane label of a start or end at a ramp (a dataset whose ramp roadway carries main-lane labels, as NGSIM US-101, needs a higher value). |
1
|
thresholds
|
GateThresholds | None
|
Thresholds ( |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per track and end ( |
DataFrame
|
and |
spawn_vanish_rates
spawn_vanish_rates(tracks: DataFrame, view: tuple[float, float], *, breaks: ndarray | None = None, break_m: float = 60.0, lon_range: tuple[float, float] | None = None, ends: DataFrame | None = None, thresholds: GateThresholds | None = None) -> dict[str, float]
Return the track starts (spawns) and ends (vanishes) per vehicle-km on the main lanes inside the view.
Counted: starts and ends on lanes 1 and higher, at least view_edge_m inside the view, not legitimate
(track_ends); with breaks, also those farther than break_m from every camera break. The tracks are
taken whole; with lon_range only the ends and the travel inside it count (a site in a longer view). On the
reference datasets the rates are 0-0.015 per vehicle-km.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tracks
|
DataFrame
|
Pipeline output ( |
required |
view
|
tuple[float, float]
|
Observed |
required |
breaks
|
ndarray | None
|
Camera breaks, |
None
|
break_m
|
float
|
Distance from a break below which an end lies at the break [m]. |
60.0
|
lon_range
|
tuple[float, float] | None
|
|
None
|
ends
|
DataFrame | None
|
|
None
|
thresholds
|
GateThresholds | None
|
Thresholds ( |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
|
dict[str, float]
|
|
evaluate_gate
evaluate_gate(tracks: DataFrame, events: DataFrame, analysis: str, *, view: tuple[float, float], thresholds: GateThresholds | None = None, ends: DataFrame | None = None) -> pd.DataFrame
Apply the gate of one analysis to every event of its kind.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tracks
|
DataFrame
|
Pipeline output ( |
required |
events
|
DataFrame
|
|
required |
analysis
|
str
|
Key of |
required |
view
|
tuple[float, float]
|
Observed |
required |
thresholds
|
GateThresholds | None
|
Thresholds; None: the shipped ones. With infinite kinematic, sweep and zero confidence thresholds the result holds the reference distributions of the values. |
None
|
ends
|
DataFrame | None
|
|
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per event: |
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
Raises:
| Type | Description |
|---|---|
KeyError
|
If |
Reconstruction quality measures on trajectories and merge time series.
All functions take plain frames with id, t [s], x / y [m] and optionally a [m/s^2] and return
per-vehicle (or per-merge) tables, so that a reference dataset (e.g. exiD) and a candidate (e.g. I-24) are measured
the same way.
smoothing_residual: standard deviation of the positions around a local cubic fit overwindow_s— an estimate of the measurement noise (longitudinal and lateral), the lower bound of the scatter later analyses see.jerk_stats: longitudinal jerk (froma) and lateral jerk (third derivative of a smoothedy); shares of implausible values.joint_jumps: jump of the lateral speed and of the acceleration at stitching joints relative to their surroundings.lateral_zero_crossings: number of sign changes of the smoothed lateral speed (waviness) within a window.
smoothing_residual
smoothing_residual(df: DataFrame, window_s: float = 1.0) -> pd.DataFrame
Estimate the measurement noise per vehicle as the scatter around a local cubic fit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Trajectories with |
required |
window_s
|
float
|
Length of the Savitzky-Golay window [s]. |
1.0
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per vehicle long enough for the window: |
DataFrame
|
(standard deviations of |
jerk_stats
jerk_stats(df: DataFrame, smooth_s: float = 1.0) -> pd.DataFrame
Compute jerk percentiles and the shares of implausible samples per vehicle.
The longitudinal jerk is the derivative of a; the lateral jerk the third derivative of y smoothed by a
cubic Savitzky-Golay filter over smooth_s.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Trajectories with |
required |
smooth_s
|
float
|
Length of the smoothing window [s]. |
1.0
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per vehicle with at least 10 samples: |
DataFrame
|
|
DataFrame
|
( |
DataFrame
|
[m/s^3] and |
joint_jumps
joint_jumps(df: DataFrame, joint_col: str = 'stitch_joint', near_s: float = 0.5, ring_s: Sequence[float] = (1.0, 3.0)) -> pd.DataFrame
Measure the step a stitching joint adds on top of the vehicle's own motion.
Per joint, the peak |lateral speed| (from 0.2-s differences) and the peak |a| within near_s of the joint
minus their medians in the ring ring_s away on both sides.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Trajectories with |
required |
joint_col
|
str
|
Boolean column marking the first sample after a joint. |
'stitch_joint'
|
near_s
|
float
|
Half-width of the window around the joint [s]. |
0.5
|
ring_s
|
Sequence[float]
|
Inner and outer distance of the reference ring [s]. |
(1.0, 3.0)
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per joint with a usable ring: |
DataFrame
|
|
lateral_zero_crossings
lateral_zero_crossings(t: ArrayLike, y: ArrayLike, smooth_s: float = 1.0, min_speed: float = 0.05) -> int
Count the sign changes of the smoothed lateral speed, a measure of the waviness of a lateral course.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
t
|
ArrayLike
|
Sample times [s]. |
required |
y
|
ArrayLike
|
Lateral positions [m]. |
required |
smooth_s
|
float
|
Length of the cubic Savitzky-Golay window [s]. |
1.0
|
min_speed
|
float
|
Only speeds with a magnitude above this count [m/s]. |
0.05
|
Returns:
| Type | Description |
|---|---|
int
|
The number of sign changes; 0 for fewer than 10 samples or a track shorter than the window. |
Check before a run: does the lateral occupancy show more lanes than the site configuration has?
The lane tracking of the pipeline (docs/pipeline/06_lane_geometry.md) fits at most n_main_lanes lanes, plus
the auxiliary lane inside the configured zones. Where the road has an auxiliary, weaving or ramp lane that no zone
covers, the fit merges two lanes or invents one, and the lane tracking can carry that error far downstream. This
check counts the lanes seen in the data per section of the road and names the sections where the data show more
lanes than are configured, so that a zone can be added before the run.
detect_unconfigured_lanes
detect_unconfigured_lanes(df: DataFrame, layout: LaneLayout | LanesConfig, *, section_m: float = 200.0, min_points: int = 2000, mile_col: str | None = None) -> pd.DataFrame
Count the lanes in the lateral occupancy per section and warn where there are more than configured.
Per section of section_m along pos_lon, the lane peaks are the peaks of the histogram of pos_lat
(bins of LANE_PEAK_BIN_M, smoothed over three bins; peaks at least LANE_PEAK_MIN_DISTANCE_M apart and
with a prominence of at least LANE_PEAK_PROMINENCE of the highest one). The lanes seen are the longest chain
of neighbouring peaks whose distances lie in LANE_SPACING_M: the count follows the lanes wherever they lie
laterally, so a drift or a lateral shift of the positions neither adds nor removes a lane. The configured lanes
are the main lanes there (n_main_lanes or a lane-count zone) plus one where an auxiliary-lane zone overlaps
the section.
Use the raw positions of one direction (a reader's output, before the run), over a window long enough to fill
every lane (a few minutes of free flow).
The count is a check, not a measurement: a ramp roadway still in view beside its auxiliary lane, or a wide shoulder used by stopped vehicles, adds a peak. Each warning names a place to look at, not a missing zone.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Positions of one direction with |
required |
layout
|
LaneLayout | LanesConfig
|
The lane layout of the run: a |
required |
section_m
|
float
|
Length of a section [m]. |
200.0
|
min_points
|
int
|
Sections with fewer positions are not checked. |
2000
|
mile_col
|
str | None
|
Column with mile markers (e.g. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per section with at least |
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
Warns:
| Type | Description |
|---|---|
UserWarning
|
Once, listing the sections with |
Metrics for lane assignment, with and without ground truth.
The functions compare an estimated lane label per (vehicle, time) with a ground-truth label on the same keys, or, without ground truth, measure how plausible the estimated labels are on their own.
With ground truth:
- Point-wise accuracy: share of rows whose estimated lane equals the true lane, overall and per true lane, plus a confusion matrix (rows = true lane, columns = estimated lane).
- Sequence accuracy: share of vehicles whose whole label sequence is correct.
- Lane-change events: every label transition is an event at the first sample in the new lane. An estimated event matches a true one of the same vehicle and direction if their times differ by at most the tolerance (default 1 s); each event is matched at most once (closest first). From the matches: precision (share of estimated events that are real), recall (share of real events that were found), F1 (their harmonic mean) and the mean absolute time error of the matched pairs.
- Spurious transitions per vehicle-km: unmatched estimated events, divided by the distance driven by all vehicles.
Without ground truth (consistency):
- Flicker: transitions that are undone within
flicker_window_s(A -> B -> A within 2 s). - Space-time conflicts: rows where another vehicle is in the same lane at the same time and the two overlap longitudinally (centre distance below the mean of the two lengths).
- Transitions per vehicle-km and the agreement between two methods.
All times are seconds, distances metres. Rows with a missing or negative label (-1 = unassigned) are left out of accuracy and event metrics.
align_labels
align_labels(est: DataFrame, gt: DataFrame, est_col: str = C.LANE_FIXED, gt_col: str = 'lane_gt', id_col: str = C.ID, time_col: str = C.TIME) -> pd.DataFrame
Join estimated and true labels on (id, time).
Rows whose true label is missing or negative are dropped; a missing estimated label stays as -1 (counted as wrong).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
est
|
DataFrame
|
Estimated labels with |
required |
gt
|
DataFrame
|
True labels with |
required |
est_col
|
str
|
Estimated label column. |
LANE_FIXED
|
gt_col
|
str
|
True label column. |
'lane_gt'
|
id_col
|
str
|
Vehicle ID column. |
ID
|
time_col
|
str
|
Time column. |
TIME
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Indexed by (id, time), with the integer columns |
lane_accuracy
lane_accuracy(joined: DataFrame) -> dict[str, Any]
Compute the point-wise and sequence accuracy of aligned labels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
joined
|
DataFrame
|
Result of |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
|
dict[str, Any]
|
= true lane, columns = estimated lane, counts), |
dict[str, Any]
|
row [-], 0 … 1) and |
label_transitions
label_transitions(df: DataFrame, lane_col: str = C.LANE_FIXED, id_col: str = C.ID, time_col: str = C.TIME) -> pd.DataFrame
List all label changes: one row per transition at the first sample in the new lane.
Unassigned rows (missing or negative label) are skipped, i.e. A, -1, B counts as one transition A -> B.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Labels with |
required |
lane_col
|
str
|
Lane label column. |
LANE_FIXED
|
id_col
|
str
|
Vehicle ID column. |
ID
|
time_col
|
str
|
Time column. |
TIME
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
A frame (not one of the documented schemas) with |
DataFrame
|
lane), |
DataFrame
|
right). |
match_events
match_events(est: DataFrame, gt: DataFrame, tolerance_s: float = 1.0) -> dict[str, Any]
Match estimated to true lane-change events (same vehicle and direction, |dt| <= tolerance).
Greedy, closest pairs first; every event is used at most once.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
est
|
DataFrame
|
Estimated transitions as returned by |
required |
gt
|
DataFrame
|
True transitions as returned by |
required |
tolerance_s
|
float
|
Maximum time difference [s]. |
1.0
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
|
dict[str, Any]
|
error of matched pairs [s]) and |
dict[str, Any]
|
|
vehicle_km
vehicle_km(df: DataFrame, id_col: str = C.ID, lon_col: str = C.POS_LON) -> float
Compute the total distance driven by all vehicles.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Trajectories with |
required |
id_col
|
str
|
Vehicle ID column. |
ID
|
lon_col
|
str
|
Longitudinal position column [m]. |
POS_LON
|
Returns:
| Type | Description |
|---|---|
float
|
The sum of the |
label_flicker
label_flicker(transitions: DataFrame, window_s: float = 2.0) -> int
Count the transitions undone within window_s [s] (A -> B followed by B -> A).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
transitions
|
DataFrame
|
Result of |
required |
window_s
|
float
|
Maximum time between the two transitions [s]. |
2.0
|
Returns:
| Type | Description |
|---|---|
int
|
The number of undone transitions. |
conflict_rows
conflict_rows(df: DataFrame, lane_col: str = C.LANE_FIXED, id_col: str = C.ID, time_col: str = C.TIME, lon_col: str = C.POS_LON, length_col: str = C.LENGTH, default_length_m: float = C.DEFAULT_VEHICLE_LENGTH_M, margin_m: float = 0.0) -> pd.Series
Mark the rows where another vehicle occupies the same lane at the same time and overlaps.
Two vehicles overlap if |s1 - s2| < (L1 + L2) / 2 + margin_m (centre positions). Only neighbours in
pos_lon order are compared, which finds every overlap of sorted intervals of similar length.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Trajectories with the ID, time, lane, position and optionally length columns ( |
required |
lane_col
|
str
|
Lane label column. |
LANE_FIXED
|
id_col
|
str
|
Vehicle ID column. |
ID
|
time_col
|
str
|
Time column. |
TIME
|
lon_col
|
str
|
Longitudinal position column [m]. |
POS_LON
|
length_col
|
str
|
Vehicle length column [m]; |
LENGTH
|
default_length_m
|
float
|
Length of vehicles without one [m]. |
DEFAULT_VEHICLE_LENGTH_M
|
margin_m
|
float
|
Additional distance that still counts as overlap [m]. |
0.0
|
Returns:
| Type | Description |
|---|---|
Series
|
Boolean series on the index of |
consistency_metrics
consistency_metrics(df: DataFrame, lane_col: str = C.LANE_FIXED, flicker_window_s: float = 2.0, id_col: str = C.ID, time_col: str = C.TIME) -> dict[str, float]
Measure the plausibility of one lane labelling without ground truth.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Trajectories ( |
required |
lane_col
|
str
|
Lane label column. |
LANE_FIXED
|
flicker_window_s
|
float
|
Window for undone transitions [s]. |
2.0
|
id_col
|
str
|
Vehicle ID column. |
ID
|
time_col
|
str
|
Time column. |
TIME
|
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
|
dict[str, float]
|
[1/km], |
method_agreement
method_agreement(a: DataFrame, b: DataFrame, col_a: str = C.LANE_FIXED, col_b: str | None = None, id_col: str = C.ID, time_col: str = C.TIME) -> dict[str, Any]
Measure the agreement of two labellings on their common (id, time) keys.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
DataFrame
|
First labelling: frame with |
required |
b
|
DataFrame
|
Second labelling: frame with |
required |
col_a
|
str
|
Label column of |
LANE_FIXED
|
col_b
|
str | None
|
Label column of |
None
|
id_col
|
str
|
Vehicle ID column. |
ID
|
time_col
|
str
|
Time column. |
TIME
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
|
dict[str, Any]
|
rows). |
evaluate_lanes
evaluate_lanes(est: TrackFrame, gt: DataFrame | None = None, est_col: str = C.LANE_FIXED, gt_col: str = 'lane_gt', tolerance_s: float = 1.0, flicker_window_s: float = 2.0) -> dict[str, float]
Compute all lane metrics of one estimate in a flat dict (ground-truth metrics only if gt is given).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
est
|
TrackFrame
|
Estimated output ( |
required |
gt
|
DataFrame | None
|
Ground truth with |
None
|
est_col
|
str
|
Estimated label column. |
LANE_FIXED
|
gt_col
|
str
|
True label column. |
'lane_gt'
|
tolerance_s
|
float
|
Event matching tolerance [s]. |
1.0
|
flicker_window_s
|
float
|
Window for undone transitions [s]. |
2.0
|
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
Flat dict of scalars: the |
dict[str, float]
|
|
dict[str, float]
|
|
class_group
class_group(label: object, hgv_classes: Sequence[str] = HGV_CLASSES, motorcycle_classes: Sequence[str] = MOTORCYCLE_CLASSES) -> str
Group a class label (case-insensitive) into "hgv", "motorcycle" or "car".
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label
|
object
|
Class label; anything not listed is |
required |
hgv_classes
|
Sequence[str]
|
Lower-case labels of heavy goods vehicles and buses. |
HGV_CLASSES
|
motorcycle_classes
|
Sequence[str]
|
Lower-case labels of motorcycles. |
MOTORCYCLE_CLASSES
|
Returns:
| Type | Description |
|---|---|
str
|
The group. |
in_lane_overtakings
in_lane_overtakings(df: DataFrame, lane_col: str = C.LANE_FIXED, min_persistence_sec: float = 0.5, deadband_m: float = 1.0, exclude_classes: Sequence[str] = MOTORCYCLE_CLASSES, hgv_classes: Sequence[str] = HGV_CLASSES, id_col: str = C.ID, time_col: str = C.TIME, lon_col: str = C.POS_LON, class_col: str = C.CLASS) -> dict[str, Any]
Find vehicle pairs that swap their longitudinal order while both stay in the same lane.
Two vehicles in one lane cannot pass each other without one of them leaving the lane, so on motorways (motorcycles aside) every such in-lane overtaking points to a lane-assignment error or a position bias (e.g. the perspective offset of tall vehicles). The measure needs no ground truth.
Only clean rows count: a valid lane label, not flagged
is_changing_lane or is_lateral_excursion (if the columns exist)
and not of an excluded class. For a pair, the maximal common intervals
in which both are clean in the same lane at consecutive time steps are
considered. Inside an interval the order of the two is the sign of
pos_lon_i - pos_lon_j where the difference lies outside the band
+-deadband_m (and undefined inside it; a real overtaking in one lane
has to pass through the band, two vehicles cannot stand side by side in
one lane). Runs of a defined order shorter than min_persistence_sec
are ignored, and every change of order between two remaining runs is one
overtaking. Band and persistence keep position noise of near-equal
vehicles from counting.
Candidate pairs are found efficiently: per lane and time step, the clean
vehicles that stay clean in the same lane at the next step are sorted by
pos_lon; only where their order at the next step is no longer sorted
are the pairs examined in detail.
The vehicles must share a common time grid (e.g. the pipeline output).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Trajectories ( |
required |
lane_col
|
str
|
Lane label column. |
LANE_FIXED
|
min_persistence_sec
|
float
|
Minimum duration of the reversed order (and of the order before it) [s]. |
0.5
|
deadband_m
|
float
|
Hysteresis band around equal positions [m]. |
1.0
|
exclude_classes
|
Sequence[str]
|
Class labels (case-insensitive) left out. |
MOTORCYCLE_CLASSES
|
hgv_classes
|
Sequence[str]
|
Class labels counted as HGV for the class pairs. |
HGV_CLASSES
|
id_col
|
str
|
Vehicle ID column. |
ID
|
time_col
|
str
|
Time column. |
TIME
|
lon_col
|
str
|
Longitudinal position column [m]. |
POS_LON
|
class_col
|
str
|
Class column. |
CLASS
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
|
dict[str, Any]
|
of the two [m]), |
dict[str, Any]
|
|
dict[str, Any]
|
new order lasts within the interval [s]); |
dict[str, Any]
|
|
dict[str, Any]
|
( |
order_swaps
order_swaps(df: DataFrame, lat_col: str = C.POS_LAT, max_lateral_m: float = 6.0, deadband_m: float = 1.0, min_persistence_sec: float = 0.5, neighbours: int = 12, exclude_classes: Sequence[str] = MOTORCYCLE_CLASSES, hgv_classes: Sequence[str] = HGV_CLASSES, id_col: str = C.ID, time_col: str = C.TIME, lon_col: str = C.POS_LON, class_col: str = C.CLASS) -> pd.DataFrame
Find every change of the longitudinal order of two vehicles, without lane labels (ANT 2027).
The order of a pair is the sign of pos_lon_i - pos_lon_j outside the band +-deadband_m;
runs of one order shorter than min_persistence_sec are ignored (as in in_lane_overtakings,
but over the whole common lifetime of the pair, whatever its labels). A swap episode runs from
the last sample of the old order to the first sample of the new one (the passage through the
band). Candidate pairs: vehicles at most neighbours places apart in the order along the road
at one time step whose order differs at the next, and at most max_lateral_m apart laterally
there.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Trajectories ( |
required |
lat_col
|
str
|
Lateral position column [m]. |
POS_LAT
|
max_lateral_m
|
float
|
Maximum lateral distance of a candidate pair [m]. |
6.0
|
deadband_m
|
float
|
Hysteresis band around equal positions [m]. |
1.0
|
min_persistence_sec
|
float
|
Minimum duration of an order [s]. |
0.5
|
neighbours
|
int
|
Maximum distance of a candidate pair in the order along the road (places). |
12
|
exclude_classes
|
Sequence[str]
|
Class labels (case-insensitive) left out. |
MOTORCYCLE_CLASSES
|
hgv_classes
|
Sequence[str]
|
Class labels counted as HGV for the class pairs. |
HGV_CLASSES
|
id_col
|
str
|
Vehicle ID column. |
ID
|
time_col
|
str
|
Time column. |
TIME
|
lon_col
|
str
|
Longitudinal position column [m]. |
POS_LON
|
class_col
|
str
|
Class column. |
CLASS
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per swap: |
DataFrame
|
(episode), |
DataFrame
|
(|d_i - d_j| at the crossing [m]), |
DataFrame
|
|
robust_in_lane_overtakings
robust_in_lane_overtakings(swaps: DataFrame, df: TrackFrame, lane_col: str = C.LANE_FIXED, lane_changes: EventFrame | None = None, offset_s: float = 2.0, id_col: str = C.ID, time_col: str = C.TIME) -> pd.DataFrame
Classify order swaps as label-robust in-lane overtakings (ANT 2027).
A swap of order_swaps counts if both vehicles carry the same valid lane label offset_s
before the start and offset_s after the end of the swap episode, the same lane at both times,
whatever their labels during the episode (a conflict re-assignment during the overlap does not
hide it). A lane change of either vehicle (lane_changes: id, time_start,
time_end) overlapping that window exempts the pair. Swaps for which a label is missing (a
vehicle not observed at one of the two times) are undetermined.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
swaps
|
DataFrame
|
Result of |
required |
df
|
TrackFrame
|
Trajectories ( |
required |
lane_col
|
str
|
Lane label column. |
LANE_FIXED
|
lane_changes
|
EventFrame | None
|
Lane-change events ( |
None
|
offset_s
|
float
|
Distance of the label checks before and after the episode [s]. |
2.0
|
id_col
|
str
|
Vehicle ID column. |
ID
|
time_col
|
str
|
Time column. |
TIME
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
|
DataFrame
|
|
compute_leaders
compute_leaders(df: TrackFrame, lane_col: str = C.LANE_FIXED) -> pd.DataFrame
Return the leader of every sample, recomputed from the lane labels lane_col.
The leader is the nearest vehicle ahead in the same lane at the same time (compute_surroundings).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
TrackFrame
|
Trajectories on a common time grid ( |
required |
lane_col
|
str
|
Lane label column. |
LANE_FIXED
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
A frame (not one of the documented schemas) with |
DataFrame
|
by |
detect_leader_changes
detect_leader_changes(df: TrackFrame, lane_changes: DataFrame, lane_col: str = C.LANE_FIXED, *, leaders: DataFrame | None = None, label_changes: DataFrame | None = None, window_s: float = 2.0) -> pd.DataFrame
Find the leader changes and why each is explained, as in ANT 2027, with a split for fragmented data.
A leader change is a change of the leader of a vehicle (compute_leaders on lane_col) from one vehicle to
another or to none. Definition of the ANT 2027 paper: a change is explained if, within window_s of it, a
detected lane change (lane_changes) of the vehicle itself (ego), of the old leader (old, cut-out)
or of the new leader (new, cut-in) overlaps, or the old leader's track ends (exit, it leaves the
section); otherwise it is unexplained. Re-assignments of the lane labels without a detected lane change do
not explain anything.
On fragmented data (camera hand-overs, short provider fragments) most track ends and starts are fragment
boundaries, not vehicles leaving or entering. split therefore separates: lane_change (ego, old, new),
old_leader_end (the old leader's track ends within window_s, ANT exit), new_leader_start (else,
the new leader's track begins within window_s before the change; unexplained by the ANT definition) and
unexplained (the rest). The ANT count of unexplained changes is new_leader_start + unexplained.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
TrackFrame
|
Trajectories on a common time grid ( |
required |
lane_changes
|
DataFrame
|
The detected lane changes that explain a change: |
required |
lane_col
|
str
|
Lane label column. |
LANE_FIXED
|
leaders
|
DataFrame | None
|
Result of |
None
|
label_changes
|
DataFrame | None
|
Label transitions of |
None
|
window_s
|
float
|
Half width of the explanation window [s]. |
2.0
|
Returns:
| Name | Type | Description |
|---|---|---|
DataFrame
|
One row per leader change: |
|
NaN |
DataFrame
|
none), |
DataFrame
|
(ANT definition), |
|
DataFrame
|
|
leader_change_counts
leader_change_counts(changes: DataFrame) -> dict[str, int]
Count the leader changes of detect_leader_changes by the ANT definition and by split.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
changes
|
DataFrame
|
Result of |
required |
Returns:
| Type | Description |
|---|---|
dict[str, int]
|
|
dict[str, int]
|
count per split: |
Noise of the smoothed lateral speed of lane keepers, the lower bound for the lane-change detector threshold.
The lane-change detector (docs/pipeline/07_lane_change_detection.md) opens an interval where the smoothed
lateral speed exceeds lane_change.lat_speed_threshold_mps. A vehicle that keeps its lane has no lateral speed
except measurement noise and small corrections within the lane. If the threshold lies below this noise, the
detector opens intervals on lane keepers too, and the intervals of real lane changes start early and end late.
compute_lateral_speed_noise measures the noise where it is free of manoeuvres: on the lane keepers, the
vehicles whose lane label does not change over their whole trajectory. The lateral speed is smoothed exactly as the
detector smooths it (trajlab.processing.lane_changes.smooth_lateral_speed with the settings of the
lane_change section). The 95th percentile of its absolute value, rounded to 0.05 m/s, is the rule of the
ngsim preset for the threshold (docs/adapting_configuration.md).
LateralSpeedNoise
dataclass
LateralSpeedNoise(quantile: float, speed_mps: float, share_above_threshold: float, threshold_mps: float, n_lane_keepers: int, n_vehicles: int, n_samples: int)
Distribution of the smoothed lateral speed of the lane keepers.
Attributes:
| Name | Type | Description |
|---|---|---|
quantile |
float
|
Quantile level that was measured [-], 0 … 1. |
speed_mps |
float
|
That quantile of the absolute smoothed lateral speed [m/s]. |
share_above_threshold |
float
|
Share of the lane-keeper samples whose absolute smoothed lateral speed exceeds the
configured |
threshold_mps |
float
|
The configured detector threshold the share refers to [m/s]. |
n_lane_keepers |
int
|
Vehicles without a label change that have a lateral speed. |
n_vehicles |
int
|
Vehicles in the input. |
n_samples |
int
|
Lane-keeper samples with a lateral speed. |
compute_lateral_speed_noise
compute_lateral_speed_noise(tracks: TrackFrame, config: LaneChangeConfig | None = None, *, lane_col: str = C.LANE_FIXED, quantile: float = 0.95) -> LateralSpeedNoise
Measure the smoothed lateral speed of the vehicles that keep their lane.
A lane keeper is a vehicle without any transition of lane_col (label_transitions: unassigned samples,
lane -1, are skipped). Its lateral speed is pos_lat differentiated and smoothed per vehicle as the detector
does it, with the filter widths of config.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tracks
|
TrackFrame
|
Trajectories ( |
required |
config
|
LaneChangeConfig | None
|
Detector settings: filter widths and the threshold the share refers to. Defaults to
|
None
|
lane_col
|
str
|
Lane label that defines the lane keepers. |
LANE_FIXED
|
quantile
|
float
|
Quantile level of the absolute lateral speed [-], 0 … 1. |
0.95
|
Returns:
| Type | Description |
|---|---|
LateralSpeedNoise
|
The quantile, the share of samples above the threshold and the counts; |
LateralSpeedNoise
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Noise estimation and kinematic consistency of reconstructed trajectories.
All functions work on one vehicle sampled on a regular grid (t in s, positions in m). They estimate the
measurement error the later analyses see, after Punzo et al. (2011) and Montanino & Punzo (2015):
position_residual: positions minus a local cubic (Savitzky-Golay) trend overtrend_s. Its standard deviation estimates the noise above the trend's pass band; its lag-1 autocorrelation tells white from coloured noise.noise_model: standard deviation, AR(1) correlation time, outlier share (robust z above 5) and kurtosis of a residual.kindiswhite(lag-1 autocorrelation below 0.3),colouredorjumps(outlier share above 0.5 %).band_power: power of a signal (e.g. the acceleration) in frequency bands (Welch).standstill_noise: scatter of the positions while the vehicle stands (speed belowv_max), the cleanest measurement-noise estimate where standstill exists.kinematic_consistency: position against integrated speed and speed against integrated acceleration over short windows (drift afterwindow_s), i.e. whether x, v and a belong to one motion.length_stats: constancy of the vehicle length along a track, and jumps of the reference point (steps of the position residual abovejump_m).
position_residual
position_residual(t: ArrayLike, x: ArrayLike, trend_s: float = 4.0, trim: bool = True) -> FloatArray
Subtract the local cubic (Savitzky-Golay) trend from a position series.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
t
|
ArrayLike
|
Sample times [s], regular grid. |
required |
x
|
ArrayLike
|
Positions [m]. |
required |
trend_s
|
float
|
Length of the trend window [s]. |
4.0
|
trim
|
bool
|
Cut half a window at both ends (edge effects). |
True
|
Returns:
| Type | Description |
|---|---|
FloatArray
|
The residual [m]; empty for fewer than 3 samples or a track shorter than two windows. |
noise_model
noise_model(residual: ArrayLike, dt: float) -> dict[str, float | str | None]
Characterise a residual series as a noise model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
residual
|
ArrayLike
|
Residual series, e.g. from |
required |
dt
|
float
|
Sampling interval [s]. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, float | str | None]
|
|
dict[str, float | str | None]
|
|
dict[str, float | str | None]
|
(excess [-]) and |
dict[str, float | str | None]
|
|
band_power
band_power(t: ArrayLike, s: ArrayLike, bands: Sequence[tuple[float, float]] = BANDS) -> dict[str, float]
Integrate the Welch power density of a signal (mean removed) over frequency bands.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
t
|
ArrayLike
|
Sample times [s], regular grid. |
required |
s
|
ArrayLike
|
The signal, e.g. the acceleration [m/s^2]. |
required |
bands
|
Sequence[tuple[float, float]]
|
Lower and upper band limits [Hz]. |
BANDS
|
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
|
dict[str, float]
|
than 64 samples or a band with fewer than two frequencies. |
standstill_noise
standstill_noise(t: ArrayLike, x: ArrayLike, y: ArrayLike, v: ArrayLike, v_max: float = 0.3, min_s: float = 3.0) -> dict[str, float]
Measure the position scatter while the vehicle stands.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
t
|
ArrayLike
|
Sample times [s]. |
required |
x
|
ArrayLike
|
Longitudinal positions [m]. |
required |
y
|
ArrayLike
|
Lateral positions [m]. |
required |
v
|
ArrayLike
|
Speeds [m/s]. |
required |
v_max
|
float
|
Speed below which the vehicle stands [m/s]. |
0.3
|
min_s
|
float
|
Minimum duration of a standstill phase [s]. |
3.0
|
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
|
dict[str, float]
|
phase), and |
kinematic_consistency
kinematic_consistency(t: ArrayLike, x: ArrayLike, v: ArrayLike, a: ArrayLike, window_s: float = 5.0) -> dict[str, float]
Check whether position, speed and acceleration belong to one motion.
Over non-overlapping windows, the change of the position is compared with the integrated speed and the change of the speed with the integrated acceleration (trapezoidal rule).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
t
|
ArrayLike
|
Sample times [s]. |
required |
x
|
ArrayLike
|
Positions [m]. |
required |
v
|
ArrayLike
|
Speeds along |
required |
a
|
ArrayLike
|
Accelerations [m/s^2]. |
required |
window_s
|
float
|
Window length [s]. |
5.0
|
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
|
length_stats
length_stats(length: ArrayLike, residual: ArrayLike | None = None, jump_m: float = 0.5) -> dict[str, float]
Measure the constancy of the vehicle length and the jumps of the reference point along a track.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
length
|
ArrayLike
|
Vehicle lengths per sample [m]; non-finite values are dropped. |
required |
residual
|
ArrayLike | None
|
Position residual ( |
None
|
jump_m
|
float
|
Sample-to-sample step of the residual that counts as a jump [m]. |
0.5
|
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
|
Physically impossible states between vehicles of one lane.
On an analysis frame (vid, tk, lane, x, length; one direction, x along travel):
overlaps: per frame and lane, consecutive vehicles whose bounding boxes overlap (net gap below-tol_m);same_lane_overtakes: order swaps of two vehicles that stay on the same lane in consecutive frames (a vehicle passes another without leaving the lane).
overlaps
overlaps(traj: DataFrame, tol_m: float = 0.0) -> pd.DataFrame
Find consecutive same-lane vehicles whose bounding boxes overlap.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
traj
|
DataFrame
|
Analysis frame ( |
required |
tol_m
|
float
|
Overlap tolerated [m]. |
0.0
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per overlapping pair: |
DataFrame
|
below |
same_lane_overtakes
same_lane_overtakes(traj: DataFrame) -> pd.DataFrame
Find order swaps of two vehicles that stay on the same lane between consecutive steps.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
traj
|
DataFrame
|
Analysis frame ( |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per swap with |
DataFrame
|
at |
Synthetic recovery test for longitudinal reconstruction methods (selection rule fixed before the evaluation).
- Noise model per dataset (
fit_noise_model): white noisesigma_whiteplus one coloured component on the 10-Hz positions, either first-order autoregressive (time constanttau) or band-limited (white noise through a second-order Butterworth low-pass atfc; provider-smoothed positions have smooth, low-frequency errors). The parameters are fitted to the dataset's position residuals around cubic trends of 1, 2 and 4 s (residual_moments) in excess of an accepted dataset at the same speed (real motion): for independent components the squared residual SD at trend length W issigma_white^2 r_w(W)^2 + sigma_col^2 r_col(W)^2with response factorsrfrom simulated unit noise (response_factors); non-negative least squares per family member, the best member wins. Optional outliers are added from the measured outlier share. - Synthetic followers (
synthetic_tracks): 40 s at 5-35 m/s with mild natural acceleration (Ornstein-Uhlenbeck, SD 0.1 m/s^2, 3 s) and, on event tracks, one braking event: a step (jerk-limited to 0.3 s) or a ramp to -0.5 ... -4 m/s^2, held 1-5 s; quiet tracks have no event. - Measures per method (
run_recovery) on the noisy 10-Hz positions: - error of the strongest braking (reconstructed minus true minimum within the event window);
- error of the braking onset (first instant below half the event's deceleration);
- false braking: share of 5-s windows of quiet tracks whose reconstructed minimum is below -1 m/s^2;
- jerk: p95 |jerk| of the reconstruction over p95 |jerk| of the truth on quiet tracks.
select_method: the pre-registered rule (admissible if false braking <= max(Montanino & Punzo, 2 %); smallest median |error of the strongest braking|; ties below 0.05 m/s^2 go to the simpler method in the given order).
residual_sd
residual_sd(x: FloatArray, window_s: float, dt: float = DT) -> float
Return the standard deviation of a position series around its cubic Savitzky-Golay trend.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
FloatArray
|
Positions [m] on a regular grid. |
required |
window_s
|
float
|
Trend length [s]. |
required |
dt
|
float
|
Sampling interval [s]. |
DT
|
Returns:
| Type | Description |
|---|---|
float
|
The standard deviation [m], half a window trimmed at both ends; NaN for a series shorter than two windows. |
residual_moments
residual_moments(tracks: Sequence[FloatArray], windows: Sequence[float] = WINDOWS_S, dt: float = DT) -> dict[float, float]
Return the median residual standard deviation over tracks per trend length.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tracks
|
Sequence[FloatArray]
|
10-Hz position arrays [m]. |
required |
windows
|
Sequence[float]
|
Trend lengths [s]. |
WINDOWS_S
|
dt
|
float
|
Sampling interval [s]. |
DT
|
Returns:
| Type | Description |
|---|---|
dict[float, float]
|
Trend length [s] -> median of |
lowpass_noise
lowpass_noise(n: int, sigma: float, fc: float, rng: Generator) -> FloatArray
Draw band-limited Gaussian noise.
White noise through a zero-phase second-order Butterworth low-pass on 10-Hz samples, scaled to the given standard deviation; unlike AR(1) noise it is smooth at short time scales.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of samples. |
required |
sigma
|
float
|
Standard deviation [m]. |
required |
fc
|
float
|
Cut-off frequency [Hz]. |
required |
rng
|
Generator
|
Random generator. |
required |
Returns:
| Type | Description |
|---|---|
FloatArray
|
The |
noise_component
noise_component(kind: str, par: float, n: int, rng: Generator) -> FloatArray
Draw unit-variance noise of one family member.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kind
|
str
|
|
required |
par
|
float
|
Time constant [s] for |
required |
n
|
int
|
Number of samples. |
required |
rng
|
Generator
|
Random generator. |
required |
Returns:
| Type | Description |
|---|---|
FloatArray
|
The |
Raises:
| Type | Description |
|---|---|
ValueError
|
For any other |
response_factors
response_factors(windows: Sequence[float] = WINDOWS_S, n: int = 400, reps: int = 200, seed: int = 0) -> dict[tuple[str, float], dict[float, float]]
Simulate the residual standard deviation of unit-variance noise for every family member.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
windows
|
Sequence[float]
|
Trend lengths [s]. |
WINDOWS_S
|
n
|
int
|
Samples per simulated series. |
400
|
reps
|
int
|
Series per member and trend length (the median is taken). |
200
|
seed
|
int
|
Random seed. |
0
|
Returns:
| Type | Description |
|---|---|
dict[tuple[str, float], dict[float, float]]
|
|
dict[tuple[str, float], dict[float, float]]
|
trend length |
fit_noise_model
fit_noise_model(moments: Mapping[float, float], factors: Mapping[tuple[str, float], Mapping[float, float]] | None = None, reference: Mapping[float, float] | None = None) -> dict[str, Any]
Fit white noise plus one coloured member (AR(1) or band-limited) to residual moments.
Non-negative least squares on the squared moments per coloured member; the member with the smallest relative error of the fitted moments wins.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
moments
|
Mapping[float, float]
|
Trend length [s] -> residual standard deviation [m] ( |
required |
factors
|
Mapping[tuple[str, float], Mapping[float, float]] | None
|
Response factors ( |
None
|
reference
|
Mapping[float, float] | None
|
Moments of an accepted dataset in the same speed band, which contain real motion; the fit then
uses the excess |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
|
dict[str, Any]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
add_noise
add_noise(x: FloatArray, model: Mapping[str, Any], rng: Generator) -> FloatArray
Add noise of a fitted model to positions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
FloatArray
|
True positions [m] on the 10-Hz grid. |
required |
model
|
Mapping[str, Any]
|
Noise model as from |
required |
rng
|
Generator
|
Random generator. |
required |
Returns:
| Type | Description |
|---|---|
FloatArray
|
The noisy positions [m]. |
synthetic_tracks
synthetic_tracks(n_event: int, n_quiet: int, rng: Generator, duration_s: float = 40.0) -> list[dict[str, Any]]
Generate synthetic follower tracks (see the module description).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_event
|
int
|
Number of tracks with a braking event (first in the list). |
required |
n_quiet
|
int
|
Number of tracks without an event. |
required |
rng
|
Generator
|
Random generator. |
required |
duration_s
|
float
|
Track duration [s]. |
40.0
|
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
One dict per track with |
list[dict[str, Any]]
|
|
run_recovery
run_recovery(methods: Mapping[str, tuple[Literal['mp', 'rts', 'tv'], Mapping[str, Any]]], model: Mapping[str, Any], n_event: int = 400, n_quiet: int = 200, seed: int = 0) -> pd.DataFrame
Run every reconstruction method on the same noisy synthetic tracks.
Every method sees the same truth and the same noise.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
methods
|
Mapping[str, tuple[Literal['mp', 'rts', 'tv'], Mapping[str, Any]]]
|
Name -> |
required |
model
|
Mapping[str, Any]
|
Noise model ( |
required |
n_event
|
int
|
Number of event tracks. |
400
|
n_quiet
|
int
|
Number of quiet tracks. |
200
|
seed
|
int
|
Random seed. |
0
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per method and track with |
summarise
summarise(R: DataFrame) -> pd.DataFrame
Summarise the recovery results per method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
R
|
DataFrame
|
Result of |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
Indexed by method: |
DataFrame
|
strongest braking [m/s^2]), |
DataFrame
|
|
select_method
select_method(summary: DataFrame, order: Sequence[str], baseline: str = 'mp', tie: float = 0.05, floor: float = 0.02) -> tuple[str, str]
Choose a method by the pre-registered rule (see the module description).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
summary
|
DataFrame
|
Result of |
required |
order
|
Sequence[str]
|
Methods from simplest to most complex (tie break). |
required |
baseline
|
str
|
Reference method whose false-braking share sets the admissibility limit. |
'mp'
|
tie
|
float
|
|Error| difference below which methods tie [m/s^2]. |
0.05
|
floor
|
float
|
Minimum admissible false-braking share [-], 0 … 1. |
0.02
|
Returns:
| Type | Description |
|---|---|
tuple[str, str]
|
The chosen method and the reason as text. |
Reference bands and acceptance tests for reconstruction quality (fixed before the evaluation).
- The reference is pooled from accepted datasets (highD and exiD) per speed band
SPEED_BANDS; a band with fewer thanmin_nreference values is merged with its neighbour (band_edges). exceedance_test: share of candidate values above the reference band's p95. A dataset matching the reference has 5 % by construction; it passes if the share is at mostlimit(10 %) plus the one-sided 95 % sampling margin 1.645 sqrt(limit (1 - limit) / n).ratio_test: candidate median againstfactortimes the reference median (position residual).envelope_test: a statistic of the candidate (median strongest braking, share below -1 m/s^2 in steady following) lies within the range spanned by the reference datasets, widened by a tolerance. Used where the accepted datasets themselves differ (highD brakes more in steady following than exiD), so that matching either one passes.
band_labels
band_labels(edges: Sequence[float]) -> list[str]
Label speed bands by their edges.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edges
|
Sequence[float]
|
Band edges [m/s], increasing; the last may be |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
One label per band, e.g. |
band_edges
band_edges(ref_speed: ArrayLike, edges: Sequence[float] = SPEED_BANDS, min_n: int = 50) -> tuple[tuple[float, ...], list[str]]
Merge every speed band with too few reference values into its neighbour.
A band is merged with the next faster band; the fastest band with the slower one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ref_speed
|
ArrayLike
|
Speeds of the reference values [m/s]. |
required |
edges
|
Sequence[float]
|
Initial band edges [m/s]. |
SPEED_BANDS
|
min_n
|
int
|
Minimum number of reference values per band. |
50
|
Returns:
| Type | Description |
|---|---|
tuple[float, ...]
|
The remaining edges [m/s] and the labels of the bands that were merged away (labels at the time of |
list[str]
|
merging). |
assign_band
assign_band(v: ArrayLike, edges: Sequence[float]) -> npt.NDArray[np.object_]
Assign every speed to its speed band.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
ArrayLike
|
Speeds [m/s]. |
required |
edges
|
Sequence[float]
|
Band edges [m/s] (e.g. from |
required |
Returns:
| Type | Description |
|---|---|
NDArray[object_]
|
The band label ( |
exceedance_test
exceedance_test(values: ArrayLike, ref_values: ArrayLike, limit: float = 0.1, q: float = 0.95) -> dict[str, Any]
Test the share of candidate values above a reference quantile.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
ArrayLike
|
Candidate values; non-finite values are dropped. |
required |
ref_values
|
ArrayLike
|
Reference values; non-finite values are dropped. |
required |
limit
|
float
|
Admissible share above the quantile [-], 0 … 1. |
0.1
|
q
|
float
|
Reference quantile [-], 0 … 1. |
0.95
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
|
dict[str, Any]
|
( |
ratio_test
ratio_test(values: ArrayLike, ref_values: ArrayLike, factor: float = 1.5) -> dict[str, Any]
Test the candidate median against a multiple of the reference median.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
ArrayLike
|
Candidate values; non-finite values are dropped. |
required |
ref_values
|
ArrayLike
|
Reference values; non-finite values are dropped. |
required |
factor
|
float
|
Admissible ratio of the medians [-]. |
1.5
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
|
dict[str, Any]
|
values). |
envelope_test
envelope_test(value: float, ref_values: Mapping[str, float], tol: float) -> dict[str, Any]
Test whether a candidate statistic lies within the range spanned by the reference datasets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
float
|
The candidate's statistic. |
required |
ref_values
|
Mapping[str, float]
|
Reference dataset name -> its statistic; non-finite values are ignored. |
required |
tol
|
float
|
Widening of the range on both sides, in the unit of the statistic (e.g. [m/s^2] for the median strongest braking, [-] for a share). |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
|
dict[str, Any]
|
finite value). |
steady_statistics
steady_statistics(windows: DataFrame) -> dict[str, float]
Summarise steady-following windows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
windows
|
DataFrame
|
Result of |
required |
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
|
dict[str, float]
|
-1 m/s^2 [-], 0 … 1) and |
Battery of synthetic scenarios with known lanes for evaluating lane assignment (ANT 2027).
Every scenario is a straight 3-lane road (io.synthetic) with light
background traffic in all lanes plus actors that do the manoeuvre under
test. All vehicles of a scenario drive at the same speed and the actors sit
between the background vehicles, so no two vehicles ever overlap in the
same true lane and the true labels contain no in-lane overtaking. Six
families cover the situations a lane-assignment method has to handle:
================= =========================================================
lane_changes complete lane changes of 3, 5 and 8 s, left and right
slow_drift lane changes stretched over 60, 90 and 120 s (drifts)
excursions lateral excursions of 1.0, 1.5 and 2.0 m without a change
aborted lane changes aborted before / just after the boundary
merge merges from an auxiliary lane (lane 0) into lane 1
dense dense traffic, vehicles side by side, plus lane changes
================= =========================================================
Each family is generated for every position-noise level (default 0, 0.05,
0.15 m) and sampling rate (default 10, 25, 30 Hz) with fixed seeds, run
through the pipeline with each method under test and scored with
lane_metrics against the true (intended) lane. run_battery returns
one row per (family, noise, rate, method) and can write a CSV.
family_lane_changes
family_lane_changes(fps: float, noise: float, seed: int) -> tuple[Scenario, dict[str, Any]]
Build complete lane changes of 3, 5 and 8 s, left and right.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fps
|
float
|
Sampling rate [Hz]. |
required |
noise
|
float
|
Position-noise standard deviation [m]. |
required |
seed
|
int
|
Random seed. |
required |
Returns:
| Type | Description |
|---|---|
tuple[Scenario, dict[str, Any]]
|
The scenario and its configuration overrides (none). |
family_slow_drift
family_slow_drift(fps: float, noise: float, seed: int) -> tuple[Scenario, dict[str, Any]]
Build lane changes stretched over 60, 90 and 120 s (slow drifts).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fps
|
float
|
Sampling rate [Hz]. |
required |
noise
|
float
|
Position-noise standard deviation [m]. |
required |
seed
|
int
|
Random seed. |
required |
Returns:
| Type | Description |
|---|---|
tuple[Scenario, dict[str, Any]]
|
The scenario and its configuration overrides (none). |
family_excursions
family_excursions(fps: float, noise: float, seed: int) -> tuple[Scenario, dict[str, Any]]
Build lateral excursions of 1.0, 1.5 and 2.0 m without a lane change.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fps
|
float
|
Sampling rate [Hz]. |
required |
noise
|
float
|
Position-noise standard deviation [m]. |
required |
seed
|
int
|
Random seed. |
required |
Returns:
| Type | Description |
|---|---|
tuple[Scenario, dict[str, Any]]
|
The scenario and its configuration overrides (none). |
family_aborted
family_aborted(fps: float, noise: float, seed: int) -> tuple[Scenario, dict[str, Any]]
Build lane changes that turn back: peak 1.5 m (before the boundary at 1.875 m) and 2.2 m (after it).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fps
|
float
|
Sampling rate [Hz]. |
required |
noise
|
float
|
Position-noise standard deviation [m]. |
required |
seed
|
int
|
Random seed. |
required |
Returns:
| Type | Description |
|---|---|
tuple[Scenario, dict[str, Any]]
|
The scenario and its configuration overrides (none). |
family_merge
family_merge(fps: float, noise: float, seed: int) -> tuple[Scenario, dict[str, Any]]
Build merges from an auxiliary lane (lane 0) into lane 1.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fps
|
float
|
Sampling rate [Hz]. |
required |
noise
|
float
|
Position-noise standard deviation [m]. |
required |
seed
|
int
|
Random seed. |
required |
Returns:
| Type | Description |
|---|---|
Scenario
|
The scenario and its configuration overrides, which set the auxiliary-lane zone |
dict[str, Any]
|
( |
family_dense
family_dense(fps: float, noise: float, seed: int) -> tuple[Scenario, dict[str, Any]]
Build dense traffic: all three lanes with one vehicle per 30 m, side by side in rows, and two lane changes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fps
|
float
|
Sampling rate [Hz]. |
required |
noise
|
float
|
Position-noise standard deviation [m]. |
required |
seed
|
int
|
Random seed. |
required |
Returns:
| Type | Description |
|---|---|
tuple[Scenario, dict[str, Any]]
|
The scenario and its configuration overrides (none). |
truth_labels
truth_labels(out: TrackFrame, scenario: Scenario) -> pd.DataFrame
Return the true (intended) lane for every row of a pipeline output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
out
|
TrackFrame
|
Pipeline output of a battery scenario ( |
required |
scenario
|
Scenario
|
The scenario. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
A frame (not one of the documented schemas) with |
DataFrame
|
in the scenario), row-aligned with |
run_battery
run_battery(methods: Mapping[str, Mapping[str, Any]], families: Mapping[str, Callable[[float, float, int], tuple[Scenario, dict[str, Any]]]] | None = None, noise_levels: Sequence[float] = NOISE_LEVELS, rates_hz: Sequence[float] = RATES_HZ, seed: int = 0, out_csv: PathLike | None = None, progress: Callable[[str], None] | None = None) -> pd.DataFrame
Run every method on every scenario of the battery and score it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
methods
|
Mapping[str, Mapping[str, Any]]
|
|
required |
families
|
Mapping[str, Callable[[float, float, int], tuple[Scenario, dict[str, Any]]]] | None
|
|
None
|
noise_levels
|
Sequence[float]
|
Position-noise standard deviations [m]. |
NOISE_LEVELS
|
rates_hz
|
Sequence[float]
|
Sampling rates [Hz]. |
RATES_HZ
|
seed
|
int
|
Base seed; scenario |
0
|
out_csv
|
PathLike | None
|
Optional path of the CSV to write. |
None
|
progress
|
Callable[[str], None] | None
|
Optional callback receiving one line per run. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per (family, noise_m, rate_hz, method) with |
DataFrame
|
in-lane overtakings ( |
truth_overtakings
truth_overtakings(scenario: Scenario) -> dict[str, Any]
Count the in-lane overtakings of the true lanes (reference rate; zero for well-designed scenarios).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scenario
|
Scenario
|
The scenario. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
The |
Statistics of the merge and car-following analyses.
Modules:
bootstrap: cluster and stratified bootstrap intervals with one seeded generator per statistic.agreement: Lin's concordance correlation coefficient (CCC) of model and observation.tests: exact McNemar test of paired verdicts and the Holm correction.merge_summary: aggregate measures per merge class for field and simulation merge tables.
Agreement of model and observation: Lin's concordance correlation coefficient (CCC).
ccc
ccc(x: Sequence[float], y: Sequence[float]) -> float
Compute Lin's concordance correlation coefficient of two paired samples.
ccc = 2 cov(x, y) / (var(x) + var(y) + (mean(x) - mean(y))^2) with population moments (ddof = 0).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Sequence[float]
|
First sample, e.g. the observed values (any unit, the same as |
required |
y
|
Sequence[float]
|
Second sample, paired with |
required |
Returns:
| Type | Description |
|---|---|
float
|
The CCC in [-1, 1]; 1 means perfect agreement. NaN if both samples are constant and equal. |
Bootstrap confidence intervals with one generator per statistic and key-sorted inputs.
Earlier analysis scripts drew bootstrap samples from module-level generators in the order of the calls and resampled
rows in the order in which parallel jobs had finished, so an interval depended on unrelated earlier calls and on job
timing. Here every statistic gets its own generator (generator(seed, name)) and its input is sorted by a key
before any row is drawn: the same data give the same interval regardless of call order or row order.
Main functions: generator, sort_by_key, cluster_bootstrap (whole clusters, e.g. recording units, are
resampled) and stratified_median_ci (resampling within strata). Intervals are percentile intervals.
generator
generator(seed: int, name: str) -> np.random.Generator
Create the random generator of one named statistic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seed
|
int
|
Base seed of the analysis (e.g. |
required |
name
|
str
|
Name of the statistic; its CRC-32 is the second seed word, so every name gets its own stream. |
required |
Returns:
| Type | Description |
|---|---|
Generator
|
A NumPy generator seeded with |
sort_by_key
sort_by_key(df: DataFrame, key: Sequence[str]) -> pd.DataFrame
Sort the rows by key columns so that the row order no longer depends on job completion.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Input table. |
required |
key
|
Sequence[str]
|
Key columns; columns missing from |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
The sorted table with a fresh |
Raises:
| Type | Description |
|---|---|
KeyError
|
If none of the key columns is in |
cluster_bootstrap
cluster_bootstrap(df: DataFrame, stat: Callable[[DataFrame], float], *, rng: Generator, cluster: str = 'unit', key: Sequence[str] = ('set', 'dataset', 'unit', 'id'), n: int = 1000, level: float = 0.95) -> tuple[float, float, float]
Compute the estimate and percentile interval of a statistic, resampling whole clusters.
The frame is first sorted by key; each replicate draws n_clusters clusters with replacement and evaluates
stat on the concatenated rows. NaN replicates are ignored by the quantiles.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Input table, one row per case. |
required |
stat
|
Callable[[DataFrame], float]
|
Statistic of a table, e.g. a median of a column. |
required |
rng
|
Generator
|
Generator of this statistic ( |
required |
cluster
|
str
|
Column with the cluster label (e.g. |
'unit'
|
key
|
Sequence[str]
|
Columns that define the canonical row order (see |
('set', 'dataset', 'unit', 'id')
|
n
|
int
|
Number of bootstrap replicates. |
1000
|
level
|
float
|
Confidence level of the interval [-], 0 … 1, e.g. 0.95. |
0.95
|
Returns:
| Type | Description |
|---|---|
tuple[float, float, float]
|
|
Raises:
| Type | Description |
|---|---|
KeyError
|
From |
stratified_median_ci
stratified_median_ci(values: Sequence[float], strata: Sequence[object], *, rng: Generator, n: int = 2000, level: float = 0.95) -> tuple[float, float]
Compute the percentile interval of the median, resampling within each stratum.
Each replicate draws, in every stratum, as many values with replacement as the stratum has, and takes the median of the pooled draw.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
Sequence[float]
|
Values (any unit; the interval has the same unit). |
required |
strata
|
Sequence[object]
|
Stratum label per value (e.g. the dataset); compared as strings. |
required |
rng
|
Generator
|
Generator of this statistic ( |
required |
n
|
int
|
Number of bootstrap replicates. |
2000
|
level
|
float
|
Confidence level of the interval [-], 0 … 1, e.g. 0.95. |
0.95
|
Returns:
| Type | Description |
|---|---|
tuple[float, float]
|
|
Paired tests and multiple-testing correction: exact McNemar test and Holm adjustment.
mcnemar_exact
mcnemar_exact(a: Sequence[bool], b: Sequence[bool]) -> tuple[int, int, float]
Run the exact McNemar test of two paired binary verdicts.
The discordant pairs are tested against a binomial distribution with p = 0.5.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
Sequence[bool]
|
Verdicts (bool) of the first method, one per case. |
required |
b
|
Sequence[bool]
|
Verdicts (bool) of the second method for the same cases. |
required |
Returns:
| Type | Description |
|---|---|
int
|
|
int
|
true, and the two-sided exact binomial p value (1.0 without discordant pairs). |
holm
holm(p: Sequence[float]) -> FloatArray
Adjust p values for multiple testing with the Holm step-down method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
p
|
Sequence[float]
|
Unadjusted p values. |
required |
Returns:
| Type | Description |
|---|---|
FloatArray
|
Holm-adjusted p values in the order of |