Skip to content

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).

Interactions between vehicles: neighbours, surroundings, merge measures, merge typology.

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 (events.merge_table.trajectory_frame); used are vid (str), tk (int grid step), lane (int), x [m], v [m/s], length [m] and datum.

required

Returns:

Type Description
DataFrame

Frame indexed by (vid, tk) with id_<pos> (str or None) and clearance_<pos> [m] for the six

DataFrame

positions of compute_surroundings (front, rear, front_left, rear_left, front_right, rear_right; the

DataFrame

surroundings columns of docs/output_format.md).

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 step_surroundings for the subject at one step, or None.

required
subject_lane int

Lane of the subject.

required
target_lane int

Lane on which the neighbour is looked for.

required
side str

"front" for the vehicle ahead, "rear" for the vehicle behind.

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 (TrackFrame columns by default). Not modified.

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 datetime_col, e.g. seconds [s] or an integer step index; only equality of its values is used (no unit needed). It is used as is (not rounded) and kept in the output.

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 default_length_m in the returned copy.

LENGTH
default_length_m float

Vehicle length used when length_col is missing [m].

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 docs/output_format.md), where <pos> is one of the six positions:

DataFrame
  • id_<pos>: vehicle ID of the neighbour (NaN if there is none).
DataFrame
  • headway_<pos>: centre-to-centre longitudinal distance [m].
DataFrame
  • clearance_<pos>: bumper-to-bumper distance, the headway minus half the length of each vehicle [m].
DataFrame
  • rel_speed_<pos>: speed of the neighbour minus that of the subject [km/h] (positive = neighbour faster).

Raises:

Type Description
ValueError

If (id, time) is not unique; also raised by check_pos_lon_increasing if pos_lon does not increase in the direction of travel.

Reconstruction and lane-assignment quality measures on pipeline output.

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_t with phi = exp(-dt / tau) (standard deviation sigma, correlation time tau in seconds, so the result does not depend on the sampling rate).
  • Outlier bursts: at outlier_rate_per_s per second of track, a burst of outlier_burst_s seconds in which the position jumps by outlier_amplitude_m along the direction of travel (random sign).
  • Fragmentation (optional): gaps of gap_length_s at gaps_per_track_hour; the samples inside are removed.
  • Perspective offset (optional): HGVs are displaced laterally by kappa_hgv * (d - d_c), with d the 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 sigma_*, tau_*, outliers, outlier_burst_length_samples (10-Hz samples), outlier_amplitude_m and optionally the gap and perspective entries.

required
perspective bool

Take kappa_hgv from the file (perspective offset); otherwise it stays 0.

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 n noise values; zeros when n is 0 or sigma is not positive.

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 (RawFrame with attrs["coordinates"] == "planar"): id, datum, point geometry (metric CRS) and class (for the perspective offset).

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 d).

None
fragmentation bool

Remove the samples inside gaps.

False
perspective bool

Displace HGVs laterally by kappa_hgv * (d - d_c).

False

Returns:

Type Description
GeoDataFrame

A copy sorted by id and datum with degraded geometry (and utm_x / utm_y if present)

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 (RawFrame), row-aligned with degraded (sorted by id and datum, no fragmentation).

required
degraded GeoDataFrame

The degraded trajectories (degrade).

required

Returns:

Type Description
dict[str, float]

sigma_x and sigma_y: standard deviations of the displacement in x and y [m] (no lag-1 correlation).

Raises:

Type Description
ValueError

If the rows are not aligned, i.e. the lengths or the id / datum values per row differ (e.g. clean not sorted, or samples removed by fragmentation).

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:

  1. observed: positions over the whole window, no gap above max_gap_s, at most max_bridged_share of 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);
  2. no identity switch: no jump of the vehicle length above max_length_jump_m;
  3. no phantom: no other vehicle appears or vanishes within phantom_range_m of the subject, in its lane or the target lane, inside the window and away from the view edges;
  4. 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 most max_abs_acc / max_abs_jerk, at least min_confident_share of the samples with lane_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 SWEEP_S [m].

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 lane_confidence.

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

subject, lead (target-lane leader at the lateral start), lag (target-lane follower) or lag_leader (the lag's own leader before the change).

start tuple[Anchor, float]

Window start: the event time it refers to ("start" = lateral start, "cross" = line crossing) and the offset [s].

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: "merge", "lane_change" or "any".

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 GateThresholds (value, source, reason); None: the shipped trajlab/config/analysis/gate_thresholds.yaml.

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 (EventFrame: time_start, time_cross, lane_before, lane_after).

required

Returns:

Type Description
DataFrame

The selected events with kind ("merge" or "lane_change"), t_start and t_cross.

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 (TrackFrame).

required
view tuple[float, float]

Observed pos_lon range [m].

required
entry_zones Sequence[tuple[float, float]]

(lon_start, lon_end) [m] of on-ramp zones: a start on lane 0 or 1 within ramp_edge_m of the zone start is a ramp entry (a ramp roadway in view before the zone is labelled lane 0 or 1).

()
exit_zones Sequence[tuple[float, float]]

Of off-ramp zones: an end on lane 0 or 1 within ramp_edge_m of the zone end is a ramp exit.

()
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 (view_edge_m, ramp_edge_m); None: the shipped ones.

None

Returns:

Type Description
DataFrame

One row per track and end (end = "first" / "last") with id, datum, pos_lon, lane

DataFrame

and legitimate (at the view edge, at a ramp edge, or at the first or last second of the data).

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 (in_window and off_mainline are used where present).

required
view tuple[float, float]

Observed pos_lon range [m].

required
breaks ndarray | None

Camera breaks, pos_lon [m], or None.

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

pos_lon range of the site [m], or None for the whole view.

None
ends DataFrame | None

track_ends output with the site's ramp edges; None: track_ends without ramp edges.

None
thresholds GateThresholds | None

Thresholds (view_edge_m); None: the shipped ones.

None

Returns:

Type Description
dict[str, float]

vkm (vehicle-km), spawn_per_vkm and vanish_per_vkm; with breaks also vkm_away_from_breaks,

dict[str, float]

spawn_per_vkm_away_from_breaks and vanish_per_vkm_away_from_breaks.

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 (TrackFrame); rows with off_mainline are left out.

required
events DataFrame

detect_gate_events output.

required
analysis str

Key of GATE_ANALYSES.

required
view tuple[float, float]

Observed pos_lon range [m].

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

track_ends output with the ramp edges of the site; None: track_ends without ramp edges.

None

Returns:

Type Description
DataFrame

One row per event: event ("<id>@<lateral start, s>"), kind, t_start, lane_before,

DataFrame

lane_after, per role its status and values (<role>_status, <role>_max_gap_s,

DataFrame

<role>_bridged_share, <role>_lateral_sweep_m, <role>_length_jump_m, <role>_confident_share,

DataFrame

<role>_max_abs_acc, <role>_max_abs_jerk), phantoms, reason ("ok", "censored",

DataFrame

"not_applicable", "scene:phantom" or "<role>:<criterion>") and passes.

Raises:

Type Description
KeyError

If analysis is not a key of GATE_ANALYSES.

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 over window_s — an estimate of the measurement noise (longitudinal and lateral), the lower bound of the scatter later analyses see.
  • jerk_stats: longitudinal jerk (from a) and lateral jerk (third derivative of a smoothed y); 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 id, t [s], x and y [m].

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: id, n (samples), resid_x_m and resid_y_m

DataFrame

(standard deviations of x and y around the fit [m]).

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 id, t [s], y [m] and optionally a [m/s^2].

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: id, n; with a also jerk_lon_p50,

DataFrame

jerk_lon_p95 [m/s^3], share_jerk_lon_implausible and share_acc_implausible

DataFrame

(JERK_LON_MAX, ACC_MAX); when long enough for the window jerk_lat_p50, jerk_lat_p95

DataFrame

[m/s^3] and share_jerk_lat_implausible (JERK_LAT_MAX). Shares are [-], 0 … 1.

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 id, t [s], y [m], the joint flag and optionally a [m/s^2].

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: id, t_joint [s], vlat_jump [m/s] and, with a,

DataFrame

acc_jump [m/s^2].

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 pos_lon and pos_lat [m] (e.g. a RawFrame).

required
layout LaneLayout | LanesConfig

The lane layout of the run: a LaneLayout or the lanes section of the configuration.

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. "mm" of read_i24motion); the table and the warning then give the sections in miles as well.

None

Returns:

Type Description
DataFrame

One row per section with at least min_points positions: lon_start, lon_end [m], mm_start,

DataFrame

mm_end [mi] (with mile_col: the range of the column in the section), n_points,

DataFrame

n_lanes_observed, n_lanes_configured, lane_positions_m (all peaks, pos_lat [m], text) and

DataFrame

excess (n_lanes_observed > n_lanes_configured).

Warns:

Type Description
UserWarning

Once, listing the sections with excess, if there are any.

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 id_col, time_col and est_col (e.g. a TrackFrame).

required
gt DataFrame

True labels with id_col, time_col and gt_col.

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 gt and est.

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 align_labels.

required

Returns:

Type Description
dict[str, Any]

accuracy [-], 0 … 1, accuracy_per_lane (dict true lane -> accuracy), confusion (DataFrame, rows

dict[str, Any]

= true lane, columns = estimated lane, counts), sequence_accuracy (share of vehicles without any wrong

dict[str, Any]

row [-], 0 … 1) and n_rows / n_vehicles.

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 id_col, time_col and lane_col (e.g. a TrackFrame).

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 id, time (timestamp of the first sample in the new

DataFrame

lane), lane_from, lane_to and direction (+1 = to the left, i.e. higher lane index, -1 = to the

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 label_transitions.

required
gt DataFrame

True transitions as returned by label_transitions.

required
tolerance_s float

Maximum time difference [s].

1.0

Returns:

Type Description
dict[str, Any]

tp, fp, fn, precision, recall and f1 ([-], 0 … 1), mae_s (mean absolute time

dict[str, Any]

error of matched pairs [s]) and matched (DataFrame of pairs: id, est_index, gt_index,

dict[str, Any]

dt_s [s]).

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 id_col and lon_col (e.g. a TrackFrame).

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 lon_col range per vehicle [km].

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 label_transitions.

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 (TrackFrame names by default).

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]; default_length_m where missing.

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 df.

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 (TrackFrame) with id, datum, pos_lon [m], the label column and optionally length [m].

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]

transitions, transitions_per_vehicle_km [1/km], flicker (count), flicker_per_vehicle_km

dict[str, float]

[1/km], conflict_rate (share of rows in a space-time conflict [-], 0 … 1) and vehicle_km [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 id_col, time_col and col_a (e.g. a TrackFrame).

required
b DataFrame

Second labelling: frame with id_col, time_col and col_b.

required
col_a str

Label column of a.

LANE_FIXED
col_b str | None

Label column of b; col_a when None.

None
id_col str

Vehicle ID column.

ID
time_col str

Time column.

TIME

Returns:

Type Description
dict[str, Any]

agreement (share of equal rows [-], 0 … 1), n_rows and per_vehicle (Series id -> share of equal

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 (TrackFrame) with id, datum, pos_lon [m] and est_col (and length for conflicts).

required
gt DataFrame | None

Ground truth with id, datum and gt_col; may be the same frame as est.

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 consistency_metrics and, with ground truth, accuracy,

dict[str, float]

sequence_accuracy, n_rows, n_vehicles, lc_true, lc_est, lc_precision,

dict[str, float]

lc_recall, lc_f1, lc_mae_s [s], spurious_per_vehicle_km and accuracy_lane_<lane>.

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 "car" (e.g. car, van, medium vehicle).

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 (TrackFrame) with id, datum, pos_lon [m], lane_col and optionally class, is_changing_lane, is_lateral_excursion.

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]

events: DataFrame with time (first sample after the positions cross), lane, pos_lon (mean

dict[str, Any]

of the two [m]), id_ahead (vehicle that moves ahead), id_behind, class_ahead,

dict[str, Any]

class_behind, class_pair (car-car, car-hgv, hgv-hgv) and duration_s (how long the

dict[str, Any]

new order lasts within the interval [s]); summary: dict with events, vehicle_hours,

dict[str, Any]

vehicle_km, per_vehicle_hour, per_100_vehicle_km and the counts and rates per class pair

dict[str, Any]

(events_car-hgv, per_100_vehicle_km_car-hgv, ...).

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 (TrackFrame) with id, datum, pos_lon [m], the lateral column and optionally class, on a common time grid.

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: id_ahead, id_behind (order after the swap), time_start, time_end

DataFrame

(episode), time (first sample after the raw positions cross), pos_lon [m], lat_dist_cross

DataFrame

(|d_i - d_j| at the crossing [m]), lat_dist_max and lat_dist_min over the episode [m],

DataFrame

class_ahead, class_behind, class_pair.

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 order_swaps.

required
df TrackFrame

Trajectories (TrackFrame) with the ID, time and lane columns.

required
lane_col str

Lane label column.

LANE_FIXED
lane_changes EventFrame | None

Lane-change events (EventFrame; uses id, time_start, time_end), optional.

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

swaps with lane_before, lane_after (common lane or NaN) and status (in_lane,

DataFrame

different_lanes, exempt_lane_change, undetermined).

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 (TrackFrame) with id, datum, pos_lon, speed, length and lane_col.

required
lane_col str

Lane label column.

LANE_FIXED

Returns:

Type Description
DataFrame

A frame (not one of the documented schemas) with id, datum and id_front (NaN: no leader), sorted

DataFrame

by id and datum, with a fresh index.

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 (TrackFrame; id, datum, pos_lon, speed, length, lane_col), cut to the section analysed.

required
lane_changes DataFrame

The detected lane changes that explain a change: id, time_start, time_end (e.g. the lane_change rows of the event table, or label transitions with time_start = time_end).

required
lane_col str

Lane label column.

LANE_FIXED
leaders DataFrame | None

Result of compute_leaders(df, lane_col) if already computed; None computes it.

None
label_changes DataFrame | None

Label transitions of lane_col (id, time; e.g. label_transitions) for the earlier, partly circular definition explained_old, in which any label change explains; None leaves the column out.

None
window_s float

Half width of the explanation window [s].

2.0

Returns:

Name Type Description
DataFrame

One row per leader change: id, datum (first sample with the new leader), id_front (new leader,

NaN DataFrame

none), id_front_before (old leader), reason (one of LEADER_CHANGE_REASONS), explained

DataFrame

(ANT definition), old_leader_ends, new_leader_starts (track boundaries within window_s),

DataFrame

split (one of LEADER_CHANGE_SPLITS) and, with label_changes, explained_old.

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 detect_leader_changes.

required

Returns:

Type Description
dict[str, int]

leader_changes (all), unexplained_ant (ANT definition: new_leader_start + unexplained) and one

dict[str, int]

count per split: lane_change, old_leader_end, new_leader_start, unexplained.

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 lat_speed_threshold_mps [-], 0 … 1.

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 (TrackFrame) with id, datum, pos_lat [m] and lane_col; usually the pipeline output, whose pos_lat is the position the detector saw.

required
config LaneChangeConfig | None

Detector settings: filter widths and the threshold the share refers to. Defaults to LaneChangeConfig().

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; speed_mps and

LateralSpeedNoise

share_above_threshold are NaN if no vehicle keeps its lane.

Raises:

Type Description
ValueError

If quantile is not in [0, 1].

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 over trend_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. kind is white (lag-1 autocorrelation below 0.3), coloured or jumps (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 below v_max), the cleanest measurement-noise estimate where standstill exists.
  • kinematic_consistency: position against integrated speed and speed against integrated acceleration over short windows (drift after window_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 above jump_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 position_residual; non-finite values are dropped.

required
dt float

Sampling interval [s].

required

Returns:

Type Description
dict[str, float | str | None]

sigma (standard deviation, unit of the residual, e.g. [m]), rho1 (lag-1 autocorrelation [-]),

dict[str, float | str | None]

tau_s (AR(1) correlation time [s]), outlier_share (robust z above 5 [-], 0 … 1), kurtosis

dict[str, float | str | None]

(excess [-]) and kind ("white", "coloured" or

dict[str, float | str | None]

"jumps"); NaN and None for fewer than 20 values.

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]

bp_<lo>_<hi> per band, in the squared unit of s (e.g. [m^2/s^4] for an acceleration); NaN for fewer

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]

still_sd_x and still_sd_y: pooled standard deviations within the phases [m] (NaN without a

dict[str, float]

phase), and still_s: their total duration [s].

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 x [m/s].

required
a ArrayLike

Accelerations [m/s^2].

required
window_s float

Window length [s].

5.0

Returns:

Type Description
dict[str, float]

drift_x_m [m] and drift_v_ms [m/s]: median absolute drifts after one window; NaN for short tracks.

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 (position_residual) [m], optional.

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]

length_sd and length_range [m]; with a residual also ref_point_jumps (count).

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 (events.merge_table.trajectory_frame) with vid, tk, lane, x [m] and optionally length [m] (4.5 m when missing); unassigned rows (lane below 0) are ignored.

required
tol_m float

Overlap tolerated [m].

0.0

Returns:

Type Description
DataFrame

One row per overlapping pair: tk, lane, back and front (vehicle IDs) and gap (net gap,

DataFrame

below -tol_m) [m].

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 (events.merge_table.trajectory_frame) with vid, tk, lane and x [m].

required

Returns:

Type Description
DataFrame

One row per swap with tk, lane, a and b: a was behind b at tk - 1 and is ahead

DataFrame

at tk, both on lane in both steps.

Synthetic recovery test for longitudinal reconstruction methods (selection rule fixed before the evaluation).

  1. Noise model per dataset (fit_noise_model): white noise sigma_white plus one coloured component on the 10-Hz positions, either first-order autoregressive (time constant tau) or band-limited (white noise through a second-order Butterworth low-pass at fc; 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 is sigma_white^2 r_w(W)^2 + sigma_col^2 r_col(W)^2 with response factors r from 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.
  2. 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.
  3. Measures per method (run_recovery) on the noisy 10-Hz positions:
  4. error of the strongest braking (reconstructed minus true minimum within the event window);
  5. error of the braking onset (first instant below half the event's deceleration);
  6. false braking: share of 5-s windows of quiet tracks whose reconstructed minimum is below -1 m/s^2;
  7. jerk: p95 |jerk| of the reconstruction over p95 |jerk| of the truth on quiet tracks.
  8. 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 residual_sd [m].

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 n noise values; zeros when sigma is not positive.

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

"white", "ar" (AR(1)) or "lp" (band-limited).

required
par float

Time constant [s] for "ar", cut-off frequency [Hz] for "lp"; ignored for "white".

required
n int

Number of samples.

required
rng Generator

Random generator.

required

Returns:

Type Description
FloatArray

The n noise values.

Raises:

Type Description
ValueError

For any other kind.

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]]

{("white", 0.0): {W: r}, ("ar", tau): {...}, ("lp", fc): {...}} with the response factor r per

dict[tuple[str, float], dict[float, float]]

trend length W [s].

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] (residual_moments).

required
factors Mapping[tuple[str, float], Mapping[float, float]] | None

Response factors (response_factors); simulated for the trend lengths of moments when None.

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 m^2 - m_ref^2 (floored at 0).

None

Returns:

Type Description
dict[str, Any]

sigma_white [m], kind ("ar" or "lp"), par (time constant [s] or cut-off [Hz]),

dict[str, Any]

sigma_col [m] and fit_error (relative [-]).

Raises:

Type Description
ValueError

If factors has no coloured member.

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 fit_noise_model, optionally with outlier_share (per sample) and outlier_m (jump [m], default 0.5).

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 x [m], v [m/s], a [m/s^2] on the 10-Hz grid and event: None or

list[dict[str, Any]]

kind ("step" / "ramp"), a_ev [m/s^2], dur, t_on and rise [s].

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 -> (method, params) for reconstruct_grid.

required
model Mapping[str, Any]

Noise model (fit_noise_model, see add_noise).

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 method, track and the measures of _metrics.

summarise

summarise(R: DataFrame) -> pd.DataFrame

Summarise the recovery results per method.

Parameters:

Name Type Description Default
R DataFrame

Result of run_recovery.

required

Returns:

Type Description
DataFrame

Indexed by method: err_min_abs and err_min_median (median |error| and median error of the

DataFrame

strongest braking [m/s^2]), err_onset_abs (median |onset error| [s]), detected (share),

DataFrame

false_braking (share of quiet 5-s windows) and jerk_ratio (median).

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 summarise.

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 than min_n reference 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 most limit (10 %) plus the one-sided 95 % sampling margin 1.645 sqrt(limit (1 - limit) / n).
  • ratio_test: candidate median against factor times 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 inf.

required

Returns:

Type Description
list[str]

One label per band, e.g. "0-10", ..., ">=30" for an open upper band.

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 band_edges).

required

Returns:

Type Description
NDArray[object_]

The band label (band_labels) per speed; speeds outside the edges go to the outer bands.

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]

n, ref_q (the reference quantile, unit of the values), share [-], bound

dict[str, Any]

(limit + 1.645 SE(limit)) and pass (share <= bound; None without values).

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]

n, median, ref_median, ratio and pass (median <= factor * ref_median; None without

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]

value, low and high (min(ref) - tol and max(ref) + tol) and pass (None without a

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 steady.steady_windows (columns listed there).

required

Returns:

Type Description
dict[str, float]

n, a_min_median (median strongest acceleration [m/s^2]), below_m1 (share of windows below

dict[str, float]

-1 m/s^2 [-], 0 … 1) and jerk_p95 (median p95 |jerk| [m/s^3]).

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]

(lanes.auxiliary_lane_zones, pos_lon [m]).

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 (TrackFrame; uses id, datum).

required
scenario Scenario

The scenario.

required

Returns:

Type Description
DataFrame

A frame (not one of the documented schemas) with id, datum and lane_gt (-1 for vehicles not

DataFrame

in the scenario), row-aligned with out.

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]]

{name: {"config": nested config dict, "label_col": str}}; label_col defaults to lane_fixed. Example: the per-point GMM baseline is {"config": {"lane_change": {"enabled": False}}, "label_col": "lane"}.

required
families Mapping[str, Callable[[float, float, int], tuple[Scenario, dict[str, Any]]]] | None

{name: builder}; defaults to FAMILIES. A builder takes (fps, noise, seed) and returns (Scenario, config dict).

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 i uses seed + i.

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 seed, the scalar evaluate_lanes metrics,

DataFrame

in-lane overtakings (overtakings, overtakings_per_100_vehicle_km) and runtime_s [s].

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 summary of in_lane_overtakings on the true lanes.

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 y).

required
y Sequence[float]

Second sample, paired with x element by element.

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. SEED).

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 [seed, crc32(name)].

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 df are skipped. Values are compared as strings, the sort is stable.

required

Returns:

Type Description
DataFrame

The sorted table with a fresh RangeIndex.

Raises:

Type Description
KeyError

If none of the key columns is in df.

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 (generator(seed, name)).

required
cluster str

Column with the cluster label (e.g. "unit", a recording unit).

'unit'
key Sequence[str]

Columns that define the canonical row order (see sort_by_key).

('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]

(estimate, lower, upper): stat on the full (sorted) frame and the lower and upper percentile bounds.

Raises:

Type Description
KeyError

From sort_by_key, if none of the key columns is in df.

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 (generator(seed, name)).

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]

(lower, upper) bounds of the interval of the median.

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

(n10, n01, p): the number of pairs with a true and b false, the number with a false and b

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 p, capped at 1.

Macroscopic traffic quantities (Edie).