Skip to content

Processing

Generated by docs/scripts/make_api_pages.py.

Processing steps of the pipeline, from raw positions to road-referenced trajectories with lanes and surroundings.

Every step has an entry function that takes a DataFrame and keyword parameters, without the configuration (e.g. project_to_reference_line, assign_lanes); processing.pipeline calls them in order. The names below are re-exported for callers; the subpackages hold the implementations. Conventions: pos_lon [m] runs along the travel direction, pos_lat [m] is positive to the left; lane 0 is the auxiliary or ramp lane, 1 the rightmost main lane, -1 not assigned.

PerspectiveParams dataclass

PerspectiveParams(correction: str = 'class_offset_empirical_view', kappa: dict[str, float] | None = None, d_c_m: float | None = None, offset_m: dict[str, float] | None = None, min_points: int = 30, max_iter: int = 4, tol_m: float = 0.05, max_offset_m: float = 2.5, joint_offset_scope: str = 'global', joint_tau_m: float = 1.5, joint_lane_tau_m: float = 0.5, joint_lane_min_sep_m: float | None = 2.5, joint_section_m: float = 300.0, joint_smooth_tau_m: float = 0.3, joint_hgv_lane_alpha: float = 0.5, joint_hgv_exclude_left_lane: bool = True, joint_mode_tie_nats: float = 0.05, joint_profile: bool = True, joint_profile_range_m: float = 3.0, joint_profile_step_m: float = 0.05, joint_max_outer: int = 20, joint_tol_m: float = 0.01, joint_estimate: dict[str, Any] | None = None, view_detection: str = 'hgv_band', view_boundaries_m: Sequence[float] | None = None, view_offsets_m: Sequence[float] | None = None, view_bin_m: float = 50.0, view_min_segment_m: float = 150.0, view_min_jump_m: float = 0.6, view_min_hgv: int = 300, view_min_car: int = 1000, view_blend_m: float = 25.0, view_max_offset_m: float = 5.0, view_ambiguous_pp: float = 5.0, view_robust_reading: bool = True, view_robust_margin_pp: float = 10.0, view_max_abs_delta_m: float | None = None)

Parameters of correct_perspective; defaults of the preset drone_hgv_paper.

The fields and their meaning are those of the configuration section perspective (docs/configuration.md); only the default of correction differs (the method of the preset instead of "none").

Attributes:

Name Type Description
correction str

Method: "class_offset_empirical_view" (one iterated empirical HGV offset per camera view), "class_offset_empirical" (one iterated offset per direction), "constant_class_offset", "lateral_class_offset" (geometric model) or "joint_gmm" (experimental). Defaults to "class_offset_empirical_view".

kappa dict[str, float] | None

lateral_class_offset: class group -> kappa [-]; None estimates it. Defaults to None.

d_c_m float | None

lateral_class_offset: lateral position [m] of the ground point of the camera. Defaults to None.

offset_m dict[str, float] | None

constant_class_offset / class_offset_empirical: class group -> lateral shift [m]; None estimates it. Defaults to None.

min_points int

Minimum rows per class, lane and 50 m bin in a diagnostic pass. Defaults to 30.

max_iter int

Maximum diagnostic passes of the iterated estimates. Defaults to 4.

tol_m float

Stop when the absolute residual offset is below this [m]. Defaults to 0.05.

max_offset_m float

class_offset_empirical: safety limit [m]. Defaults to 2.5.

joint_offset_scope str

joint_gmm: "global", "lane" or "piecewise". Defaults to "global".

joint_tau_m float

joint_gmm: prior SD of the offset [m]. Defaults to 1.5.

joint_lane_tau_m float

joint_gmm: SD of the lane offsets around their mean [m]. Defaults to 0.5.

joint_lane_min_sep_m float | None

joint_gmm: minimum distance [m] of displaced HGV centers of adjacent lanes. Defaults to 2.5.

joint_section_m float

joint_gmm: section length [m]. Defaults to 300.0.

joint_smooth_tau_m float

joint_gmm: SD of the change between neighboring sections [m]. Defaults to 0.3.

joint_hgv_lane_alpha float

joint_gmm: strength of the Dirichlet prior favoring the right lanes. Defaults to 0.5.

joint_hgv_exclude_left_lane bool

joint_gmm: no HGVs in the leftmost of three or more lanes. Defaults to True.

joint_mode_tie_nats float

joint_gmm: tolerance [nats per HGV point] of equivalent modes. Defaults to 0.05.

joint_profile bool

joint_gmm: evaluate the profile log posterior. Defaults to True.

joint_profile_range_m float

joint_gmm: range of that profile [m]. Defaults to 3.0.

joint_profile_step_m float

joint_gmm: grid step of that profile [m]. Defaults to 0.05.

joint_max_outer int

joint_gmm: maximum outer iterations. Defaults to 20.

joint_tol_m float

joint_gmm: stop when the offset changes by less than this [m]. Defaults to 0.01.

joint_estimate dict[str, Any] | None

joint_gmm: estimate of an earlier run; skips the estimation. Defaults to None.

view_detection str

"hgv_band" or "seams": how the view boundaries are found. Defaults to "hgv_band".

view_boundaries_m Sequence[float] | None

Fixed view boundaries along pos_lon [m]. Defaults to None.

view_offsets_m Sequence[float] | None

With view_boundaries_m: fixed HGV offset per view [m]. Defaults to None.

view_bin_m float

Bin length of the HGV band profile [m]. Defaults to 50.0.

view_min_segment_m float

Minimum view length [m]. Defaults to 150.0.

view_min_jump_m float

Minimum offset step between views [m]. Defaults to 0.6.

view_min_hgv int

Minimum HGV samples per view. Defaults to 300.

view_min_car int

Minimum car samples per view. Defaults to 1000.

view_blend_m float

Offsets are blended over +- this around each boundary [m]. Defaults to 25.0.

view_max_offset_m float

Per-view safety limit [m]. Defaults to 5.0.

view_ambiguous_pp float

Readings closer than this [percentage points] are ambiguous. Defaults to 5.0.

view_robust_reading bool

Robust reading of the per-view offset. Defaults to True.

view_robust_margin_pp float

Margin of the robust reading [percentage points]. Defaults to 10.0.

view_max_abs_delta_m float | None

Readings with |delta| above this [m] are not considered. Defaults to None.

__post_init__

__post_init__() -> None

Check correction.

Raises:

Type Description
ValueError

If correction is not in PERSPECTIVE_CORRECTIONS.

PerspectiveResult dataclass

PerspectiveResult(tracks: TrackFrame, estimate: dict[str, Any])

Result of correct_perspective.

Attributes:

Name Type Description
tracks TrackFrame

The samples with the corrected pos_lat of tall vehicles.

estimate dict[str, Any]

What was estimated or applied (the perspective record of the run metadata).

AlignmentParams dataclass

AlignmentParams(km_step: float = 10.0, smoothing_sigma_m: float = 30.0, quantile: float = 0.05, target_offset_m: float = 2.0, edge_freeze_m: float = 0.0, edge_freeze_bins: int | None = None, profile_classes: Sequence[str] | None = None)

Parameters of the road-edge alignment (align_lateral_positions); defaults of the preset drone_hgv_paper.

Attributes:

Name Type Description
km_step float

Longitudinal bin width of the road-edge profile [m]. Defaults to 10.0.

smoothing_sigma_m float

Gaussian smoothing sigma of the profile [m]. Defaults to 30.0.

quantile float

Quantile (0-1) of pos_lat per bin that defines the right road edge. Defaults to 0.05.

target_offset_m float

Lateral position [m] the road-edge profile is moved to (center of lane 1). Defaults to 2.0.

edge_freeze_m float

Length [m] at each end of the profile frozen to the first interior value; 0 disables the freeze. Defaults to 0.0.

edge_freeze_bins int | None

Legacy setting in bins; overrides edge_freeze_m if set. Defaults to None.

profile_classes Sequence[str] | None

Classes whose positions define the road-edge profile; None uses all rows. Defaults to None.

AlignmentResult dataclass

AlignmentResult(tracks: TrackFrame, edge_profile: DataFrame)

Result of align_lateral_positions.

Attributes:

Name Type Description
tracks TrackFrame

The aligned samples.

edge_profile DataFrame

The lower-bound profile per bin (the second result of align_to_lower_bound).

KinematicsParams dataclass

KinematicsParams(method: str = 'montanino_punzo', smooth_window_sec: float = 4.0, smooth_window_frames: int | None = None, poly_order: int = 2, max_reversal_m: float = 15.0, lateral_smooth_window_sec: float | None = None, direction_consistency_min: float = 0.9, mp: MontaninoPunzoConfig = MontaninoPunzoConfig(), reconstruction: Mapping[str, Any] | None = None, spatial_correction_profiles: DataFrame | None = None)

Parameters of reconstruct_kinematics; defaults of the preset drone_hgv_paper.

Attributes:

Name Type Description
method str

"montanino_punzo" (Montanino & Punzo for pos_lon) or "savgol" (Savitzky-Golay for both coordinates). Defaults to "montanino_punzo".

smooth_window_sec float

Savitzky-Golay window [s]. Defaults to 4.0.

smooth_window_frames int | None

Explicit window in frames; wins over smooth_window_sec when set. Defaults to None.

poly_order int

Savitzky-Golay polynomial order. Defaults to 2.

max_reversal_m float

Vehicles moving backwards by more than this [m] are dropped. Defaults to 15.0.

lateral_smooth_window_sec float | None

Savitzky-Golay window [s] of pos_lat with montanino_punzo; None uses the longitudinal window. Defaults to None.

direction_consistency_min float

Minimum share (0-1) of vehicles whose pos_lon increases. Defaults to 0.9.

mp MontaninoPunzoConfig

Parameters of the Montanino & Punzo reconstruction (trim_track_ends_sec = 2.0 s as in the preset).

reconstruction Mapping[str, Any] | None

Filter spec that replaces the Montanino & Punzo steps (filters.track_kinematics); None for Montanino & Punzo. Defaults to None.

spatial_correction_profiles DataFrame | None

Profiles of spatial_correction.estimate_spatial_bias to remove a spatially fixed position error first; None for no correction. Defaults to None.

__post_init__

__post_init__() -> None

Check method.

Raises:

Type Description
ValueError

If method is not in KINEMATICS_METHODS.

KinematicsResult dataclass

KinematicsResult(tracks: TrackFrame, mp_tracks: dict[Hashable, TrackKinematics], counters: dict[str, Any], spatial_corrected_share: float | None = None)

Result of reconstruct_kinematics.

Attributes:

Name Type Description
tracks TrackFrame

The samples with smoothed positions, speed [km/h] and acceleration [m/s^2].

mp_tracks dict[Hashable, TrackKinematics]

Vehicle ID -> its Montanino & Punzo reconstruction (TrackKinematics, with the 10 Hz grid values); empty for savgol.

counters dict[str, Any]

Counters of the Montanino & Punzo reconstruction (vehicles, too short, the track-end report); empty for savgol.

spatial_corrected_share float | None

Share of the rows on corrected lanes; None without a spatial correction.

HmmLaneParams dataclass

HmmLaneParams(rate_in_event: float = 2.0, rate_background: float = 0.001, sigma_floor_m: float = 0.4, epsilon: float = 0.001, emission_floor: str = 'relative', initial_geometry: str = 'labels', zone_margin_m: float = 10.0, merge_gap_s: float = 1.0, max_dwell_s: float = 2.0, aux_lane_fallback: bool = True, conflict_margin_m: float = 1.0, conflict_penalty: float = float(np.log(0.0001)), max_conflict_iterations: int = 10, duplicate_min_overlap_sec: float = 1.0, duplicate_min_confidence: float = 0.9, duplicate_max_lateral_m: float = 0.5, max_em_iterations: int = 3, em_tolerance: float = 0.001, em_bin_m: float = 10.0, em_smooth_sigma_m: float = 30.0, min_points_per_bin: int = 10, conflict_damping: bool = True, conflict_min_duration_sec: float = 1.0, conflict_hold_sec: float = 2.0, min_aux_zone_m: float = 50.0)

Parameters of the hidden-Markov-model lane assignment (method="hmm"); defaults of drone_hgv_paper.

Rates are per second and converted per sample with p = 1 - exp(-rate * dt).

Attributes:

Name Type Description
rate_in_event float

Rate [1/s] of a switch towards the detected side inside a detector interval. Defaults to 2.0.

rate_background float

Rate [1/s] of any other switch. Defaults to 1e-3.

sigma_floor_m float

Minimum lateral spread of a lane [m]. Defaults to 0.4.

epsilon float

Weight of the outlier floor in the emission. Defaults to 1e-3.

emission_floor str

"relative" or "uniform" (hmm.emission_logprob). Defaults to "relative".

initial_geometry str

"labels" (medians of the step 06 labels) or "tracker" (the step 06 lane centers, passed as lane_centers). Defaults to "labels".

zone_margin_m float

Lane 0 is valid up to this distance [m] beyond an auxiliary-lane zone. Defaults to 10.0.

merge_gap_s float

Detector intervals closer than this [s] form one maneuver. Defaults to 1.0.

max_dwell_s float

A -> B -> A is collapsed to A if the time in B is at most this [s]. Defaults to 2.0.

aux_lane_fallback bool

Keep lane 0 (center one lane width right of lane 1) when step 06 gave it no points. Defaults to True.

conflict_margin_m float

Margin [m] of the feasibility test of two vehicles in one lane. Defaults to 1.0.

conflict_penalty float

Log-penalty for the occupied lane on conflict frames. Defaults to log(1e-4).

max_conflict_iterations int

Re-decoding rounds. Defaults to 10.

duplicate_min_overlap_sec float

Minimum conflict length [s] of a suspected duplicate track. Defaults to 1.0.

duplicate_min_confidence float

Minimum lane confidence (0-1) of both vehicles of a duplicate. Defaults to 0.9.

duplicate_max_lateral_m float

Maximum lateral distance [m] of a duplicate. Defaults to 0.5.

max_em_iterations int

Alternating estimation of lane centers and labels. Defaults to 3.

em_tolerance float

Stop when less than this share of labels changes. Defaults to 0.001.

em_bin_m float

Bin length [m] of the center re-estimation. Defaults to 10.0.

em_smooth_sigma_m float

Gaussian smoothing [m] of the center profile. Defaults to 30.0.

min_points_per_bin int

Minimum points of a lane in a bin. Defaults to 10.

conflict_damping bool

Damped conflict resolution (conflict_min_duration_sec, conflict_hold_sec). Defaults to True.

conflict_min_duration_sec float

Shortest conflict episode [s] that is resolved. Defaults to 1.0.

conflict_hold_sec float

Shortest penalty window [s] of a re-assigned vehicle. Defaults to 2.0.

min_aux_zone_m float

Auxiliary-lane zones shorter than this [m] are not offered to the HMM. Defaults to 50.0.

LaneAssignmentParams dataclass

LaneAssignmentParams(method: str = 'hmm', lane_changes: LaneChangeParams = LaneChangeParams(), resolve_conflicts: bool = True, keep_unresolved_lane: bool = False, edge_buffer_m: float = 30.0, direction_consistency_min: float = 0.9, hmm: HmmLaneParams = HmmLaneParams())

Parameters of assign_lanes; defaults of the preset drone_hgv_paper.

Attributes:

Name Type Description
method str

"hmm" (hidden Markov model, page 09) or "heuristic" (crossover correction, page 08). Defaults to "hmm".

lane_changes LaneChangeParams

Settings of the lane-change detector. Defaults to LaneChangeParams().

resolve_conflicts bool

Resolve two vehicles in one lane at the same time. Defaults to True.

keep_unresolved_lane bool

Keep the lane before the conflict resolution in lane_fixed_unresolved. Defaults to False.

edge_buffer_m float

Events within this distance [m] of either road end are flagged near_road_end. Defaults to 30.0.

direction_consistency_min float

Minimum share (0-1) of vehicles whose pos_lon increases. Defaults to 0.9.

hmm HmmLaneParams

Parameters of the hidden Markov model. Defaults to HmmLaneParams().

__post_init__

__post_init__() -> None

Check method.

Raises:

Type Description
ValueError

If method is not in LANE_ASSIGNMENT_METHODS.

LaneAssignmentResult dataclass

LaneAssignmentResult(tracks: TrackFrame, events: EventFrame | None, hmm_geometry: LaneGeometry | None = None, em_history: list[dict[str, float]] = list(), conflict_history: list[dict[str, int]] = list())

Result of assign_lanes.

Attributes:

Name Type Description
tracks TrackFrame

The samples with the corrected lanes.

events EventFrame | None

One row per detected lateral maneuver, classified (event_type) and flagged near_road_end; None for an empty input.

hmm_geometry LaneGeometry | None

The lane geometry of the hidden Markov model; None for the heuristic.

em_history list[dict[str, float]]

One record per EM iteration of the hidden Markov model; empty for the heuristic.

conflict_history list[dict[str, int]]

One record per conflict round of the hidden Markov model; empty for the heuristic.

LaneGeometryParams dataclass

LaneGeometryParams(lon_step_m: float = 50.0, window_size_m: float = 200.0, max_drift_m: float = 2.0, gmm_model: str = 'restricted', gmm_prior_eta_m: float = 3.75, gmm_prior_kappa: float = 100.0, gmm_prior_nu: float = 3.0, gmm_prior_varsigma2_m2: float = 0.25, direction_consistency_min: float = 0.9)

Parameters of estimate_lane_geometry; defaults of the preset drone_hgv_paper.

Attributes:

Name Type Description
lon_step_m float

Step of the rolling window along pos_lon [m]. Defaults to 50.0.

window_size_m float

Length of the rolling window [m]. Defaults to 200.0.

max_drift_m float

Largest lateral drift [m] of a tracked lane center between two windows. Defaults to 2.0.

gmm_model str

"restricted" (equal lane widths, Chen & Krumm 2010) or "free". Defaults to "restricted".

gmm_prior_eta_m float

Prior lane width [m] of the restricted GMM. Defaults to 3.75.

gmm_prior_kappa float

Prior strength of the lane width. Defaults to 100.0.

gmm_prior_nu float

Prior degrees of freedom of the lane variance. Defaults to 3.0.

gmm_prior_varsigma2_m2 float

Prior lane variance [m^2]. Defaults to 0.25.

direction_consistency_min float

Minimum share (0-1) of vehicles whose pos_lon increases. Defaults to 0.9.

priors

priors() -> dict[str, float]

Return the GMM priors as the tracker takes them.

Returns:

Type Description
dict[str, float]

eta, kappa, nu and varsigma2.

LaneGeometryResult dataclass

LaneGeometryResult(tracks: TrackFrame, centers: DataFrame, diagnostics: dict[str, Any] | None)

Result of estimate_lane_geometry.

Attributes:

Name Type Description
tracks TrackFrame

The samples with lane.

centers DataFrame

Lane centers per window (km_bin, lane, center_y [m]), lanes numbered like lane; empty if no sample was labeled.

diagnostics dict[str, Any] | None

Stability of the geometry (lane_geometry_diagnostics); None if no sample was labeled.

LaneChangeParams dataclass

LaneChangeParams(lat_speed_threshold_mps: float = 0.1, min_displacement_m: float = 1.5, median_kernel_sec: float = 0.167, sewma_halfwidth_sec: float = 0.5, sewma_width_sec: float = SEWMA_WIDTH_DEFAULT_SEC)

Settings of the lane-change detector (detect_lane_changes), as the lane assignment takes them.

Attributes:

Name Type Description
lat_speed_threshold_mps float

Threshold [m/s] on the smoothed lateral speed. Defaults to 0.1.

min_displacement_m float

Minimum lateral displacement [m] of an interval. Defaults to 1.5.

median_kernel_sec float

Width of the median filter [s]. Defaults to 0.167.

sewma_halfwidth_sec float

Half-width of the SEWMA kernel [s]. Defaults to 0.5.

sewma_width_sec float

Kernel width T of the SEWMA [s]. Defaults to SEWMA_WIDTH_DEFAULT_SEC (0.316 s).

ResamplingResult dataclass

ResamplingResult(tracks: TrackFrame, rows_from_mp_grid: int | None = None)

Result of resample_tracks.

Attributes:

Name Type Description
tracks TrackFrame

The samples on the output grid.

rows_from_mp_grid int | None

Number of output rows that took the Montanino & Punzo grid values; None if they were not used (no reconstruction given, or another rate).

PlatoonResult dataclass

PlatoonResult(tracks: TrackFrame, report: dict[str, Any] | None = None)

Result of enforce_platoon_consistency.

Attributes:

Name Type Description
tracks TrackFrame

The samples after the post-pass and the new surroundings.

report dict[str, Any] | None

The report of platoon_consistency_post_pass plus rows_below_h_min_after; None if skipped.

StitchingResult dataclass

StitchingResult(tracks: TrackFrame, links: DataFrame)

Result of stitch_fragments.

Attributes:

Name Type Description
tracks TrackFrame

The stitched samples (merged IDs).

links DataFrame

One record per link of two fragments (stitch_trajectories), with the stage number in stage.

PipelineResult dataclass

PipelineResult(tracks: TrackFrame, events: EventFrame, intermediates: dict[str, TrackFrame] = dict())

Full result of run_pipeline_detailed.

Attributes:

Name Type Description
tracks TrackFrame

The processed trajectories (a TrackFrame; all columns in docs/output_format.md) with the run metadata in tracks.attrs["trajlab"].

events EventFrame

The lane-change event table (an EventFrame; one row per lateral manoeuvre, see docs/output_format.md), empty if Step 5 did not run.

intermediates dict[str, TrackFrame]

Step name -> copy of the data after that step (only steps that ran; before rounding); empty unless keep_intermediates=True.

project_onto_centerline

project_onto_centerline(gdf: GeoDataFrame, ref_line: LineString, direction_consistency_min: float = 0.9) -> gpd.GeoDataFrame

Project UTM trajectory points onto a reference line in Frenet coordinates.

Computes the longitudinal position pos_lon (arc-length distance along the centerline) and the signed lateral offset pos_lat (perpendicular distance) for every trajectory point, then normalises both to the direction of travel:

  • The sign of the raw lateral offset comes from the cross product of the local tangent and the point-to-projection offset, i.e. it is relative to the digitising direction of ref_line.
  • The per-vehicle net displacement along the line decides the travel direction. If the moving vehicles travel against the digitising direction, pos_lon <- L - pos_lon and pos_lat <- -pos_lat with L = ref_line.length, which is the same as reversing the line.

Afterwards pos_lon increases in the direction of travel and pos_lat > 0 is left of it, whichever way the line was drawn.

Parameters:

Name Type Description Default
gdf GeoDataFrame

Points with a geometry column of UTM point coordinates (e.g. EPSG:25832) and, for the direction check, id and datum. Other columns are preserved.

required
ref_line LineString

Shapely LineString along the road, in the same CRS as gdf; it may be digitised in either direction.

required
direction_consistency_min float

Minimum share (0-1) of moving vehicles that must travel in the same direction along the line.

0.9

Returns:

Type Description
GeoDataFrame

A copy of gdf with the added columns pos_lon (distance along the line in the direction of travel

GeoDataFrame

[m]), pos_lat (signed lateral offset [m], positive to the left of the direction of travel),

GeoDataFrame

pos_lon_ref (distance from the start of ref_line as digitised [m], for mapping results back to the

GeoDataFrame

line) and ref_line_reversed (bool: the travel direction is opposite to the digitising direction).

Raises:

Type Description
ValueError

If the vehicles do not share one travel direction; the input then has to be split by direction.

project_to_reference_line

project_to_reference_line(tracks: GeoDataFrame, ref_line: LineString, *, direction_consistency_min: float = 0.9, end_margin_m: float = 1.0) -> TrackFrame

Project the trajectory points onto the reference line and drop the points near its ends.

Entry function of page 01 of the pipeline steps 01-10 (docs/pipeline/01_reference_line_projection.md). Requires the column geometry (UTM points; id and datum for the direction check) and adds pos_lon [m] (along the direction of travel), pos_lat [m] (positive to the left), pos_lon_ref [m] and ref_line_reversed [bool]. Method: projection onto the arc length of the line (Frenet frame), see project_onto_centerline.

Example

import trajlab from trajlab.processing.reference_line import project_to_reference_line raw = trajlab.examples.synthetic_motorway() ref_east, _ = trajlab.estimate_ref_lines(raw) tracks = project_to_reference_line(raw[raw["orientation"] > 0], ref_east)

Parameters:

Name Type Description Default
tracks GeoDataFrame

Trajectory points (a GeoDataFrame in the CRS of ref_line). Not modified.

required
ref_line LineString

Reference line along the road; it may be digitised in either direction.

required
direction_consistency_min float

Minimum share (0-1) of moving vehicles that must travel in the same direction. Defaults to 0.9 (preset drone_hgv_paper, projection.direction_consistency_min).

0.9
end_margin_m float

Points closer than this to either end of the line [m] are dropped. Defaults to 1.0.

1.0

Returns:

Type Description
TrackFrame

The projected points within the line, a new frame.

check_pos_lon_increasing

check_pos_lon_increasing(df: TrackFrame, step: str, direction_consistency_min: float = 0.9, lon_col: str = C.POS_LON, time_col: str = C.TIME) -> None

Raise if pos_lon does not increase in the direction of travel.

Steps 3-6 rely on this convention, which Step 1 establishes. Input that skips Step 1 (pre-computed pos_lon) has to follow it as well.

Parameters:

Name Type Description Default
df TrackFrame

Trajectory points with id, the time and the longitudinal column.

required
step str

Name of the calling step, used in the error message.

required
direction_consistency_min float

Minimum share (0-1) of moving vehicles whose pos_lon must increase.

0.9
lon_col str

Column of the longitudinal position [m].

POS_LON
time_col str

Column of the time.

TIME

Raises:

Type Description
ValueError

If fewer than direction_consistency_min of the moving vehicles have an increasing pos_lon.

correct_perspective

correct_perspective(tracks: TrackFrame, *, params: PerspectiveParams | None = None, layout: LaneLayout | None = None, lane_geometry: LaneGeometryParams | None = None, alignment: AlignmentParams | None = None, label_lanes: Callable[[TrackFrame], TrackFrame] | None = None) -> PerspectiveResult

Correct the lateral displacement of tall vehicles (HGVs) that the camera perspective causes.

Entry function of page 02 of the pipeline steps 01-10 (docs/pipeline/02_perspective_correction.md). Requires the columns pos_lon and pos_lat [m] (project_to_reference_line), class and, for the view method, id and datum; corrects pos_lat [m] of the HGVs and adds no column. The offsets are estimated on diagnostic passes that label the lanes of the uncorrected data: by default the alignment, Savitzky-Golay kinematics, the lane geometry and the heuristic lane assignment with the parameters given here. Method: the HGV-minus-car offset per lane and bin, iterated per camera view (Baumann, Grau & Vortisch, ANT 2027).

Example

import trajlab from trajlab.processing.perspective import PerspectiveParams, correct_perspective from trajlab.processing.reference_line import project_to_reference_line raw = trajlab.examples.synthetic_motorway() ref_east, _ = trajlab.estimate_ref_lines(raw) tracks = project_to_reference_line(raw[raw["orientation"] > 0], ref_east) result = correct_perspective(tracks, params=PerspectiveParams(correction="class_offset_empirical")) corrected, estimate = result.tracks, result.estimate

Parameters:

Name Type Description Default
tracks TrackFrame

Projected samples of one direction of travel. Not modified.

required
params PerspectiveParams | None

Parameters; None uses PerspectiveParams().

None
layout LaneLayout | None

Number of main lanes and the zones of the site; None uses LaneLayout() (3 lanes, no zones).

None
lane_geometry LaneGeometryParams | None

Lane-geometry parameters (GMM priors; window and step of joint_gmm); None uses LaneGeometryParams().

None
alignment AlignmentParams | None

Alignment parameters of the diagnostic pass and of joint_gmm; None uses AlignmentParams().

None
label_lanes Callable[[TrackFrame], TrackFrame] | None

The diagnostic pass: a function that returns the samples with lane_fixed; None uses diagnostic_lane_labels with the parameters above.

None

Returns:

Type Description
PerspectiveResult

The corrected samples and the estimate.

align_lateral_positions

align_lateral_positions(tracks: TrackFrame, *, params: AlignmentParams | None = None, layout: LaneLayout | None = None, lane_width_m: float = 3.75) -> AlignmentResult

Align the lateral positions to the lower road edge, so that the lanes become horizontal bands.

Entry function of page 03 of the pipeline steps 01-10 (docs/pipeline/03_alignment.md). Requires the columns pos_lon and pos_lat [m] (project_to_reference_line); changes pos_lat and adds pos_lat_raw [m] (before the alignment) and y_correction [m]. Method: the lower-quantile profile of pos_lat along the road, smoothed and subtracted (align_to_lower_bound).

Example

import trajlab from trajlab.processing.alignment import align_lateral_positions from trajlab.processing.reference_line import project_to_reference_line raw = trajlab.examples.synthetic_motorway() ref_east, _ = trajlab.estimate_ref_lines(raw) tracks = project_to_reference_line(raw[raw["orientation"] > 0], ref_east) aligned = align_lateral_positions(tracks).tracks

Parameters:

Name Type Description Default
tracks TrackFrame

Samples of one direction of travel. Not modified.

required
params AlignmentParams | None

Alignment parameters; None uses AlignmentParams().

None
layout LaneLayout | None

Number of main lanes and the zones of the site; None uses LaneLayout() (3 lanes, no zones).

None
lane_width_m float

Lane width [m] used for lane-count zones on the right side. Defaults to 3.75 (the prior lanes.gmm_prior_eta_m of the preset).

3.75

Returns:

Type Description
AlignmentResult

The aligned samples and the road-edge profile.

align_to_lower_bound

align_to_lower_bound(df_direction: TrackFrame, km_step: float = 10.0, smoothing_sigma_m: float = 30.0, lon_col: str = C.POS_LON, lat_col: str = C.POS_LAT, quantile: float = 0.05, target_offset_m: float = 2.0, edge_freeze_bins: int = 10, aux_lane_zones: Sequence[AuxLaneZone] | None = None, edge_freeze_m: float | None = None, lane_count_zones: Sequence[LaneCountZone] | None = None, n_main_lanes: int = 3, lane_width_m: float = 3.75, profile_classes: Sequence[str] | None = None) -> tuple[TrackFrame, pd.DataFrame]

Align the lateral coordinates horizontally to the lower road edge.

Corrects for centerline curvature by computing the 5th-percentile (right-most) lateral offset profile along the longitudinal axis, smoothing it with a Gaussian filter, and subtracting this profile from all lateral coordinates. The result is shifted so that the right-most edge sits at y = +2.0 m, which corresponds to the geometric center of the rightmost lane.

This step converts curved, non-horizontal lane bands into parallel, horizontal bands that are independent of road curvature—making downstream GMM lane detection much more reliable.

A boundary freeze is applied to the first and last edge_freeze_m metres (or edge_freeze_bins bins) to avoid edge artifacts from sparse data near the field-of-view boundaries. The freeze also hides real lateral changes of the road edge there, e.g. an exit taper.

Inside auxiliary-lane zones the lowest lateral band is the auxiliary lane, not the right edge of the main carriageway. Bins that overlap a zone are therefore left out of the lower-bound profile, which is interpolated linearly across them (over pos_lon) before smoothing. Without zones the result is unchanged.

Lane-count zones on the right side (side == "right") move the road edge by whole lanes; there the profile is referred back to the cross-section of n_main_lanes lanes (with a linear taper of taper_m), so that lane positions and numbers stay continuous.

Parameters:

Name Type Description Default
df_direction TrackFrame

Samples of a single direction of travel with pos_lon and pos_lat [m].

required
km_step float

Bin width along the longitudinal axis [m] (resolution of the correction profile).

10.0
smoothing_sigma_m float

Standard deviation of the Gaussian smoothing of the profile [m].

30.0
lon_col str

Column of the longitudinal position [m].

POS_LON
lat_col str

Column of the lateral position [m].

POS_LAT
quantile float

Quantile (0-1) of lat_col per bin that defines the lower bound.

0.05
target_offset_m float

Lateral position [m] that the lower bound is moved to (the centre of the rightmost lane).

2.0
edge_freeze_bins int

Number of bins at each end whose profile value is frozen to that of the first interior bin. Applied only when the profile has more than 2 * edge_freeze_bins bins; 0 disables it.

10
aux_lane_zones Sequence[AuxLaneZone] | None

AuxLaneZone intervals (pos_lon [m], widened by one bin) to leave out of the profile; None for none.

None
edge_freeze_m float | None

Length [m] at each end to freeze; overrides edge_freeze_bins (converted with round(edge_freeze_m / km_step)). None uses edge_freeze_bins.

None
lane_count_zones Sequence[LaneCountZone] | None

LaneCountZone intervals (lane gain or drop); only zones on the right side change the profile. None for none.

None
n_main_lanes int

Number of main lanes outside the lane-count zones.

3
lane_width_m float

Lane width [m] used to refer the edge back in lane-count zones.

3.75
profile_classes Sequence[str] | None

Classes whose samples define the profile (e.g. cars, whose positions are not displaced by perspective); the profile is applied to all rows. None (or no class column) uses all samples.

None

Returns:

Type Description
TrackFrame

(df_aligned, lower_bound_profile): a copy of the input with corrected lat_col, the original values

DataFrame

in <lat_col>_raw and the subtracted profile in y_correction [m]; and the profile with the columns

tuple[TrackFrame, DataFrame]

x_bin (bin start [m]), lat_col (lower bound per bin after zones, gap filling and edge freeze [m])

tuple[TrackFrame, DataFrame]

and y_smooth (smoothed profile [m]).

apply_kinematic_smoothing

apply_kinematic_smoothing(x_pos: FloatArray, y_pos: FloatArray, timestamps: NDArray[datetime64] | FloatArray, smooth_window_frames: int | None = None, smooth_window_sec: float = 4.0, poly_order: int = 2) -> tuple[FloatArray, FloatArray, FloatArray, FloatArray]

Smooth one vehicle's track and derive speed and acceleration (Step 3).

A Savitzky-Golay filter fits a local polynomial of order poly_order over a moving window and evaluates the fitted value and its analytic first and second derivatives (generic smoothing; the Montanino & Punzo reconstruction is in montanino_punzo). To avoid the filter's distortion at the track ends, the positions are first extended by one window length at both ends with constant velocity (estimated from the first and last 5 samples); the padded part is cut off afterwards.

Window length: smooth_window_frames if given (made odd), otherwise smooth_window_sec divided by the median sampling interval, rounded to an odd number of at least 5 frames (121 frames for 4 s at 30 Hz).

Tracks shorter than the window (or with window <= poly_order) are not filtered: positions are returned unchanged and speed/acceleration come from first differences. Time steps of 0 s are treated as 0.04 s.

Parameters:

Name Type Description Default
x_pos FloatArray

Longitudinal positions pos_lon [m], in time order.

required
y_pos FloatArray

Lateral positions pos_lat [m], same length.

required
timestamps NDArray[datetime64] | FloatArray

Time stamps (datetime64 or seconds as floats), same length.

required
smooth_window_frames int | None

Fixed window in frames (made odd); wins over smooth_window_sec when positive.

None
smooth_window_sec float

Window [s], used when smooth_window_frames is None or not positive.

4.0
poly_order int

Polynomial order.

2

Returns:

Type Description
FloatArray

(x_smooth, y_smooth, speed_kmh, acc_ms2), each of the input length: smoothed longitudinal and lateral

FloatArray

position [m], speed [km/h] (absolute value of the longitudinal derivative) and longitudinal acceleration

FloatArray

[m/s^2] (signed, along increasing pos_lon). Tracks with fewer than 2 points return the positions

FloatArray

unchanged and zero speed and acceleration.

reconstruct_kinematics

reconstruct_kinematics(tracks: TrackFrame, *, params: KinematicsParams | None = None) -> KinematicsResult

Smooth the positions and derive speed [km/h] and acceleration [m/s^2] per vehicle.

Entry function of page 05 of the pipeline steps 01-10 (docs/pipeline/05_kinematics.md). Requires the columns id, datum, pos_lon and pos_lat [m] (project_to_reference_line); smooths pos_lon and pos_lat and adds speed [km/h], acceleration [m/s^2] and, with Montanino & Punzo, mp_reconstructed [bool]. Vehicles moving backwards by more than max_reversal_m are dropped. Method: Montanino & Punzo (2013, 2015) for pos_lon, Savitzky-Golay (1964) for pos_lat (and for both with method="savgol").

Example

import trajlab from trajlab.processing.kinematics import KinematicsParams, reconstruct_kinematics from trajlab.processing.reference_line import project_to_reference_line raw = trajlab.examples.synthetic_motorway() ref_east, _ = trajlab.estimate_ref_lines(raw) tracks = project_to_reference_line(raw[raw["orientation"] > 0], ref_east) smoothed = reconstruct_kinematics(tracks, params=KinematicsParams(method="savgol")).tracks

Parameters:

Name Type Description Default
tracks TrackFrame

Samples of one direction of travel (a DataFrame or a GeoDataFrame). Not modified.

required
params KinematicsParams | None

Parameters; None uses KinematicsParams().

None

Returns:

Type Description
KinematicsResult

The tracks, the per-vehicle Montanino & Punzo results and the counters.

assign_lanes

assign_lanes(tracks: TrackFrame, *, params: LaneAssignmentParams | None = None, layout: LaneLayout | None = None, lane_centers: DataFrame | None = None, road_length_m: float | None = None) -> LaneAssignmentResult

Detect the lane changes, correct the lane of every sample and resolve conflicts between vehicles.

Entry function of pages 08 (heuristic) and 09 (hidden Markov model) of the pipeline steps 01-10 (docs/pipeline/08_lane_assignment_heuristic.md, docs/pipeline/09_lane_assignment_hmm.md). Requires the columns id, datum, pos_lon, pos_lat [m], lane (estimate_lane_geometry) and speed [km/h] (reconstruct_kinematics). Adds lane_fixed, is_changing_lane, is_lateral_excursion, lane_conflict_resolved, optionally lane_fixed_unresolved and, with the hidden Markov model, lane_confidence, lane_posterior_margin, suspected_duplicate_track and lane_conflict_unresolved; lane is overwritten with lane_fixed. Method: lane-change detection of Hofinger & Fellendorf (2023), then a crossover correction (heuristic) or a hidden Markov model with EM re-estimation of the lane centers.

Example

import trajlab from trajlab.processing.kinematics import reconstruct_kinematics from trajlab.processing.lanes import assign_lanes, estimate_lane_geometry from trajlab.processing.reference_line import project_to_reference_line raw = trajlab.examples.synthetic_motorway() ref_east, _ = trajlab.estimate_ref_lines(raw) tracks = project_to_reference_line(raw[raw["orientation"] > 0], ref_east) tracks = estimate_lane_geometry(reconstruct_kinematics(tracks).tracks).tracks result = assign_lanes(tracks, road_length_m=ref_east.length) lanes, events = result.tracks, result.events

Parameters:

Name Type Description Default
tracks TrackFrame

Samples of one direction of travel. Not modified.

required
params LaneAssignmentParams | None

Parameters; None uses LaneAssignmentParams().

None
layout LaneLayout | None

Number of main lanes and the zones of the site; None uses LaneLayout() (3 lanes, no zones).

None
lane_centers DataFrame | None

Lane centers of step 06 (LaneGeometryResult.centers), used by the hidden Markov model with initial_geometry="tracker". Defaults to None.

None
road_length_m float | None

Length of the road [m] for the near_road_end flag; None uses the largest pos_lon.

None

Returns:

Type Description
LaneAssignmentResult

The tracks, the event table and, for the hidden Markov model, its geometry and histories.

estimate_lane_geometry

estimate_lane_geometry(tracks: TrackFrame, *, params: LaneGeometryParams | None = None, layout: LaneLayout | None = None) -> LaneGeometryResult

Track the lanes with a rolling GMM along the road and label every sample with its lane.

Entry function of page 06 of the pipeline steps 01-10 (docs/pipeline/06_lane_geometry.md). Requires the columns id, datum, pos_lon and pos_lat [m] (project_to_reference_line, best after align_lateral_positions) and adds lane (0 auxiliary lane, 1 rightmost main lane, -1 not assigned). Method: Gaussian mixtures in rolling windows along pos_lon, restricted to equal lane widths after Chen & Krumm (2010), lane centers tracked from window to window.

Example

import trajlab from trajlab.processing.lanes import estimate_lane_geometry from trajlab.processing.reference_line import project_to_reference_line from trajlab.road_layout import LaneLayout raw = trajlab.examples.synthetic_motorway() ref_east, _ = trajlab.estimate_ref_lines(raw) tracks = project_to_reference_line(raw[raw["orientation"] > 0], ref_east) labeled = estimate_lane_geometry(tracks, layout=LaneLayout(n_main_lanes=3)).tracks

Parameters:

Name Type Description Default
tracks TrackFrame

Samples of one direction of travel. Not modified.

required
params LaneGeometryParams | None

Parameters; None uses LaneGeometryParams().

None
layout LaneLayout | None

Number of main lanes and the zones of the site; None uses LaneLayout() (3 lanes, no zones).

None

Returns:

Type Description
LaneGeometryResult

The labeled samples, the lane centers and the diagnostics.

estimate_lanes_rolling_tracker

estimate_lanes_rolling_tracker(df_direction: TrackFrame, lon_step: float = 50.0, window_size: float = 200.0, max_lanes: int = 4, max_drift: float = 2.0, lon_col: str = C.POS_LON, lat_col: str = C.POS_LAT, aux_lane_zones: Sequence[AuxLaneZone] | None = None, gmm_model: Literal['free', 'restricted'] = 'free', gmm_priors: dict[str, float] | None = None, lane_count_zones: list[LaneCountZone] | None = None) -> tuple[TrackFrame, pd.DataFrame, pd.DataFrame]

Extract and track the lanes of one direction with a rolling GMM and Hungarian matching.

Processes trajectory data using a sliding longitudinal window. Within each window, fits Gaussian Mixture Models (GMM) of varying component counts to the lateral positions and selects the best-fitting number of lanes using the Bayesian Information Criterion (BIC). A minimum lane separation of 2.5 m is enforced to prevent spurious components.

Lane identities are tracked across windows using the Hungarian algorithm (linear sum assignment) to minimise the total drift distance between consecutive GMM centroids. Lanes that miss more than MAX_MISSED_FRAMES (10) consecutive windows are removed. Each point is then assigned to the nearest active lane centroid.

The returned lane IDs are raw tracking IDs (1, 2, ... in order of appearance, never 0); collapse_and_standardize_lanes numbers them by lateral order afterwards. Points that are never assigned stay -1.

Auxiliary lanes: inside an AuxLaneZone every point to the right of the rightmost main lane (its local centre minus half the local lane width) gets lane 0 and is left out of the GMM fit, so that the auxiliary lane does not take one of the main-lane components. In windows that touch a zone the GMM may use max_lanes + 1 components; if it does, the rightmost one is the auxiliary lane and is not tracked as a main lane (needed when a zone starts at the beginning of the section and no main lane is known yet). Outside zones lane 0 never occurs.

If the DataFrame contains a class column, GMM fitting is performed only on Car-class points; all points are classified against the fitted centroids.

Parameters:

Name Type Description Default
df_direction TrackFrame

Samples of one direction in the Frenet frame (lon_col, lat_col), optionally with a class column for the car-only fit.

required
lon_step float

Longitudinal step between window centres [m].

50.0
window_size float

Full length of the sliding window [m].

200.0
max_lanes int

Maximum number of GMM components ("free": BIC selects up to this number) or the number of main lanes ("restricted").

4
max_drift float

Maximum lateral drift [m] when matching a window centre to a tracked lane; pairs beyond it start a new lane.

2.0
lon_col str

Column of the longitudinal position [m].

POS_LON
lat_col str

Column of the lateral position [m].

POS_LAT
aux_lane_zones Sequence[AuxLaneZone] | None

AuxLaneZone intervals (pos_lon [m]) in which an auxiliary lane is assigned; None for none.

None
gmm_model Literal['free', 'restricted']

"free" (BIC over 1..max_lanes free components) or "restricted" (fit_restricted_gmm with exactly max_lanes equally spaced components, started from the grid search and from the previous window, keeping the higher posterior; plus the auxiliary-lane component in zones).

'free'
gmm_priors dict[str, float] | None

Priors of the restricted model (eta, kappa, nu, varsigma2) overriding RESTRICTED_GMM_PRIORS.

None
lane_count_zones list[LaneCountZone] | None

LaneCountZone intervals (lane gain or drop). Each window uses the main-lane count at its centre (max_lanes outside the zones): exactly that many components for "restricted", at most that many for "free". Tracked lanes left without a centre where the count drops are removed at once, and lane centres are not back-filled over more than one window (a lane that starts later must not appear earlier).

None

Returns:

Type Description
TrackFrame

(df_labeled, df_lane_boundaries, df_lane_centers):

DataFrame
  • df_labeled: copy of the input with the column lane: raw main-lane tracking IDs (>= 1), 0 for the auxiliary lane, -1 for unassigned samples.
DataFrame
  • df_lane_boundaries: columns km (window centre, pos_lon [m]) and boundary (lateral position of a lane boundary [m]).
tuple[TrackFrame, DataFrame, DataFrame]
  • df_lane_centers: columns km_bin (window centre [m]), lane (raw ID) and center_y (tracked lane centre [m]). Its attrs["windows"] holds one row per window: km_bin, n_fit (main-lane centres of the window fit), n_tracked (tracked lanes before the window), n_matched and lane_lost (a tracked lane got no centre of the window fit). The attrs entry is missing when no lane centre was found.

Raises:

Type Description
ValueError

If gmm_model is neither "free" nor "restricted" (checked after the early return for fewer than 10 samples).

collapse_and_standardize_lanes

collapse_and_standardize_lanes(df: TrackFrame, max_lanes: int, lat_col: str = C.POS_LAT, random_state: int = 42) -> TrackFrame

Number the main lanes by lateral order and collapse surplus tracks.

After the rolling-window GMM tracker runs, raw main-lane IDs are in order of appearance and may be fragmented (e.g. 1, 4, 7) or more than the road has lanes. This function always renumbers them strictly by lateral position: the lowest pos_lat band (rightmost lane) becomes 1, the next one to the left 2, and so on.

  • If there are at most max_lanes raw main lanes, they are ranked by their median lateral position.
  • Otherwise 1D KMeans with max_lanes clusters is fitted on the lateral positions of the main-lane points (on a reproducible random sample of at most 10 000 points), and each raw lane is mapped to its nearest cluster centre, numbered from right to left.

The auxiliary lane (0) and unassigned points (-1) are kept as they are and never mapped to a main-lane ID.

Parameters:

Name Type Description Default
df TrackFrame

Samples with a lane column (raw lane IDs) and the lateral position column.

required
max_lanes int

Number of main lanes (PipelineConfig.n_main_lanes).

required
lat_col str

Column of the lateral position [m] used to order the lanes.

POS_LAT
random_state int

Seed of the KMeans sample and initialisation.

42

Returns:

Type Description
TrackFrame

A copy of df with the main lanes renumbered to 1..max_lanes (or fewer if fewer lanes are observed);

TrackFrame

unchanged copy if df is empty, has no lane column or no main-lane sample.

apply_lane_correction

apply_lane_correction(df: TrackFrame, lat_speed_threshold_mps: float = 0.1, min_displacement_m: float = 1.5, median_kernel_sec: float = 0.167, sewma_halfwidth_sec: float = 0.5, alpha: float | None = None, sewma_width_sec: float = SEWMA_WIDTH_DEFAULT_SEC) -> tuple[TrackFrame, EventFrame, dict[int, float]]

Classify the lateral manoeuvres and correct the lane assignment at the crossovers.

Runs detect_lane_changes to find the lateral manoeuvre intervals of every vehicle and classifies each interval:

  • "lane_change": during the interval the lateral position crosses the boundary between the start-lane centre and the next lane centre in the direction of the movement, and the corrected lane (lane_fixed) before time_start differs from the one after time_end. For a track that starts (ends) inside the interval, the lane nearest to its first (last) observed position counts as the lane before (after).
  • "lateral_excursion": otherwise. This includes moves that stay inside a lane and aborted lane changes: a vehicle that crosses the boundary during the interval but then returns (slowly enough that the return is not detected as a manoeuvre of its own) has the same lane before and after, so the interval is an excursion. A return that is fast enough to be detected is a second interval; the two crossings then form a lane change and a lane change back.

Only lane changes create crossover points and set is_changing_lane. The crossover is the first sample beyond the boundary midpoint between the two lane centres. Between crossovers, lane_fixed is the lane whose centre is nearest to the segment's mean pos_lat. Excursions leave lane_fixed unchanged and set is_lateral_excursion for their window.

Vehicles without any lane change are handled by comparing the lateral median at the start vs. end of the trajectory. If they differ (a lane change too slow to be detected), a single crossover is placed where the boundary is crossed (the middle sample if it never is); its direction comes from the lane-centre positions, and is_changing_lane is set within 3 s of it. Vehicles whose start and end lanes agree get the lane nearest to their median pos_lat throughout.

Lane centres are the median pos_lat of the lanes with more than 100 samples (the auxiliary lane with any number; all assigned lanes if none qualifies).

Parameters:

Name Type Description Default
df TrackFrame

Trajectory samples with at least id, datum, pos_lon, pos_lat, lane and speed. It is not modified.

required
lat_speed_threshold_mps float

Detection threshold on the smoothed lateral speed [m/s] (detect_lane_changes).

0.1
min_displacement_m float

Minimum lateral displacement of an interval [m] (detect_lane_changes).

1.5
median_kernel_sec float

Width of the median filter [s] (detect_lane_changes).

0.167
sewma_halfwidth_sec float

Half-width of the SEWMA kernel [s] (detect_lane_changes).

0.5
alpha float | None

Deprecated per-sample SEWMA decay factor (see detect_lane_changes); None uses sewma_width_sec.

None
sewma_width_sec float

SEWMA kernel width [s].

SEWMA_WIDTH_DEFAULT_SEC

Returns:

Type Description
TrackFrame

(df_corrected, events, lane_centers):

EventFrame
  • df_corrected: the samples sorted by id and time with the added columns lane_fixed (corrected lane), is_changing_lane and is_lateral_excursion (bool).
dict[int, float]
  • events: one row per detected interval (detect_lane_changes columns) plus event_type (EVENT_LANE_CHANGE or EVENT_LATERAL_EXCURSION), time_cross (boundary crossing, lane changes only), lane_before / lane_after (lane_fixed just before time_start / just after time_end) and max_lateral_offset_m [m] (excursions only: the largest signed offset from the start-lane centre in the interval, positive = left). Time columns keep the time zone of df.
tuple[TrackFrame, EventFrame, dict[int, float]]
  • lane_centers: lane ID -> median lateral position [m].

resolve_in_lane_conflicts

resolve_in_lane_conflicts(df: TrackFrame, lane_centers: Mapping[int, float], aux_lane_zones: Sequence[AuxLaneZone] | None = None) -> TrackFrame

Resolve space-time overlaps where two vehicles share the same lane position.

Scans each time stamp (and recording, if present) for pairs of vehicles assigned to the same lane whose longitudinal extents overlap (distance of the positions < sum of the half-lengths + 1 m; vehicles without length use conventions.DEFAULT_VEHICLE_LENGTH_M). Each conflicting pair is reassigned to the lane pair (lower pos_lat to the lane with the lower centre) with the smallest total lateral distance to the lane centres.

Before that, vehicles flagged as is_changing_lane at the very start or end of their observation are snapped to the laterally nearest lane centre over these edge segments.

Lane validity: the auxiliary lane (0) is a candidate only for points whose pos_lon lies inside one of aux_lane_zones; outside the zones neither the overlap reassignment nor the edge snapping can choose lane 0. The numbers of conflicts found and resolved are logged.

Parameters:

Name Type Description Default
df TrackFrame

Trajectory samples with id, datum, pos_lon, pos_lat, lane_fixed and is_changing_lane; length [m] and recording are used if present.

required
lane_centers Mapping[int, float]

Lane ID -> median lateral position [m] (from apply_lane_correction).

required
aux_lane_zones Sequence[AuxLaneZone] | None

AuxLaneZone intervals (pos_lon [m]) in which lane 0 may be assigned; None for none (lane 0 is never chosen where other lanes exist).

None

Returns:

Type Description
TrackFrame

A copy of df sorted by time and pos_lon with lane_fixed updated and the boolean column

TrackFrame

lane_conflict_resolved, True on every row whose lane_fixed this function changed (edge snapping and

TrackFrame

overlap reassignment), so that such rows can be filtered downstream.

detect_lane_changes

detect_lane_changes(df_points: TrackFrame, lat_speed_threshold_mps: float = 0.1, alpha: float | None = None, n_cores: int | None = None, frame_rate: float = 30.0, min_displacement_m: float = 1.5, median_kernel_sec: float = 0.167, sewma_halfwidth_sec: float = 0.5, sewma_width_sec: float = SEWMA_WIDTH_DEFAULT_SEC) -> EventFrame

Detect all lane changes and return their start, crossing and end with kinematics and neighbors.

Entry function of page 07 of the pipeline steps 01-10 (docs/pipeline/07_lane_change_detection.md). Requires the columns id, datum, pos_lon [m], pos_lat [m], lane and speed; returns an event table and leaves the tracks unchanged. Inside the pipeline assign_lanes (pages 08 and 09) calls it at the native frame rate; run_pipeline_detailed(...).events is that table, classified and enriched with neighbor attributes. Calling this function on the resampled (10 Hz) output detects the events again on fewer samples and can give slightly different times; use it for standalone data. Method: Thiemann, Treiber & Kesting (2008), Hofinger & Fellendorf (2023).

Example

import trajlab from trajlab.processing.lane_changes import detect_lane_changes raw = trajlab.examples.synthetic_motorway() ref_east, _ = trajlab.estimate_ref_lines(raw) tracks = trajlab.run_pipeline(raw[raw["orientation"] > 0], ref_east) events = detect_lane_changes(tracks, lat_speed_threshold_mps=0.1)

For each vehicle, the lateral speed d pos_lat / dt [m/s] is median-filtered and smoothed with the symmetric exponential kernel of Thiemann, Treiber & Kesting (2008) (SEWMA, width sewma_width_sec). As in Hofinger & Fellendorf (2023), a threshold on the smoothed lateral speed marks the start and the end of a lane change: intervals in which the smoothed lateral speed exceeds lat_speed_threshold_mps and whose lateral displacement exceeds min_displacement_m are accepted. Filter widths are given in seconds and converted to samples with each vehicle's median sampling interval, so the result does not depend on the frame rate.

The defaults reproduce the former behaviour at 30 Hz (threshold 0.003 per pseudo-frame of 1/33.3 s, median kernel 5 samples, SEWMA half-width 15 samples).

Parameters:

Name Type Description Default
df_points TrackFrame

Trajectory samples in the pipeline schema. Needs at least id, datum (time), pos_lon, pos_lat, lane and speed; class, orientation and the neighbour columns (id_front_left, clearance_front, ...) are read if present (missing neighbour columns are NaN).

required
lat_speed_threshold_mps float

Threshold [m/s] on the smoothed lateral speed that marks a lane-change interval.

0.1
alpha float | None

Deprecated per-sample SEWMA decay factor. If given, it is used as is for every vehicle (dependent on the sampling rate) and a DeprecationWarning is emitted; None uses sewma_width_sec.

None
n_cores int | None

Number of worker processes for the per-vehicle detection; None or <= 1 runs sequentially, which is faster here (see the note at the dispatch). Parallelise around whole recordings instead.

None
frame_rate float

Recording frame rate [Hz], used only to express the crossing time as a frame number (frame_lc).

30.0
min_displacement_m float

Minimum lateral displacement [m] over the interval for it to count as a lane change.

1.5
median_kernel_sec float

Width of the median filter [s], rounded to an odd number of samples.

0.167
sewma_halfwidth_sec float

Half-width of the SEWMA kernel [s].

0.5
sewma_width_sec float

Kernel width T of the SEWMA [s]; per vehicle alpha = exp(-dt / T) with its median sampling interval dt. The default (0.3164 s) is the former alpha = 0.9 at 30 Hz.

SEWMA_WIDTH_DEFAULT_SEC

Returns:

Type Description
EventFrame

One row per detected lane change (an empty DataFrame without columns if there is none) with the columns

EventFrame

id, class, lc_direction (+1 left, i.e. towards larger pos_lat and a higher lane ID; -1

EventFrame

right), direction (the vehicle's orientation), frame_lc (crossing time in frames since the

EventFrame

vehicle's first sample), time_start, time_lc, time_end [datetime] (start, peak of the smoothed

EventFrame

lateral speed, end), duration_sec [s], lane_start, lane_end, speed_start, speed_lc,

EventFrame

speed_end (unit of the speed column, km/h in the pipeline), pos_lon_lc [m] and the neighbour

EventFrame

attributes id_*, rel_speed_* (unit of speed), clearance_* [m] and headway_* [m]

EventFrame

(centre distance) of front and rear at the start (*_start, on the target side) and at the end

EventFrame

(*_end, in the own lane).

sewma_filter

sewma_filter(data: ArrayLike, alpha: float = 0.8, window_size: int = 5) -> FloatArray

Smooth a 1-D signal with the symmetric exponentially weighted moving average (SEWMA).

The signal is convolved with an exponentially decaying kernel that is symmetric (causal and anti-causal at the same time). This avoids the phase shift of a one-sided EWMA, so the peaks of the lateral speed during a lane change are not delayed.

The kernel weight at offset k is alpha ** |k|, normalized so the filtered values lie in the same range as the input. This is the symmetric exponential kernel of Thiemann, Treiber & Kesting (2008), exp(-|k| / Delta) with Delta = T / dt samples. alpha is per sample: the same alpha means a different width in seconds at another sampling rate, so the pipeline derives it from a width in seconds (sewma_alpha). Thiemann et al. truncate the kernel at 3 * Delta; here the half-width window_size is set separately.

Parameters:

Name Type Description Default
data ArrayLike

1-D signal values (for example the lateral speed [m/s]).

required
alpha float

Per-sample decay factor, in (0, 1). Higher values give the distant samples more weight (wider kernel, more smoothing).

0.8
window_size int

Half-width of the kernel in samples; the full kernel spans 2 * window_size + 1 samples. It is clamped so that the kernel does not exceed the data length.

5

Returns:

Type Description
FloatArray

The smoothed signal, same length as data (the input as float array if it is empty).

estimate_lane_axis_sign

estimate_lane_axis_sign(df_points: TrackFrame, lane_col: str = C.LANE, lat_col: str = C.POS_LAT) -> int

Determine whether the lateral coordinate grows with the lane index.

Two conventions meet in this package and they are not the same thing. compute_surroundings names a neighbour "left" when it sits at lane + 1 and "right" at lane - 1: a lane-index convention. Manoeuvre detection can only see the lateral coordinate, and whether a vehicle moving towards a larger pos_lat moves towards a larger or a smaller lane index is a property of how the dataset was built, not something either module may assume.

Getting it backwards does not fail loudly. The manoeuvre is still detected and its start and end lanes are still right, because those are read from the lane column. Only the neighbours in the target lane at the start of the manoeuvre are read from the wrong side. On an edge lane that yields NaN; anywhere else it yields the neighbours of the lane the vehicle was moving away from, which looks entirely plausible in the output.

The relation is therefore measured rather than assumed: the sign of the slope of the per-lane median lateral position against the lane index.

Since lane IDs follow conventions (lane 1 rightmost, increasing to the left) and pos_lat > 0 is left of travel, the pipeline itself no longer needs this; the function is kept as a diagnostic, and returns +1 for any output that follows the conventions.

Parameters:

Name Type Description Default
df_points TrackFrame

Trajectory samples with a lane column and a lateral coordinate.

required
lane_col str

Column of the lane index.

LANE
lat_col str

Column of the lateral coordinate [m]. Must be the absolute lateral position, not an offset from the lane centre: an offset has the same median in every lane and carries no slope.

POS_LAT

Returns:

Type Description
int

+1 if the lateral coordinate grows with the lane index, -1 if it falls. Falls back to +1 when a

int

column is missing or fewer than two lanes are present, that being the convention of a lateral axis measured

int

from the right-hand road edge with lane indices counting towards the left.

add_event_neighbors

add_event_neighbors(events: EventFrame, tracks: TrackFrame, *, tolerance_s: float | None = None) -> EventFrame

Add the attributes of the surrounding vehicles at start, crossing and end to the lane-change event table.

Entry function of the event table of page 07 of the pipeline steps 01-10 (docs/pipeline/07_lane_change_detection.md), run after the surroundings of page 10. Requires the event table of assign_lanes (or detect_lane_changes) and tracks with id, datum and, for the attributes, the surroundings columns (compute_surroundings); adds <metric>_<front|rear>_<start|lc|end> for id, rel_speed, clearance [m] and headway [m] (see enrich_events_with_neighbours).

Example

import trajlab from trajlab.processing.events import add_event_neighbors raw = trajlab.examples.synthetic_motorway() ref_east, _ = trajlab.estimate_ref_lines(raw) result = trajlab.run_pipeline_detailed(raw[raw["orientation"] > 0], ref_east) events = add_event_neighbors(result.events, result.tracks, tolerance_s=0.05)

Parameters:

Name Type Description Default
events EventFrame

Event table (id, time_start, time_lc, time_end, lc_direction). Not modified.

required
tracks TrackFrame

Samples with the surroundings columns.

required
tolerance_s float | None

Largest time difference [s] between an event time and the sample used; None uses half the median sampling interval of the tracks (half the output step on a resampled grid).

None

Returns:

Type Description
EventFrame

The event table with the neighbor attributes; an empty or missing table, or empty tracks, unchanged.

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.

resample_to_output_grid

resample_to_output_grid(df: TrackFrame, rate_hz: float | None = 10.0, id_col: str = C.ID, time_col: str = C.TIME, interpolate_columns: Iterable[str] | None = None, nearest_columns: Iterable[str] | None = None, drop_columns: Iterable[str] | None = None) -> TrackFrame

Resample all trajectories onto one common time grid.

The grid is t0 + k / rate_hz with the same t0 for every vehicle: the global minimum timestamp floored to a whole multiple of the grid step (counted from the Unix epoch, so grids of different recordings line up). Each vehicle keeps only the grid points inside its own observed time span; nothing is extrapolated.

  • Continuous columns (CONTINUOUS_COLUMNS: positions, speed, acceleration, UTM coordinates, alignment terms) are interpolated linearly in time.
  • The other columns the pipeline knows (lane IDs, flags, class, length, orientation, IDs of neighbours, ...) take the value of the nearest native sample.
  • Columns the pipeline does not know follow their dtype: floating-point columns are interpolated linearly in time (so e.g. a time_sec column stays consistent with datum); integer, boolean, string, categorical and datetime columns take the nearest native sample. The rule chosen for each unknown column is logged at INFO level.
  • interpolate_columns, nearest_columns and drop_columns override these rules for the named columns.
  • The geometry is rebuilt from utm_x/utm_y when both are present, otherwise it is taken from the nearest native sample (ties go to the earlier sample).
  • Duplicate (vehicle, time) rows are dropped (first kept) with a warning.

Parameters:

Name Type Description Default
df TrackFrame

Trajectory points at the native frame rate. Not modified.

required
rate_hz float | None

Output rate [Hz]; None returns an unchanged copy.

10.0
id_col str

Column of the vehicle ID.

ID
time_col str

Column of the time stamp (naive or tz-aware datetimes).

TIME
interpolate_columns Iterable[str] | None

Columns to interpolate linearly regardless of the rules above (must be numeric).

None
nearest_columns Iterable[str] | None

Columns to take from the nearest native sample.

None
drop_columns Iterable[str] | None

Columns to leave out of the result.

None

Returns:

Type Description
TrackFrame

A new DataFrame (GeoDataFrame if the input is one) with the same columns (minus the dropped ones), one row

TrackFrame

per vehicle and grid point, sorted by [id_col, time_col]. Vehicles whose span contains no grid point

TrackFrame

are dropped with a log message.

Raises:

Type Description
ValueError

If rate_hz is not positive or a column of interpolate_columns is not numeric.

resample_tracks

resample_tracks(tracks: TrackFrame, *, rate_hz: float = 10.0, interpolate_columns: Iterable[str] = (), nearest_columns: Iterable[str] = (), drop_columns: Iterable[str] = (), mp_tracks: Mapping[Hashable, TrackKinematics] | None = None, mp_rate_hz: float = 10.0) -> ResamplingResult

Put all trajectories on one common output grid; take the Montanino & Punzo grid values where they exist.

Entry function of the output grid of page 10 of the pipeline steps 01-10 (docs/pipeline/10_output_grid_surroundings.md). Requires the columns id and datum; numeric columns are interpolated, labels taken from the nearest sample (resample_to_output_grid). With mp_tracks (the KinematicsResult.mp_tracks of reconstruct_kinematics) at the same rate, pos_lon, speed, acceleration and mp_reconstructed come from the reconstruction grid instead of a round trip grid -> native -> grid. The preset drone_hgv_paper keeps the native rate (no resampling).

Example

import trajlab from trajlab.processing.surroundings import resample_tracks raw = trajlab.examples.synthetic_motorway() ref_east, _ = trajlab.estimate_ref_lines(raw) tracks = trajlab.run_pipeline(raw[raw["orientation"] > 0], ref_east) on_grid = resample_tracks(tracks, rate_hz=10.0).tracks

Parameters:

Name Type Description Default
tracks TrackFrame

Samples. Not modified.

required
rate_hz float

Output rate [Hz]. Defaults to 10.0.

10.0
interpolate_columns Iterable[str]

Columns forced to linear interpolation.

()
nearest_columns Iterable[str]

Columns forced to the nearest sample.

()
drop_columns Iterable[str]

Columns dropped.

()
mp_tracks Mapping[Hashable, TrackKinematics] | None

Vehicle ID -> its Montanino & Punzo reconstruction; None or empty for none.

None
mp_rate_hz float

Rate [Hz] of the reconstruction grid; its values are used only if it equals rate_hz. Defaults to 10.0.

10.0

Returns:

Type Description
ResamplingResult

The samples on the output grid and the number of rows taken from the reconstruction grid.

enforce_platoon_consistency

enforce_platoon_consistency(tracks: TrackFrame, *, mp: MontaninoPunzoConfig | None = None, output_rate_hz: float | None = 10.0, default_vehicle_length_m: float = C.DEFAULT_VEHICLE_LENGTH_M, tie_tolerance_m: float = 0.001, direction_consistency_min: float = 0.9) -> PlatoonResult

Apply the platoon consistency of Montanino & Punzo (Eq. 2e/3l), then compute the surroundings again.

Runs after compute_surroundings of page 10 (method on page 05 of the pipeline steps 01-10, docs/pipeline/05_kinematics.md); off in the preset drone_hgv_paper. Requires the columns id, datum, pos_lon [m], speed [km/h], acceleration [m/s^2] and id_front on the output grid at mp.rate_hz; changes pos_lon, speed and acceleration of followers that come closer than mp.h_min_m to their leader and recomputes the surroundings columns. Skipped with a warning on another grid.

Example

from trajlab.processing.kinematics.platoon import enforce_platoon_consistency result = enforce_platoon_consistency(on_grid_with_surroundings, output_rate_hz=10.0) # doctest: +SKIP

Parameters:

Name Type Description Default
tracks TrackFrame

Samples on the output grid with the surroundings. Not modified.

required
mp MontaninoPunzoConfig | None

Montanino & Punzo parameters (h_min_m, rate_hz, the reconstruction parameters); None uses MontaninoPunzoConfig().

None
output_rate_hz float | None

Rate [Hz] of the output grid of tracks. Defaults to 10.0.

10.0
default_vehicle_length_m float

Length [m] of vehicles without a length. Defaults to 4.5.

DEFAULT_VEHICLE_LENGTH_M
tie_tolerance_m float

Tie tolerance [m] of compute_surroundings. Defaults to 0.001.

0.001
direction_consistency_min float

Minimum share (0-1) of vehicles whose pos_lon increases. Defaults to 0.9.

0.9

Returns:

Type Description
PlatoonResult

The samples and the report.

stitch_fragments

stitch_fragments(tracks: TrackFrame, *, stages: Sequence[StitchingStage | Mapping[str, Any]] | Literal['overlap'] | None = PAPER_STAGES, bridge_joints: bool = False, bridge_trim_sec: float = 0.5) -> StitchingResult

Link the fragments of one vehicle into one track and optionally bridge the joints.

Entry function of page 04 of the pipeline steps 01-10 (docs/pipeline/04_stitching_imputation.md). Requires the columns id, datum, pos_lon and pos_lat [m] (project_to_reference_line); class, length and speed are used if present. Rewrites id (one ID per stitched vehicle) and adds fragment_id when the joints are bridged. Method: cascaded one-to-one matching of fragment ends with a constant-velocity prediction (after Wang et al. 2023), joints bridged with cubic Hermite curves.

Example

import trajlab from trajlab.processing.reference_line import project_to_reference_line from trajlab.processing.stitching import stitch_fragments raw = trajlab.examples.synthetic_motorway() ref_east, _ = trajlab.estimate_ref_lines(raw) tracks = project_to_reference_line(raw[raw["orientation"] > 0], ref_east) result = stitch_fragments(tracks) stitched, links = result.tracks, result.links

Parameters:

Name Type Description Default
tracks TrackFrame

Samples of one direction of travel. Not modified.

required
stages Sequence[StitchingStage | Mapping[str, Any]] | Literal['overlap'] | None

Cascade stages (StitchingStage objects or their keyword dicts), "overlap" for overlap_stages() (multi-camera data with overlapping views) or None for the 4 built-in stages (default_stages()). Defaults to PAPER_STAGES (preset drone_hgv_paper).

PAPER_STAGES
bridge_joints bool

Fill the joints of stitched vehicles with cubic Hermite curves (bridge_joints). Defaults to False.

False
bridge_trim_sec float

Time [s] trimmed at each side of a joint before it is bridged. Defaults to 0.5.

0.5

Returns:

Type Description
StitchingResult

The stitched samples and the link records.

bridge_joints

bridge_joints(df: TrackFrame, id_col: str = C.ID, fragment_col: str = 'fragment_id', trim_sec: float = 0.5, fit_sec: float = 0.5, rate_hz: float | None = None, max_bridge_sec: float = 4.0) -> TrackFrame

Join the fragments of each stitched vehicle with cubic Hermite bridges.

Stitching only relabels; time-overlapping fragments of one vehicle (camera seams) then interleave two cameras' samples, and plain concatenation leaves steps at every joint. Per vehicle and joint (fragments in order of their first sample): the last trim_sec of the earlier and the first trim_sec of the later fragment are dropped (spline overshoot at fragment ends), and the joint is filled at rate_hz with a cubic Hermite curve matching position and velocity (linear fits over fit_sec) on both sides, in pos_lon, pos_lat and, if present, utm_x/utm_y (C1). Gaps longer than max_bridge_sec are kept.

Parameters:

Name Type Description Default
df TrackFrame

Stitched points with id_col, fragment_col (original IDs, cascaded_stitching(..., keep_fragment_id=True)), datum and the position columns. Not modified.

required
id_col str

Column of the vehicle ID.

ID
fragment_col str

Column of the original fragment ID.

'fragment_id'
trim_sec float

Time [s] dropped at both fragment ends of a joint.

0.5
fit_sec float

Window [s] of the end-state fits.

0.5
rate_hz float | None

Sampling rate [Hz] of the bridge; None takes the median sampling rate of the fragments (25 Hz if it cannot be determined).

None
max_bridge_sec float

Longest gap [s] that is bridged.

4.0

Returns:

Type Description
TrackFrame

Points sorted by [id_col, datum] with is_bridge (True on bridge samples) and stitch_joint

TrackFrame

(True on the first sample of each bridge). Rows change: trimmed samples are dropped, bridges added.

Raises:

Type Description
KeyError

If fragment_col is missing.

cascaded_stitching

cascaded_stitching(df: TrackFrame, id_col: str = C.ID, exit_zones: Sequence[Mapping[str, float]] | None = None, entry_zones: Sequence[Mapping[str, float]] | None = None, stages: Sequence[StitchingStage | Mapping[str, Any]] | None = None, links_out: list[dict[str, Any]] | None = None, keep_fragment_id: bool = False) -> TrackFrame

Run the kinematic trajectory stitching in cascaded stages.

Parameters:

Name Type Description Default
df TrackFrame

Trajectory points to stitch, as expected by stitch_trajectories.

required
id_col str

Column of the vehicle ID.

ID
exit_zones Sequence[Mapping[str, float]] | None

StitchingStage.exit_zones of every stage (None keeps those of StitchingStage entries).

None
entry_zones Sequence[Mapping[str, float]] | None

StitchingStage.entry_zones of every stage (None keeps those of StitchingStage entries).

None
stages Sequence[StitchingStage | Mapping[str, Any]] | None

StitchingStage objects or their keyword dicts (without the zones), each applied as one stitch_trajectories pass, in order (progressively looser gates as the gap tolerance grows is the usual pattern, but any sequence is accepted). None uses default_stages().

None
links_out list[dict[str, Any]] | None

If a list is passed, the link records of all stages are appended (see stitch_trajectories) with the stage number in stage.

None
keep_fragment_id bool

Keep the original IDs in a column fragment_id (needed by bridge_joints).

False

Returns:

Type Description
TrackFrame

The stitched points (same rows, merged IDs), as returned by the last stitch_trajectories pass.

impute_trajectories

impute_trajectories(df_stitched: TrackFrame, id_col: str = C.ID, fps: int = 30, n_cores: int | None = None, max_gap_sec: float = 3.0) -> TrackFrame

Re-grid each track to a regular frame rate and fill short gaps.

Each vehicle gets a regular grid t0 + k / fps (t0 = the whole second before its first sample), built from integer nanoseconds so that it does not drift. On this grid:

  • Continuous columns (pos_lon, pos_lat, utm_x, utm_y, pos_lat_raw, y_correction, pos_lon_ref) are interpolated per vehicle (PCHIP for three or more samples, else linear).
  • All other columns (orientation, class, length, lane, ...) take the value of the nearest original sample.
  • The geometry is rebuilt per vehicle from utm_x/utm_y if both are present.
  • is_imputed is True for grid points without an original sample within half a frame.
  • Grid points inside a gap longer than max_gap_sec are left out, so the vehicle keeps a gap there.

Imputation only interpolates positions. Any speed/acceleration columns are dropped; kinematics come from Step 3 of the pipeline.

Parameters:

Name Type Description Default
df_stitched TrackFrame

Trajectory points with id_col and datum. Not modified.

required
id_col str

Column of the vehicle ID.

ID
fps int

Target frame rate [Hz].

30
n_cores int | None

Number of worker processes. None or 1 runs sequentially, which is faster for typical recordings (see detect_lane_changes). With n_cores > 1 on Windows the calling script needs an if __name__ == "__main__": guard.

None
max_gap_sec float

Longest gap [s] that is filled.

3.0

Returns:

Type Description
TrackFrame

The re-gridded points with is_imputed (GeoDataFrame for GeoDataFrame input), sorted by

TrackFrame

[id_col, datum].

overlap_stages

overlap_stages(max_overlap_sec: float = 3.0, overlap_max_dx_m: float = 6.0, overlap_max_dy_m: float = 2.0, ambiguity_margin: float = 1.0) -> list[dict[str, float]]

Return the cascade for multi-camera data with overlapping fields of view (I-24 MOTION).

A first stage links only time-overlapping fragments (max_overlap_sec, residuals at common times, speed gate 4 m/s; its gap window is closed), then the four default_stages follow unchanged for all gaps. All stages report ambiguous pairs (ambiguity_margin, m) and do not link them. On the A39 ground truth (hardly any overlaps) a stage 0 that also took gaps up to 1 s with its wider gates cost precision.

Parameters:

Name Type Description Default
max_overlap_sec float

Longest time overlap [s] of the overlap stage.

3.0
overlap_max_dx_m float

Longitudinal gate [m] of the overlap stage.

6.0
overlap_max_dy_m float

Lateral gate [m] of the overlap stage.

2.0
ambiguity_margin float

Cost margin [m] below which an alternative makes a pair ambiguous (all stages).

1.0

Returns:

Type Description
list[dict[str, float]]

Five parameter dicts (StitchingStage keyword arguments).

stitch_trajectories

stitch_trajectories(df: TrackFrame, stage: StitchingStage | None = None, *, id_col: str = C.ID, links_out: list[dict[str, Any]] | None = None) -> TrackFrame

Stitch fragments by kinematic forward projection and one-to-one matching.

Inspired by the fragment-association idea in Wang, Y., Gloudemans, D., Ji, J., Teoh, Z. N., Liu, L., Zachár, G., Barbour, W., & Work, D. (2023). Automatic vehicle trajectory data reconstruction at scale (arXiv:2212.07907), https://doi.org/10.48550/arXiv.2212.07907; implemented as one-to-one bipartite matching with constant-velocity prediction.

The pass runs four stages: the end state of every fragment (tail) and the start state of every fragment (head) outside the exit / entry zones; the gates and costs of every tail-head pair (constant-velocity prediction over a gap, median residuals over a time overlap); the one-to-one assignment with the ambiguity check; and the join of the linked fragments. Linked fragments form connected groups; each group gets the smallest of its IDs (compared as strings). The former flat keyword form (stitch_trajectories(df, max_gap_sec=2.0, ...)) is still accepted.

Parameters:

Name Type Description Default
df TrackFrame

Trajectory points with id_col, datum, pos_lon and pos_lat [m] (pos_lon increasing with travel), optionally speed [km/h], length [m] and class. Not modified.

required
stage StitchingStage | None

Gates and cost weights of the pass. None uses StitchingStage().

None
id_col str

Column of the vehicle ID.

ID
links_out list[dict[str, Any]] | None

If a list is passed, one dict per assigned pair is appended: tail, head, dt [s] (negative = overlap), dx, dy [m] (residuals), dv [m/s], cost, n_alternatives, confidence (exp(-cost^2 / 2) normalised over the admissible alternatives of tail and head, cost in units of base_x_error_m), ambiguous, linked.

None

Returns:

Type Description
TrackFrame

A copy of df sorted by [id_col, datum] in which the IDs of stitched fragments are replaced by one

TrackFrame

common ID per vehicle. The number of rows is unchanged.

Raises:

Type Description
RuntimeError

If the number of rows changed (an internal error; checked also under python -O). Raised by the helper _check_no_data_loss that this function calls at the end.

Step 03, road-edge alignment of the lateral positions (docs/pipeline/03_alignment.md).

Entry function: align_lateral_positions (parameters AlignmentParams), in the module road_edge, which also holds the profile computation align_to_lower_bound.

AlignmentParams dataclass

AlignmentParams(km_step: float = 10.0, smoothing_sigma_m: float = 30.0, quantile: float = 0.05, target_offset_m: float = 2.0, edge_freeze_m: float = 0.0, edge_freeze_bins: int | None = None, profile_classes: Sequence[str] | None = None)

Parameters of the road-edge alignment (align_lateral_positions); defaults of the preset drone_hgv_paper.

Attributes:

Name Type Description
km_step float

Longitudinal bin width of the road-edge profile [m]. Defaults to 10.0.

smoothing_sigma_m float

Gaussian smoothing sigma of the profile [m]. Defaults to 30.0.

quantile float

Quantile (0-1) of pos_lat per bin that defines the right road edge. Defaults to 0.05.

target_offset_m float

Lateral position [m] the road-edge profile is moved to (center of lane 1). Defaults to 2.0.

edge_freeze_m float

Length [m] at each end of the profile frozen to the first interior value; 0 disables the freeze. Defaults to 0.0.

edge_freeze_bins int | None

Legacy setting in bins; overrides edge_freeze_m if set. Defaults to None.

profile_classes Sequence[str] | None

Classes whose positions define the road-edge profile; None uses all rows. Defaults to None.

AlignmentResult dataclass

AlignmentResult(tracks: TrackFrame, edge_profile: DataFrame)

Result of align_lateral_positions.

Attributes:

Name Type Description
tracks TrackFrame

The aligned samples.

edge_profile DataFrame

The lower-bound profile per bin (the second result of align_to_lower_bound).

align_lateral_positions

align_lateral_positions(tracks: TrackFrame, *, params: AlignmentParams | None = None, layout: LaneLayout | None = None, lane_width_m: float = 3.75) -> AlignmentResult

Align the lateral positions to the lower road edge, so that the lanes become horizontal bands.

Entry function of page 03 of the pipeline steps 01-10 (docs/pipeline/03_alignment.md). Requires the columns pos_lon and pos_lat [m] (project_to_reference_line); changes pos_lat and adds pos_lat_raw [m] (before the alignment) and y_correction [m]. Method: the lower-quantile profile of pos_lat along the road, smoothed and subtracted (align_to_lower_bound).

Example

import trajlab from trajlab.processing.alignment import align_lateral_positions from trajlab.processing.reference_line import project_to_reference_line raw = trajlab.examples.synthetic_motorway() ref_east, _ = trajlab.estimate_ref_lines(raw) tracks = project_to_reference_line(raw[raw["orientation"] > 0], ref_east) aligned = align_lateral_positions(tracks).tracks

Parameters:

Name Type Description Default
tracks TrackFrame

Samples of one direction of travel. Not modified.

required
params AlignmentParams | None

Alignment parameters; None uses AlignmentParams().

None
layout LaneLayout | None

Number of main lanes and the zones of the site; None uses LaneLayout() (3 lanes, no zones).

None
lane_width_m float

Lane width [m] used for lane-count zones on the right side. Defaults to 3.75 (the prior lanes.gmm_prior_eta_m of the preset).

3.75

Returns:

Type Description
AlignmentResult

The aligned samples and the road-edge profile.

Align the lateral axis of the projected trajectories to the lower road edge (page 03 of the pipeline steps 01-10).

align_to_lower_bound removes the curvature of the lane bands so that the lanes become horizontal bands with the rightmost main lane (lane 1) near pos_lat = target_offset_m; align_lateral_positions is the entry function of the step, with its parameters in AlignmentParams.

AlignmentParams dataclass

AlignmentParams(km_step: float = 10.0, smoothing_sigma_m: float = 30.0, quantile: float = 0.05, target_offset_m: float = 2.0, edge_freeze_m: float = 0.0, edge_freeze_bins: int | None = None, profile_classes: Sequence[str] | None = None)

Parameters of the road-edge alignment (align_lateral_positions); defaults of the preset drone_hgv_paper.

Attributes:

Name Type Description
km_step float

Longitudinal bin width of the road-edge profile [m]. Defaults to 10.0.

smoothing_sigma_m float

Gaussian smoothing sigma of the profile [m]. Defaults to 30.0.

quantile float

Quantile (0-1) of pos_lat per bin that defines the right road edge. Defaults to 0.05.

target_offset_m float

Lateral position [m] the road-edge profile is moved to (center of lane 1). Defaults to 2.0.

edge_freeze_m float

Length [m] at each end of the profile frozen to the first interior value; 0 disables the freeze. Defaults to 0.0.

edge_freeze_bins int | None

Legacy setting in bins; overrides edge_freeze_m if set. Defaults to None.

profile_classes Sequence[str] | None

Classes whose positions define the road-edge profile; None uses all rows. Defaults to None.

AlignmentResult dataclass

AlignmentResult(tracks: TrackFrame, edge_profile: DataFrame)

Result of align_lateral_positions.

Attributes:

Name Type Description
tracks TrackFrame

The aligned samples.

edge_profile DataFrame

The lower-bound profile per bin (the second result of align_to_lower_bound).

align_to_lower_bound

align_to_lower_bound(df_direction: TrackFrame, km_step: float = 10.0, smoothing_sigma_m: float = 30.0, lon_col: str = C.POS_LON, lat_col: str = C.POS_LAT, quantile: float = 0.05, target_offset_m: float = 2.0, edge_freeze_bins: int = 10, aux_lane_zones: Sequence[AuxLaneZone] | None = None, edge_freeze_m: float | None = None, lane_count_zones: Sequence[LaneCountZone] | None = None, n_main_lanes: int = 3, lane_width_m: float = 3.75, profile_classes: Sequence[str] | None = None) -> tuple[TrackFrame, pd.DataFrame]

Align the lateral coordinates horizontally to the lower road edge.

Corrects for centerline curvature by computing the 5th-percentile (right-most) lateral offset profile along the longitudinal axis, smoothing it with a Gaussian filter, and subtracting this profile from all lateral coordinates. The result is shifted so that the right-most edge sits at y = +2.0 m, which corresponds to the geometric center of the rightmost lane.

This step converts curved, non-horizontal lane bands into parallel, horizontal bands that are independent of road curvature—making downstream GMM lane detection much more reliable.

A boundary freeze is applied to the first and last edge_freeze_m metres (or edge_freeze_bins bins) to avoid edge artifacts from sparse data near the field-of-view boundaries. The freeze also hides real lateral changes of the road edge there, e.g. an exit taper.

Inside auxiliary-lane zones the lowest lateral band is the auxiliary lane, not the right edge of the main carriageway. Bins that overlap a zone are therefore left out of the lower-bound profile, which is interpolated linearly across them (over pos_lon) before smoothing. Without zones the result is unchanged.

Lane-count zones on the right side (side == "right") move the road edge by whole lanes; there the profile is referred back to the cross-section of n_main_lanes lanes (with a linear taper of taper_m), so that lane positions and numbers stay continuous.

Parameters:

Name Type Description Default
df_direction TrackFrame

Samples of a single direction of travel with pos_lon and pos_lat [m].

required
km_step float

Bin width along the longitudinal axis [m] (resolution of the correction profile).

10.0
smoothing_sigma_m float

Standard deviation of the Gaussian smoothing of the profile [m].

30.0
lon_col str

Column of the longitudinal position [m].

POS_LON
lat_col str

Column of the lateral position [m].

POS_LAT
quantile float

Quantile (0-1) of lat_col per bin that defines the lower bound.

0.05
target_offset_m float

Lateral position [m] that the lower bound is moved to (the centre of the rightmost lane).

2.0
edge_freeze_bins int

Number of bins at each end whose profile value is frozen to that of the first interior bin. Applied only when the profile has more than 2 * edge_freeze_bins bins; 0 disables it.

10
aux_lane_zones Sequence[AuxLaneZone] | None

AuxLaneZone intervals (pos_lon [m], widened by one bin) to leave out of the profile; None for none.

None
edge_freeze_m float | None

Length [m] at each end to freeze; overrides edge_freeze_bins (converted with round(edge_freeze_m / km_step)). None uses edge_freeze_bins.

None
lane_count_zones Sequence[LaneCountZone] | None

LaneCountZone intervals (lane gain or drop); only zones on the right side change the profile. None for none.

None
n_main_lanes int

Number of main lanes outside the lane-count zones.

3
lane_width_m float

Lane width [m] used to refer the edge back in lane-count zones.

3.75
profile_classes Sequence[str] | None

Classes whose samples define the profile (e.g. cars, whose positions are not displaced by perspective); the profile is applied to all rows. None (or no class column) uses all samples.

None

Returns:

Type Description
TrackFrame

(df_aligned, lower_bound_profile): a copy of the input with corrected lat_col, the original values

DataFrame

in <lat_col>_raw and the subtracted profile in y_correction [m]; and the profile with the columns

tuple[TrackFrame, DataFrame]

x_bin (bin start [m]), lat_col (lower bound per bin after zones, gap filling and edge freeze [m])

tuple[TrackFrame, DataFrame]

and y_smooth (smoothed profile [m]).

align_lateral_positions

align_lateral_positions(tracks: TrackFrame, *, params: AlignmentParams | None = None, layout: LaneLayout | None = None, lane_width_m: float = 3.75) -> AlignmentResult

Align the lateral positions to the lower road edge, so that the lanes become horizontal bands.

Entry function of page 03 of the pipeline steps 01-10 (docs/pipeline/03_alignment.md). Requires the columns pos_lon and pos_lat [m] (project_to_reference_line); changes pos_lat and adds pos_lat_raw [m] (before the alignment) and y_correction [m]. Method: the lower-quantile profile of pos_lat along the road, smoothed and subtracted (align_to_lower_bound).

Example

import trajlab from trajlab.processing.alignment import align_lateral_positions from trajlab.processing.reference_line import project_to_reference_line raw = trajlab.examples.synthetic_motorway() ref_east, _ = trajlab.estimate_ref_lines(raw) tracks = project_to_reference_line(raw[raw["orientation"] > 0], ref_east) aligned = align_lateral_positions(tracks).tracks

Parameters:

Name Type Description Default
tracks TrackFrame

Samples of one direction of travel. Not modified.

required
params AlignmentParams | None

Alignment parameters; None uses AlignmentParams().

None
layout LaneLayout | None

Number of main lanes and the zones of the site; None uses LaneLayout() (3 lanes, no zones).

None
lane_width_m float

Lane width [m] used for lane-count zones on the right side. Defaults to 3.75 (the prior lanes.gmm_prior_eta_m of the preset).

3.75

Returns:

Type Description
AlignmentResult

The aligned samples and the road-edge profile.

Step 07, the lane-change event table and its attributes (docs/pipeline/07_lane_change_detection.md).

Entry function: add_event_neighbors (the neighbor attributes after the surroundings) in table, which also holds the road-end flag that assign_lanes sets.

add_event_neighbors

add_event_neighbors(events: EventFrame, tracks: TrackFrame, *, tolerance_s: float | None = None) -> EventFrame

Add the attributes of the surrounding vehicles at start, crossing and end to the lane-change event table.

Entry function of the event table of page 07 of the pipeline steps 01-10 (docs/pipeline/07_lane_change_detection.md), run after the surroundings of page 10. Requires the event table of assign_lanes (or detect_lane_changes) and tracks with id, datum and, for the attributes, the surroundings columns (compute_surroundings); adds <metric>_<front|rear>_<start|lc|end> for id, rel_speed, clearance [m] and headway [m] (see enrich_events_with_neighbours).

Example

import trajlab from trajlab.processing.events import add_event_neighbors raw = trajlab.examples.synthetic_motorway() ref_east, _ = trajlab.estimate_ref_lines(raw) result = trajlab.run_pipeline_detailed(raw[raw["orientation"] > 0], ref_east) events = add_event_neighbors(result.events, result.tracks, tolerance_s=0.05)

Parameters:

Name Type Description Default
events EventFrame

Event table (id, time_start, time_lc, time_end, lc_direction). Not modified.

required
tracks TrackFrame

Samples with the surroundings columns.

required
tolerance_s float | None

Largest time difference [s] between an event time and the sample used; None uses half the median sampling interval of the tracks (half the output step on a resampled grid).

None

Returns:

Type Description
EventFrame

The event table with the neighbor attributes; an empty or missing table, or empty tracks, unchanged.

The lane-change event table of step 07: its road-end flag and its neighbour attributes.

flag_near_road_end runs inside assign_lanes at the native frame rate; add_event_neighbors is the entry function that adds the neighbor attributes of the output (after the surroundings, step 10).

flag_near_road_end

flag_near_road_end(events: EventFrame | None, df: TrackFrame, buffer_m: float, road_length_m: float | None) -> EventFrame | None

Add near_road_end to the event table: crossing (or peak) within buffer_m of either road end.

The position is the pos_lon of the vehicle at time_cross (lane changes) or time_lc (excursions), nearest sample of the same vehicle.

Parameters:

Name Type Description Default
events EventFrame | None

Event table (id, time_lc, optionally time_cross); None or empty is returned as is.

required
df TrackFrame

Samples with id, datum and pos_lon [m].

required
buffer_m float

Distance [m] from either end of the road.

required
road_length_m float | None

Length of the road [m] (pos_lon of its end); None (or 0) uses the largest pos_lon.

required

Returns:

Type Description
EventFrame | None

A copy of events with the boolean column near_road_end.

enrich_events_with_neighbours

enrich_events_with_neighbours(events: EventFrame, df: TrackFrame, tolerance_s: float) -> EventFrame

Add neighbour attributes from the (resampled) output to the event table.

For every event the values are taken from the output row of the same vehicle at the grid time nearest to the event time, if that grid time is at most tolerance_s away (otherwise NaN):

  • at time_start: the neighbours in the target lane (*_left for a left manoeuvre, *_right for a right one) -> <metric>_front_start, <metric>_rear_start;
  • at time_lc: the same-lane neighbours -> <metric>_front_lc, <metric>_rear_lc;
  • at time_end: the same-lane neighbours -> <metric>_front_end, <metric>_rear_end.

<metric> is id, rel_speed (km/h), clearance (m) and headway (m).

Parameters:

Name Type Description Default
events EventFrame

Event table from Step 5 (apply_lane_correction or the HMM).

required
df TrackFrame

Output of Step 6 (one row per vehicle and grid time).

required
tolerance_s float

Maximum distance [s] between an event time and the grid time used (half a grid step in the pipeline).

required

Returns:

Type Description
EventFrame

A copy of events with the neighbour columns filled in (unchanged copy if events is empty or df

EventFrame

has no neighbour columns).

add_event_neighbors

add_event_neighbors(events: EventFrame, tracks: TrackFrame, *, tolerance_s: float | None = None) -> EventFrame

Add the attributes of the surrounding vehicles at start, crossing and end to the lane-change event table.

Entry function of the event table of page 07 of the pipeline steps 01-10 (docs/pipeline/07_lane_change_detection.md), run after the surroundings of page 10. Requires the event table of assign_lanes (or detect_lane_changes) and tracks with id, datum and, for the attributes, the surroundings columns (compute_surroundings); adds <metric>_<front|rear>_<start|lc|end> for id, rel_speed, clearance [m] and headway [m] (see enrich_events_with_neighbours).

Example

import trajlab from trajlab.processing.events import add_event_neighbors raw = trajlab.examples.synthetic_motorway() ref_east, _ = trajlab.estimate_ref_lines(raw) result = trajlab.run_pipeline_detailed(raw[raw["orientation"] > 0], ref_east) events = add_event_neighbors(result.events, result.tracks, tolerance_s=0.05)

Parameters:

Name Type Description Default
events EventFrame

Event table (id, time_start, time_lc, time_end, lc_direction). Not modified.

required
tracks TrackFrame

Samples with the surroundings columns.

required
tolerance_s float | None

Largest time difference [s] between an event time and the sample used; None uses half the median sampling interval of the tracks (half the output step on a resampled grid).

None

Returns:

Type Description
EventFrame

The event table with the neighbor attributes; an empty or missing table, or empty tracks, unchanged.

Step 05, kinematic reconstruction and platoon consistency (docs/pipeline/05_kinematics.md).

Entry function: reconstruct_kinematics (parameters KinematicsParams) in track_reconstruction. Modules in run order: spatial_correction (optional), savgol and montanino_punzo (or filters), track_ends; platoon runs after the surroundings of step 10.

KinematicsParams dataclass

KinematicsParams(method: str = 'montanino_punzo', smooth_window_sec: float = 4.0, smooth_window_frames: int | None = None, poly_order: int = 2, max_reversal_m: float = 15.0, lateral_smooth_window_sec: float | None = None, direction_consistency_min: float = 0.9, mp: MontaninoPunzoConfig = MontaninoPunzoConfig(), reconstruction: Mapping[str, Any] | None = None, spatial_correction_profiles: DataFrame | None = None)

Parameters of reconstruct_kinematics; defaults of the preset drone_hgv_paper.

Attributes:

Name Type Description
method str

"montanino_punzo" (Montanino & Punzo for pos_lon) or "savgol" (Savitzky-Golay for both coordinates). Defaults to "montanino_punzo".

smooth_window_sec float

Savitzky-Golay window [s]. Defaults to 4.0.

smooth_window_frames int | None

Explicit window in frames; wins over smooth_window_sec when set. Defaults to None.

poly_order int

Savitzky-Golay polynomial order. Defaults to 2.

max_reversal_m float

Vehicles moving backwards by more than this [m] are dropped. Defaults to 15.0.

lateral_smooth_window_sec float | None

Savitzky-Golay window [s] of pos_lat with montanino_punzo; None uses the longitudinal window. Defaults to None.

direction_consistency_min float

Minimum share (0-1) of vehicles whose pos_lon increases. Defaults to 0.9.

mp MontaninoPunzoConfig

Parameters of the Montanino & Punzo reconstruction (trim_track_ends_sec = 2.0 s as in the preset).

reconstruction Mapping[str, Any] | None

Filter spec that replaces the Montanino & Punzo steps (filters.track_kinematics); None for Montanino & Punzo. Defaults to None.

spatial_correction_profiles DataFrame | None

Profiles of spatial_correction.estimate_spatial_bias to remove a spatially fixed position error first; None for no correction. Defaults to None.

__post_init__

__post_init__() -> None

Check method.

Raises:

Type Description
ValueError

If method is not in KINEMATICS_METHODS.

KinematicsResult dataclass

KinematicsResult(tracks: TrackFrame, mp_tracks: dict[Hashable, TrackKinematics], counters: dict[str, Any], spatial_corrected_share: float | None = None)

Result of reconstruct_kinematics.

Attributes:

Name Type Description
tracks TrackFrame

The samples with smoothed positions, speed [km/h] and acceleration [m/s^2].

mp_tracks dict[Hashable, TrackKinematics]

Vehicle ID -> its Montanino & Punzo reconstruction (TrackKinematics, with the 10 Hz grid values); empty for savgol.

counters dict[str, Any]

Counters of the Montanino & Punzo reconstruction (vehicles, too short, the track-end report); empty for savgol.

spatial_corrected_share float | None

Share of the rows on corrected lanes; None without a spatial correction.

hampel

hampel(x: ArrayLike, window: int = 11, k: float = 4.0, detrend: bool = True) -> tuple[FloatArray, npt.NDArray[np.bool_]]

Replace outliers by the running median (Hampel identifier).

With detrend the values of each window are taken relative to their least-squares linear trend (slope through the window centre) before the median and the MAD, so that a moving vehicle is not flagged.

Parameters:

Name Type Description Default
x ArrayLike

Signal (e.g. positions [m]).

required
window int

Window length [samples] (odd); signals shorter than it are returned unchanged.

11
k float

Threshold in robust standard deviations (1.4826 * MAD, at least 1e-6).

4.0
detrend bool

Remove the local linear trend before the median.

True

Returns:

Type Description
tuple[FloatArray, NDArray[bool_]]

(x_clean, flagged): the cleaned signal and the mask of the replaced samples.

kalman_rts

kalman_rts(z: ArrayLike, dt: float, q: float, sigma_white: float, sigma_ar: float = 0.0, tau_ar: float = 0.0) -> tuple[FloatArray, FloatArray, FloatArray]

Smooth positions with a constant-acceleration Kalman filter and the Rauch-Tung-Striebel smoother.

See the module docstring for the model.

Parameters:

Name Type Description Default
z ArrayLike

Positions [m] on a regular grid.

required
dt float

Grid step [s].

required
q float

Spectral density of the white jerk [m^2/s^5].

required
sigma_white float

Standard deviation of the white measurement noise [m] (at least 1e-4).

required
sigma_ar float

Standard deviation of the AR(1) measurement noise [m]; 0 disables it.

0.0
tau_ar float

Correlation time of the AR(1) noise [s]; 0 disables it.

0.0

Returns:

Type Description
tuple[FloatArray, FloatArray, FloatArray]

(x, v, a): smoothed position [m], speed [m/s] and acceleration [m/s^2].

tv_smooth

tv_smooth(z: ArrayLike, dt: float, lam: float, order: int = 3, iterations: int = 30, eps: float = 0.0001) -> tuple[FloatArray, FloatArray, FloatArray]

Smooth positions with an L1 penalty on a higher difference (total variation, IRLS).

Minimises ||z - x||^2 + lam * sum |D^order x| / dt^(order - 1) by iteratively reweighted least squares (weights 1 / max(|D x|, eps); stops when the positions change by less than 1e-6 m).

Parameters:

Name Type Description Default
z ArrayLike

Positions [m] on a regular grid; tracks of at most order + 2 samples are not smoothed.

required
dt float

Grid step [s].

required
lam float

Penalty weight.

required
order int

Difference order: 3 (piecewise constant acceleration) or 4 (piecewise linear acceleration).

3
iterations int

Maximum number of IRLS iterations.

30
eps float

Lower bound of |D x| in the weights.

0.0001

Returns:

Type Description
FloatArray

(x, v, a): smoothed position [m] and speed [m/s] and acceleration [m/s^2] by centred differences

FloatArray

(np.gradient).

reconstruct_grid

reconstruct_grid(x: ArrayLike, method: Literal['mp', 'rts', 'tv'], dt: float = 0.1, **params: Any) -> tuple[FloatArray, FloatArray, FloatArray]

Reconstruct position, speed and acceleration on the 10-Hz grid with one of the strategies.

Parameters:

Name Type Description Default
x ArrayLike

Positions [m] on the grid.

required
method Literal['mp', 'rts', 'tv']

"mp" (Montanino & Punzo 2015 with the pipeline defaults or params), "rts" (q, sigma_white, optional sigma_ar / tau_ar, hampel_k) or "tv" (lam, order, hampel_k).

required
dt float

Grid step [s].

0.1
**params Any

Parameters of the method; hampel_k (rts, tv) applies the Hampel identifier (11 samples) first.

{}

Returns:

Type Description
tuple[FloatArray, FloatArray, FloatArray]

(x, v, a): position [m], speed [m/s] and acceleration [m/s^2], centred on the grid points.

Raises:

Type Description
ValueError

If method is unknown.

validate_reconstruction_spec

validate_reconstruction_spec(spec: Mapping[str, Any]) -> None

Check a kinematics.reconstruction spec.

Besides method and params / params_by_speed the spec must name the speed bands in which the reconstruction passed the counter-check (admissible_v_bands: list of [lo, hi) in m/s, hi may be None) and the track-edge exclusion that every downstream measure has to apply (edge_s [s]; the start-up transient of the reconstruction at track ends).

Parameters:

Name Type Description Default
spec Mapping[str, Any]

The kinematics.reconstruction mapping.

required

Raises:

Type Description
ValueError

If a mandatory key is missing, edge_s is not a number >= 0 or a speed band is invalid.

compute_reconstruction_flags

compute_reconstruction_flags(frame: TrackFrame, spec: Mapping[str, Any]) -> TrackFrame

Add the flags recon_admissible and recon_edge of a reconstruction spec.

Rows are kept; confirmatory evaluations use admissible rows outside the edges only.

Parameters:

Name Type Description Default
frame TrackFrame

Samples with id, datum and speed [km/h].

required
spec Mapping[str, Any]

Validated kinematics.reconstruction spec (admissible_v_bands [m/s], edge_s [s]).

required

Returns:

Type Description
TrackFrame

A copy of frame with recon_admissible (the vehicle's median speed lies in one of the bands) and

TrackFrame

recon_edge (the row lies within edge_s of its track's first or last sample).

track_kinematics

track_kinematics(times_ns: NDArray[int64], x: FloatArray, spec: Mapping[str, Any], rate_hz: float = 10.0) -> TrackKinematics | None

Reconstruct one track like montanino_punzo.mp_track_kinematics, but with the strategy spec.

The native positions are averaged onto the grid, reconstructed there, and mapped back to the native time stamps (monotone cubic interpolation; linear extrapolation with the end speeds outside the grid).

Parameters:

Name Type Description Default
times_ns NDArray[int64]

Sample times [ns].

required
x FloatArray

Longitudinal positions [m].

required
spec Mapping[str, Any]

{"method": "tv" | "rts", "params": {...}} or with "params_by_speed" (chosen by the median grid speed [m/s]).

required
rate_hz float

Grid rate [Hz].

10.0

Returns:

Type Description
TrackKinematics | None

A TrackKinematics (no reconstruction counters, reconstructed all False), or None for tracks shorter

TrackKinematics | None

than 2 s on the grid.

trim_track_ends

trim_track_ends(df: TrackFrame, max_depth_s: float, a_min: float, a_max: float) -> tuple[TrackFrame, dict[str, int]]

Cut the track ends whose acceleration Step 1 of Montanino & Punzo left outside its outlier bounds.

Step 1 never moves the first or last position of a track (the spline needs reference points on both sides), so outliers at the track ends stay in the output. Per track and end, all rows up to and including the deepest row within max_depth_s of that end whose acceleration lies outside [a_min, a_max] are removed; tracks without such rows are unchanged. Interior rows are never touched.

Parameters:

Name Type Description Default
df TrackFrame

Samples with id, datum and acceleration [m/s^2].

required
max_depth_s float

Depth [s] from each track end that is searched.

required
a_min float

Lower acceleration bound [m/s^2] (Step 1 deceleration threshold).

required
a_max float

Upper acceleration bound [m/s^2] (Step 1 acceleration threshold).

required

Returns:

Type Description
TrackFrame

(df, report): the remaining rows (original order and index) and rows_removed, ends_cut,

dict[str, int]

tracks_removed.

trim_track_ends_fixed

trim_track_ends_fixed(df: TrackFrame, cut_s: float) -> TrackFrame

Drop a fixed time at both ends of every track (the start-up transient of a reconstruction).

Parameters:

Name Type Description Default
df TrackFrame

Samples with id and datum (a TrackFrame).

required
cut_s float

Time [s] removed at each track end.

required

Returns:

Type Description
TrackFrame

The rows at least cut_s from both ends of their track (original order and index); tracks shorter than

TrackFrame

2 * cut_s vanish.

reconstruct_kinematics

reconstruct_kinematics(tracks: TrackFrame, *, params: KinematicsParams | None = None) -> KinematicsResult

Smooth the positions and derive speed [km/h] and acceleration [m/s^2] per vehicle.

Entry function of page 05 of the pipeline steps 01-10 (docs/pipeline/05_kinematics.md). Requires the columns id, datum, pos_lon and pos_lat [m] (project_to_reference_line); smooths pos_lon and pos_lat and adds speed [km/h], acceleration [m/s^2] and, with Montanino & Punzo, mp_reconstructed [bool]. Vehicles moving backwards by more than max_reversal_m are dropped. Method: Montanino & Punzo (2013, 2015) for pos_lon, Savitzky-Golay (1964) for pos_lat (and for both with method="savgol").

Example

import trajlab from trajlab.processing.kinematics import KinematicsParams, reconstruct_kinematics from trajlab.processing.reference_line import project_to_reference_line raw = trajlab.examples.synthetic_motorway() ref_east, _ = trajlab.estimate_ref_lines(raw) tracks = project_to_reference_line(raw[raw["orientation"] > 0], ref_east) smoothed = reconstruct_kinematics(tracks, params=KinematicsParams(method="savgol")).tracks

Parameters:

Name Type Description Default
tracks TrackFrame

Samples of one direction of travel (a DataFrame or a GeoDataFrame). Not modified.

required
params KinematicsParams | None

Parameters; None uses KinematicsParams().

None

Returns:

Type Description
KinematicsResult

The tracks, the per-vehicle Montanino & Punzo results and the counters.

Reconstruct longitudinal trajectories with strategies next to the Montanino & Punzo (2015) chain.

The Montanino & Punzo chain (montanino_punzo) is unchanged and stays the default.

All strategies work like montanino_punzo.mp_track_kinematics: the native positions are averaged onto the 10-Hz grid (mp_bin_to_grid), reconstructed there, and position, speed and acceleration are returned on the grid.

  • hampel: robust pre-processing; samples whose deviation from the running median exceeds k robust standard deviations (MAD) are replaced by the running median (Hampel identifier; Pearson 2002).
  • kalman_rts: Kalman filter with a constant-acceleration model driven by white jerk (process noise spectral density q in m2/s5) and the Rauch-Tung-Striebel smoother (Rauch, Tung & Striebel 1965). The measurement noise is white (sigma_white) plus, optionally, a first-order autoregressive (coloured) component (sigma_ar, tau_ar) carried as an extra state, so that slowly wandering position errors are not taken for motion.
  • tv_smooth: least squares with an L1 penalty on the third (order=3: piecewise constant acceleration) or fourth difference (order=4: piecewise linear acceleration) of the position, solved by iteratively reweighted least squares; it keeps sharp braking onsets that a low-pass filter smears (total-variation regularisation; Rudin, Osher & Fatemi 1992; Chartrand 2011 for differentiation).
  • reconstruct_grid: one entry point for mp (Montanino & Punzo), rts and tv on a 10-Hz position series, returning (x, v, a).

Parameters of rts / tv are chosen per dataset only by the synthetic recovery test (analysis.quality.recovery) with the measured noise model (rule fixed before the evaluation).

hampel

hampel(x: ArrayLike, window: int = 11, k: float = 4.0, detrend: bool = True) -> tuple[FloatArray, npt.NDArray[np.bool_]]

Replace outliers by the running median (Hampel identifier).

With detrend the values of each window are taken relative to their least-squares linear trend (slope through the window centre) before the median and the MAD, so that a moving vehicle is not flagged.

Parameters:

Name Type Description Default
x ArrayLike

Signal (e.g. positions [m]).

required
window int

Window length [samples] (odd); signals shorter than it are returned unchanged.

11
k float

Threshold in robust standard deviations (1.4826 * MAD, at least 1e-6).

4.0
detrend bool

Remove the local linear trend before the median.

True

Returns:

Type Description
tuple[FloatArray, NDArray[bool_]]

(x_clean, flagged): the cleaned signal and the mask of the replaced samples.

kalman_rts

kalman_rts(z: ArrayLike, dt: float, q: float, sigma_white: float, sigma_ar: float = 0.0, tau_ar: float = 0.0) -> tuple[FloatArray, FloatArray, FloatArray]

Smooth positions with a constant-acceleration Kalman filter and the Rauch-Tung-Striebel smoother.

See the module docstring for the model.

Parameters:

Name Type Description Default
z ArrayLike

Positions [m] on a regular grid.

required
dt float

Grid step [s].

required
q float

Spectral density of the white jerk [m^2/s^5].

required
sigma_white float

Standard deviation of the white measurement noise [m] (at least 1e-4).

required
sigma_ar float

Standard deviation of the AR(1) measurement noise [m]; 0 disables it.

0.0
tau_ar float

Correlation time of the AR(1) noise [s]; 0 disables it.

0.0

Returns:

Type Description
tuple[FloatArray, FloatArray, FloatArray]

(x, v, a): smoothed position [m], speed [m/s] and acceleration [m/s^2].

tv_smooth

tv_smooth(z: ArrayLike, dt: float, lam: float, order: int = 3, iterations: int = 30, eps: float = 0.0001) -> tuple[FloatArray, FloatArray, FloatArray]

Smooth positions with an L1 penalty on a higher difference (total variation, IRLS).

Minimises ||z - x||^2 + lam * sum |D^order x| / dt^(order - 1) by iteratively reweighted least squares (weights 1 / max(|D x|, eps); stops when the positions change by less than 1e-6 m).

Parameters:

Name Type Description Default
z ArrayLike

Positions [m] on a regular grid; tracks of at most order + 2 samples are not smoothed.

required
dt float

Grid step [s].

required
lam float

Penalty weight.

required
order int

Difference order: 3 (piecewise constant acceleration) or 4 (piecewise linear acceleration).

3
iterations int

Maximum number of IRLS iterations.

30
eps float

Lower bound of |D x| in the weights.

0.0001

Returns:

Type Description
FloatArray

(x, v, a): smoothed position [m] and speed [m/s] and acceleration [m/s^2] by centred differences

FloatArray

(np.gradient).

reconstruct_grid

reconstruct_grid(x: ArrayLike, method: Literal['mp', 'rts', 'tv'], dt: float = 0.1, **params: Any) -> tuple[FloatArray, FloatArray, FloatArray]

Reconstruct position, speed and acceleration on the 10-Hz grid with one of the strategies.

Parameters:

Name Type Description Default
x ArrayLike

Positions [m] on the grid.

required
method Literal['mp', 'rts', 'tv']

"mp" (Montanino & Punzo 2015 with the pipeline defaults or params), "rts" (q, sigma_white, optional sigma_ar / tau_ar, hampel_k) or "tv" (lam, order, hampel_k).

required
dt float

Grid step [s].

0.1
**params Any

Parameters of the method; hampel_k (rts, tv) applies the Hampel identifier (11 samples) first.

{}

Returns:

Type Description
tuple[FloatArray, FloatArray, FloatArray]

(x, v, a): position [m], speed [m/s] and acceleration [m/s^2], centred on the grid points.

Raises:

Type Description
ValueError

If method is unknown.

validate_reconstruction_spec

validate_reconstruction_spec(spec: Mapping[str, Any]) -> None

Check a kinematics.reconstruction spec.

Besides method and params / params_by_speed the spec must name the speed bands in which the reconstruction passed the counter-check (admissible_v_bands: list of [lo, hi) in m/s, hi may be None) and the track-edge exclusion that every downstream measure has to apply (edge_s [s]; the start-up transient of the reconstruction at track ends).

Parameters:

Name Type Description Default
spec Mapping[str, Any]

The kinematics.reconstruction mapping.

required

Raises:

Type Description
ValueError

If a mandatory key is missing, edge_s is not a number >= 0 or a speed band is invalid.

compute_reconstruction_flags

compute_reconstruction_flags(frame: TrackFrame, spec: Mapping[str, Any]) -> TrackFrame

Add the flags recon_admissible and recon_edge of a reconstruction spec.

Rows are kept; confirmatory evaluations use admissible rows outside the edges only.

Parameters:

Name Type Description Default
frame TrackFrame

Samples with id, datum and speed [km/h].

required
spec Mapping[str, Any]

Validated kinematics.reconstruction spec (admissible_v_bands [m/s], edge_s [s]).

required

Returns:

Type Description
TrackFrame

A copy of frame with recon_admissible (the vehicle's median speed lies in one of the bands) and

TrackFrame

recon_edge (the row lies within edge_s of its track's first or last sample).

track_kinematics

track_kinematics(times_ns: NDArray[int64], x: FloatArray, spec: Mapping[str, Any], rate_hz: float = 10.0) -> TrackKinematics | None

Reconstruct one track like montanino_punzo.mp_track_kinematics, but with the strategy spec.

The native positions are averaged onto the grid, reconstructed there, and mapped back to the native time stamps (monotone cubic interpolation; linear extrapolation with the end speeds outside the grid).

Parameters:

Name Type Description Default
times_ns NDArray[int64]

Sample times [ns].

required
x FloatArray

Longitudinal positions [m].

required
spec Mapping[str, Any]

{"method": "tv" | "rts", "params": {...}} or with "params_by_speed" (chosen by the median grid speed [m/s]).

required
rate_hz float

Grid rate [Hz].

10.0

Returns:

Type Description
TrackKinematics | None

A TrackKinematics (no reconstruction counters, reconstructed all False), or None for tracks shorter

TrackKinematics | None

than 2 s on the grid.

Reconstruct longitudinal trajectories with the multistep method of Montanino & Punzo (Step 3 montanino_punzo).

The method is from Montanino, M., & Punzo, V. (2013). Making NGSIM data usable for studies on traffic flow theory: Multistep method for vehicle trajectory reconstruction. Transportation Research Record, 2390, 99-111, https://doi.org/10.3141/2390-11. Section and equation numbers below refer to its extended version, whose Step 3 adds the platoon consistency constraints: Montanino, M., & Punzo, V. (2015). Trajectory data reconstruction and simulation-based validation against macroscopic traffic patterns. Transportation Research Part B, 80, 82-106 (Section 2), https://doi.org/10.1016/j.trb.2015.06.010.

The method works on the longitudinal position only, sampled every dt = 0.1 s. Speeds and accelerations are backward differences (Eq. 1): v(t) = (x(t) - x(t-1)) / dt and a(t) = (v(t) - v(t-1)) / dt.

  1. mp_remove_outliers (Sec. 2.1): positions whose acceleration proxy exceeds +5 / -8 m/s^2 are replaced by a natural cubic spline through 10 reference points before and 10 after (1 s each). Working on positions keeps the distance travelled.
  2. mp_lowpass_speed (Sec. 2.2): Butterworth low-pass (order 1) on the speed profile. The paper uses a 1 Hz cut-off; the default here is 0.5 Hz (at 1 Hz many 1 s windows of drone data keep more than one jerk sign inversion), as in MontaninoPunzoConfig.
  3. mp_find_reconstruction_window + mp_reconstruct_window (Sec. 2.3.2): where a(t*) leaves [-3, 2] m/s^2, the window end k* is found from the compatibility cone (Eq. 2), and the speeds in the window are replaced by a 5th-degree polynomial that minimises the largest acceleration subject to the constraints of Eq. 3. If no feasible polynomial exists, the window is enlarged to the next compatible end.
  4. Step 2's filter again (Sec. 2.4).

reconstruct_vehicle runs the four steps for one vehicle and reconstruct_track a native track on the 10 Hz grid, both with the parameters of a MontaninoPunzoConfig.

Array conventions used throughout: x[i] is the position at t_i = t_0 + i * dt; v[i] (i >= 1) is the mean speed between t_{i-1} and t_i; a[i] (i >= 2) is the acceleration proxy between v[i-1] and v[i]. v[0], a[0] and a[1] are NaN.

Deviations from the paper are marked "DEVIATION" in the comments and listed in the docstrings.

WindowResult dataclass

WindowResult(ok: bool, speeds: FloatArray | None = None, max_abs_accel: float = np.nan, reason: str = '', jerk_inversions: int = 0)

Outcome of one Eq. 3 reconstruction.

Attributes:

Name Type Description
ok bool

Whether a feasible polynomial was found.

speeds FloatArray | None

The reconstructed speeds [m/s] at the indices t*-1 .. t*+k* (None if not ok).

max_abs_accel float

Largest absolute acceleration proxy [m/s^2] of the reconstructed speeds.

reason str

Why the window failed (empty if ok).

jerk_inversions int

Largest number of jerk sign inversions in a rolling window (Eq. 3j).

VehicleReconstruction dataclass

VehicleReconstruction(x: FloatArray, v: FloatArray, a: FloatArray, outlier_changed: NDArray[bool_], window_changed: NDArray[bool_], counters: dict[str, int] = dict())

Result of reconstruct_vehicle at the reconstruction rate.

Attributes:

Name Type Description
x FloatArray

Reconstructed positions [m].

v FloatArray

Eq. 1 speeds [m/s] (v[0] NaN).

a FloatArray

Eq. 1 acceleration proxies [m/s^2] (a[0], a[1] NaN).

outlier_changed NDArray[bool_]

Positions replaced by Step 1.

window_changed NDArray[bool_]

Samples inside windows reconstructed by Step 3.

counters dict[str, int]

outlier_positions, windows, windows_enlarged, windows_failed.

TrackKinematics dataclass

TrackKinematics(pos_lon: FloatArray, speed_mps: FloatArray, acceleration: FloatArray, reconstructed: NDArray[bool_], counters: dict[str, int] = dict(), grid_ns: NDArray[int64] | None = None, grid_pos_lon: FloatArray | None = None, grid_speed_mps: FloatArray | None = None, grid_acceleration: FloatArray | None = None, grid_reconstructed: NDArray[bool_] | None = None)

MP result of one vehicle, on its native time stamps and on the reconstruction grid.

Attributes:

Name Type Description
pos_lon FloatArray

Position [m] at the native time stamps; used by Steps 4-5.

speed_mps FloatArray

Speed [m/s] at the native time stamps.

acceleration FloatArray

Acceleration [m/s^2] at the native time stamps.

reconstructed NDArray[bool_]

Per native sample: its nearest grid point was changed by Step 1 or Step 3.

counters dict[str, int]

Step counters of reconstruct_vehicle.

grid_ns NDArray[int64] | None

Reconstruction grid (int64 ns since the epoch, whole multiples of 1 / rate_hz, like the output grid).

grid_pos_lon FloatArray | None

Reconstructed position [m] on grid_ns.

grid_speed_mps FloatArray | None

Speed [m/s] on grid_ns (Eq. 1 differences centred on the grid points).

grid_acceleration FloatArray | None

Acceleration [m/s^2] on grid_ns (centred like the speed).

grid_reconstructed NDArray[bool_] | None

Per grid point: changed by Step 1 or Step 3. The pipeline writes the grid values into the output when the output grid has the same rate.

mp_speed_acceleration

mp_speed_acceleration(x: ArrayLike, dt: float) -> tuple[FloatArray, FloatArray]

Return the backward-difference speed and acceleration proxy (Eq. 1).

Parameters:

Name Type Description Default
x ArrayLike

Positions [m] at constant spacing dt.

required
dt float

Sampling interval [s].

required

Returns:

Type Description
tuple[FloatArray, FloatArray]

(v, a): arrays of the length of x [m/s], [m/s^2]; v[0], a[0] and a[1] are NaN.

mp_remove_outliers

mp_remove_outliers(x: ArrayLike, dt: float = 0.1, accel_max: float = 5.0, decel_min: float = -8.0, n_reference: int = 10, max_iterations: int = 10) -> tuple[FloatArray, npt.NDArray[np.bool_]]

Replace positions that cause extreme accelerations (Step 1, Sec. 2.1).

Samples with a > accel_max or a < decel_min are outliers. Each run of outliers is replaced on the positions by a natural cubic spline through n_reference positions before and after the run (1 s each at 10 Hz); the reference positions themselves are kept, so the distance travelled between them is unchanged. As in the paper, no constraint is imposed on the replacement, so physical accelerations are not guaranteed here. The search is repeated (up to max_iterations) because a replacement can move an outlier to a neighbouring sample.

For an outlier run on a[i0..i1] the positions x[i0-1 .. i1-1] are replaced: they are the positions shared by all accelerations of the run (a[i] uses x[i-2..i]). DEVIATION: the paper does not specify which positions belong to an outlier run; at the track ends fewer than n_reference points are used if not available (at least 2), and runs touching the first or last position are left as they are.

Parameters:

Name Type Description Default
x ArrayLike

Positions [m] at constant spacing dt.

required
dt float

Sampling interval [s].

0.1
accel_max float

Acceleration threshold [m/s^2].

5.0
decel_min float

Deceleration threshold [m/s^2] (negative).

-8.0
n_reference int

Reference points on each side.

10
max_iterations int

Maximum number of detect-and-replace passes.

10

Returns:

Type Description
tuple[FloatArray, NDArray[bool_]]

(x_new, changed): the corrected positions [m] and a boolean mask of the replaced positions.

mp_lowpass_speed

mp_lowpass_speed(v: ArrayLike, fs_hz: float = 10.0, cutoff_hz: float = 0.5, order: int = 1, zero_phase: bool = True, padlen_s: float | None = None, edge_method: Literal['pad', 'gust'] = 'pad') -> FloatArray

Low-pass filter the speed profile with a Butterworth filter (Steps 2 and 4).

The paper uses a Butterworth filter of order 1 with a 1 Hz cut-off and notes that it does not alter the integral of the signal (the distance travelled), which is why it is applied to the speed. DEVIATION: the default cut-off is 0.5 Hz (see above), as in MontaninoPunzoConfig; pass cutoff_hz=1.0 for the paper value.

DEVIATION / AMBIGUITY: the paper does not say whether the filter is causal or zero-phase. zero_phase=True (default) applies it forwards and backwards (scipy.signal.sosfiltfilt): no time lag, but the magnitude response is applied twice (squared), i.e. the effective cut-off is lower than cutoff_hz. zero_phase=False applies it once (causal, with a time lag).

The sum of the filtered speeds equals the sum of the input speeds (see the DEVIATION note in the code), so the distance travelled is kept.

Parameters:

Name Type Description Default
v ArrayLike

Speeds [m/s] at rate fs_hz; NaN entries are filled by linear interpolation (constant beyond the ends) before filtering.

required
fs_hz float

Sampling rate [Hz].

10.0
cutoff_hz float

Cut-off frequency [Hz] (paper: 1.0; default 0.5).

0.5
order int

Filter order.

1
zero_phase bool

Zero-phase (True) or causal (False) filtering.

True
padlen_s float | None

Zero-phase "pad" only: odd extension at both ends [s]. None uses 3 * (2 * n_sections + 1) samples (at most the track length - 1).

None
edge_method Literal['pad', 'gust']

Zero-phase only: "pad" (odd extension, sosfiltfilt) or "gust" (Gustafsson's initial conditions, filtfilt(method="gust"): no extension pivoting on the noisy end sample).

'pad'

Returns:

Type Description
FloatArray

The filtered speeds [m/s] (same length; NaN where the input was NaN; a copy of the input with fewer than 2

FloatArray

valid values).

mp_find_reconstruction_window

mp_find_reconstruction_window(v: FloatArray, t_star: int, dt: float = 0.1, a_min: float = -3.0, a_max: float = 2.0, c: int = 5, start_j: int = 1, spacing_ok: NDArray[bool_] | None = None, max_j: int | None = None) -> int | None

Find the end of the reconstruction window (Eq. 2).

Returns the smallest j >= start_j such that

  • (c) v[t*+j] lies in the compatibility cone drawn from v[t*-1]: a_min <= (v[t*+j] - v[t*-1]) / (dt (j+1)) <= a_max;
  • (d) each of the c following speeds lies in the cone drawn from v[t*+j]: a_min <= (v[t*+j+m] - v[t*+j]) / (dt m) <= a_max for m = 1..c;
  • (e) the spacing to the leader is at least h_min for k = j..j+c (passed in as spacing_ok; platoon post-pass).

DEVIATION / AMBIGUITY: Eq. 2 as printed averages a from t*+1 and divides by B - A; we follow the prose and Fig. 6a of the paper, which draw the first cone from v(t*-1) and require each of the c following speeds to lie in the cone from v(t*+j). Near the end of the track fewer than c look-ahead values are used, but at least one sample after the window end must exist (for constraint 3h).

Parameters:

Name Type Description Default
v FloatArray

Speeds (Eq. 1) [m/s].

required
t_star int

Index of the first acceleration outside [a_min, a_max].

required
dt float

Sampling interval [s].

0.1
a_min float

Lower bound of the acceleration proxy [m/s^2] (paper: -3).

-3.0
a_max float

Upper bound of the acceleration proxy [m/s^2] (paper: 2).

2.0
c int

Number of look-ahead samples (paper: 5).

5
start_j int

Smallest j to consider (to enlarge a window).

1
spacing_ok NDArray[bool_] | None

Boolean array, True where the spacing to the leader is at least h_min; None without a platoon constraint.

None
max_j int | None

Largest j to consider (the caller rejects longer windows anyway); None searches to the end of the track. Bounding it keeps the search O(max_j) instead of O(track length) per violation.

None

Returns:

Type Description
int | None

k* (offset from t_star) or None if no compatible end exists.

mp_reconstruct_window

mp_reconstruct_window(x: FloatArray, v: FloatArray, a: FloatArray, t_star: int, k_star: int, dt: float = 0.1, a_rec_min: float = -5.0, a_rec_max: float = 3.0, phi: float = 1.0, max_jerk_inversions: int = 1, jerk_window: int = 10, leader_x: FloatArray | None = None, spacing_offset: FloatArray | None = None, h_min: float = 1.0) -> WindowResult

Replace the speeds in one window by a constrained 5th-degree polynomial (Eq. 3).

The speeds v_rec(t) for t = t*-1 .. t*+k* are the values of a 5th-degree polynomial f(t; beta) (3c) that minimises max |a_rec(t)| with a_rec(t) = (f(t) - f(t-1)) / dt (3a, 3b), subject to

  • (d) v_rec >= 0;
  • (e, f) f(t*-1) = v(t*-1) and f(t*+k*) = v(t*+k*);
  • (g, h) |f'(t*-1) - a(t*-1)| <= phi and |f'(t*+k*) - a(t*+k*+1)| <= phi;
  • (i) a_rec_min <= f'(t) <= a_rec_max and a_rec_min <= a_rec(t) <= a_rec_max at every sample of the window (the formula bounds f', the text the acceleration proxy; both are imposed);
  • (j) at most max_jerk_inversions sign inversions of f'' in any window of jerk_window samples (checked after the solve, since it is not smooth: a violation counts as infeasible);
  • (k) dt * sum(v_rec(t*..t*+k*)) = x(t*+k*) - x(t*-1) (internal consistency);
  • (l) optional platoon consistency (platoon post-pass): leader_x(t) - x_rec(t) - spacing_offset(t) >= h_min in the window.

All constraints and the objective are linear in beta; the min-max objective uses the epigraph form (extra variable z >= |a_rec|, minimise z) and is solved with SLSQP. Infeasible windows are rejected before the solve by necessary conditions at the window ends and by a linear-programming feasibility check.

DEVIATION: (l) is written with centre positions, so spacing_offset is (L_lead + L) / 2 instead of the leader length in the paper (which uses front-bumper positions).

Parameters:

Name Type Description Default
x FloatArray

Positions [m] of the whole track (Eq. 1 conventions).

required
v FloatArray

Speeds [m/s] of the whole track.

required
a FloatArray

Acceleration proxies [m/s^2] of the whole track.

required
t_star int

Index of the first unphysical acceleration (>= 3).

required
k_star int

Window length from mp_find_reconstruction_window.

required
dt float

Sampling interval [s].

0.1
a_rec_min float

Lower bound of 3i [m/s^2] (paper: -5).

-5.0
a_rec_max float

Upper bound of 3i [m/s^2] (paper: 3).

3.0
phi float

Relaxation of the acceleration continuity [m/s^2] (paper: 1).

1.0
max_jerk_inversions int

D in 3j (paper: 1).

1
jerk_window int

Z of constraint 3j, the jerk window [samples] (10 = 1 s at 10 Hz).

10
leader_x FloatArray | None

Leader positions [m] aligned with x (NaN = no leader); None without a platoon constraint.

None
spacing_offset FloatArray | None

(L_lead + L) / 2 [m] aligned with x; needed with leader_x.

None
h_min float

Minimum spacing [m] (paper: 1).

1.0

Returns:

Type Description
WindowResult

A WindowResult with the new speeds for t*-1 .. t*+k*, or ok = False with the reason.

reconstruct_constrained_windows

reconstruct_constrained_windows(x: ArrayLike, config: MontaninoPunzoConfig, *, dt: float | None = None, leader_x: FloatArray | None = None, spacing_offset: FloatArray | None = None, vehicle_id: Hashable | None = None, counters: dict[str, int] | None = None) -> tuple[FloatArray, npt.NDArray[np.bool_]]

Run Step 3 (Sec. 2.3.2) on its own: scan the track and reconstruct every unphysical window.

Starting at the first sample whose acceleration proxy leaves [window_a_min_mps2, window_a_max_mps2], the window end is searched with Eq. 2 and the speeds are replaced with Eq. 3; an infeasible window is enlarged to the next compatible end (up to max_window_sec, otherwise it is left as it is). Scanning continues after the window.

With leader_x/spacing_offset the platoon constraints Eq. 2e and Eq. 3l are added (platoon post-pass). As in the paper, only windows triggered by an unphysical acceleration are reconstructed; a negative spacing elsewhere is not a trigger.

Parameters:

Name Type Description Default
x ArrayLike

Positions [m] at spacing dt.

required
config MontaninoPunzoConfig

Reconstruction parameters; Step 3 uses the Eq. 2 and Eq. 3 bounds (window_*, rec_*, phi_mps2, max_jerk_inversions, jerk_window_sec), max_window_sec and h_min_m.

required
dt float | None

Sampling interval [s]; None uses 1 / config.rate_hz.

None
leader_x FloatArray | None

Leader positions [m] aligned with x (NaN = no leader); None without platoon constraint.

None
spacing_offset FloatArray | None

(L_lead + L) / 2 [m] aligned with x; needed with leader_x.

None
vehicle_id Hashable | None

Only used in log messages.

None
counters dict[str, int] | None

Dict whose windows, windows_enlarged and windows_failed entries are incremented (created if missing); None uses a private dict.

None

Returns:

Type Description
tuple[FloatArray, NDArray[bool_]]

(x_new, window_changed): the positions [m] and the mask of the samples inside reconstructed windows.

reconstruct_vehicle

reconstruct_vehicle(x: ArrayLike, config: MontaninoPunzoConfig, *, dt: float | None = None, leader_x: FloatArray | None = None, spacing_offset: FloatArray | None = None, vehicle_id: Hashable | None = None) -> VehicleReconstruction

Run Steps 1-4 of the reconstruction for one vehicle.

DEVIATION: config.max_window_sec limits the reconstruction window; the paper sets no limit.

Parameters:

Name Type Description Default
x ArrayLike

Longitudinal positions [m] at constant spacing dt.

required
config MontaninoPunzoConfig

Reconstruction parameters (Step 1 outlier_*, Steps 2/4 lowpass_*, filter_* and edge_method, Step 3 as in reconstruct_constrained_windows); platoon_consistency and the track-end trimming are not used here.

required
dt float | None

Sampling interval [s] (0.1 s in the paper); None uses 1 / config.rate_hz.

None
leader_x FloatArray | None

Leader positions [m] aligned with x for the optional platoon constraint; None for none.

None
spacing_offset FloatArray | None

(L_lead + L) / 2 [m] aligned with x.

None
vehicle_id Hashable | None

Only used in log messages.

None

Returns:

Type Description
VehicleReconstruction

A VehicleReconstruction with positions, Eq. 1 speeds and accelerations, masks of the positions changed

VehicleReconstruction

by Step 1 and by Step 3, and counters (outlier_positions, windows, windows_enlarged,

VehicleReconstruction

windows_failed).

mp_bin_to_grid

mp_bin_to_grid(times_ns: NDArray[int64], x: FloatArray, rate_hz: float = 10.0) -> tuple[npt.NDArray[np.int64], FloatArray]

Average the native samples within bins centred on the common grid k / rate_hz.

DEVIATION from running the method at the native rate (see the module docstring of the pipeline integration): the paper's thresholds refer to dt = 0.1 s; at 30 Hz the position noise would turn into acceleration noise about nine times larger. The bin average also acts as an anti-aliasing filter. The grid is anchored at whole multiples of the step (counted from the Unix epoch), like the output grid. Bins at the track ends that hold fewer samples than a full bin, or whose samples lie one-sided (mean sample time more than 10 % of the step away from the grid point, e.g. 0 and 40 ms at 25 Hz), are left out (their average would be biased in time); empty bins inside the track are filled by linear interpolation. If the bins hold at most one sample (native rate at or below the grid rate), the positions are interpolated instead (_interp_to_grid).

Parameters:

Name Type Description Default
times_ns NDArray[int64]

Native time stamps as int64 nanoseconds, increasing.

required
x FloatArray

Native positions [m].

required
rate_hz float

Reconstruction rate [Hz].

10.0

Returns:

Type Description
NDArray[int64]

(grid_ns, x_grid): grid times (int64 ns) and bin-averaged positions [m]; empty arrays if the track is

FloatArray

too short.

reconstruct_track

reconstruct_track(times_ns: NDArray[int64], x: FloatArray, config: MontaninoPunzoConfig, *, vehicle_id: Hashable | None = None) -> TrackKinematics | None

Run the reconstruction for one native track and map the result back.

The native positions are averaged onto the grid of config.rate_hz (mp_bin_to_grid) and reconstructed with reconstruct_vehicle. On the grid, speeds and accelerations are centred on the grid points: the Eq. 1 speed difference belongs to the interval midpoint t - dt/2 and the acceleration difference to t - dt, so both are interpolated linearly onto the grid points.

For the native timestamps (needed by Steps 4-5) positions, speeds and accelerations are interpolated from the grid values with a monotone cubic (PCHIP) interpolant, not linearly: linear interpolation of positions gives piecewise-constant derivatives and thus artificial jerk sign changes. Positions outside the grid are extrapolated with the end speeds; speeds and accelerations there take the end values.

Parameters:

Name Type Description Default
times_ns NDArray[int64]

Native time stamps as int64 nanoseconds, increasing.

required
x FloatArray

Native longitudinal positions [m].

required
config MontaninoPunzoConfig

Reconstruction parameters; rate_hz is the reconstruction rate [Hz].

required
vehicle_id Hashable | None

Only used in log messages.

None

Returns:

Type Description
TrackKinematics | None

A TrackKinematics at the native time stamps, or None if the track is shorter than 2 s at the

TrackKinematics | None

reconstruction rate.

Enforce platoon consistency in the Montanino & Punzo reconstruction (optional post-pass).

Experimental. Not part of the supported API: kept for reproducibility of documented experiments; interfaces may change or be removed without notice.

Montanino & Punzo (2015, Sec. 2.3.1) reconstruct a vehicle only after its leaders, so that the spacing to the reconstructed leader can be kept positive ("platoon consistency", Eq. 2e and Eq. 3l). Because vehicles change leaders over time, this needs an order of processing:

  • The leader-follower hierarchy tree has one node per vehicle and an edge from every leader to every vehicle that followed it at some time (id_front). Vehicles that overtake each other lead each other at different times; such "circular dependencies" are the strongly connected groups of this directed graph and share one layer.
  • Layer 1 holds the vehicles (groups) without a leader; every other group is placed one layer below the deepest layer among its leaders.

platoon_consistency_post_pass then re-runs Step 3 of the reconstruction (reconstruct_constrained_windows) with the spacing constraints, layer by layer, on the 10 Hz output positions, iterating within circular groups until nothing changes or max_platoon_iterations is reached.

LeaderFollowerTree dataclass

LeaderFollowerTree(layers: list[list[list[Any]]], vehicle_layer: dict[Any, int], graph: DiGraph)

Leader-follower hierarchy of a recording.

Attributes:

Name Type Description
layers list[list[list[Any]]]

layers[i] lists the groups of layer i + 1; each group is a sorted list of vehicle IDs (more than one ID = circular dependency).

vehicle_layer dict[Any, int]

Vehicle ID -> layer (1-based).

graph DiGraph

Directed graph leader -> follower.

circular_groups property

circular_groups: list[list[Any]]

Groups with more than one vehicle.

PlatoonResult dataclass

PlatoonResult(tracks: TrackFrame, report: dict[str, Any] | None = None)

Result of enforce_platoon_consistency.

Attributes:

Name Type Description
tracks TrackFrame

The samples after the post-pass and the new surroundings.

report dict[str, Any] | None

The report of platoon_consistency_post_pass plus rows_below_h_min_after; None if skipped.

build_leader_follower_tree

build_leader_follower_tree(df: TrackFrame, id_col: str = C.ID, leader_col: str = C.ID_FRONT) -> LeaderFollowerTree

Build the leader-follower hierarchy tree (Montanino & Punzo 2015, Sec. 2.3.1).

Parameters:

Name Type Description Default
df TrackFrame

Rows with a vehicle ID and the ID of its leader (NaN = none); leaders not in df are ignored.

required
id_col str

Column of the vehicle ID.

ID
leader_col str

Column of the leader ID.

ID_FRONT

Returns:

Type Description
LeaderFollowerTree

The tree; every vehicle of df appears in exactly one group of one layer.

platoon_consistency_post_pass

platoon_consistency_post_pass(df: TrackFrame, mp_config: MontaninoPunzoConfig, default_length_m: float = C.DEFAULT_VEHICLE_LENGTH_M) -> tuple[TrackFrame, dict[str, Any]]

Re-run Step 3 of the reconstruction with the platoon constraints (Eq. 2e/3l), layer by layer.

Works on the output grid (constant spacing 1 / mp_config.rate_hz, which must equal the output rate). Per vehicle, the leader's current position at each grid time comes from the vehicles already processed (or, inside a circular group, from the current state of the group). Only vehicles with a spacing below h_min to their current leader are processed, and of their reconstructed windows only those within window_lookahead samples of such a violation are kept; as in the paper, windows are triggered by unphysical accelerations, so a spacing violation without one is reported but not fixed. Samples changed here get new pos_lon, speed and acceleration (Eq. 1 at the reconstruction rate, mapped to the grid like in Step 3) and mp_reconstructed = True. Speeds/accelerations elsewhere are kept.

DEVIATIONS: the paper runs the whole reconstruction in hierarchy order; here only Step 3 is re-run as a post-pass, because the leaders are only known after Step 6. Spacing uses centre positions: leader_x - x - (L_lead + L) / 2 >= h_min.

Parameters:

Name Type Description Default
df TrackFrame

Pipeline output after Step 6 (id, datum, pos_lon [m], speed [km/h], acceleration [m/s^2], id_front, optionally length [m] and clearance_front [m]) on a regular grid.

required
mp_config MontaninoPunzoConfig

MontaninoPunzoConfig (reconstruction parameters, h_min_m, rate_hz, max_platoon_iterations).

required
default_length_m float

Vehicle length [m] when length is missing.

DEFAULT_VEHICLE_LENGTH_M

Returns:

Type Description
TrackFrame

(df_new, report): the updated frame sorted by id and time (surroundings are not recomputed here)

dict[str, Any]

and a dict with tree, layers, circular_groups, largest_circular_group,

tuple[TrackFrame, dict[str, Any]]

group_iterations (per circular group), counters and rows_below_h_min_before (rows with

tuple[TrackFrame, dict[str, Any]]

clearance_front below h_min before the pass).

enforce_platoon_consistency

enforce_platoon_consistency(tracks: TrackFrame, *, mp: MontaninoPunzoConfig | None = None, output_rate_hz: float | None = 10.0, default_vehicle_length_m: float = C.DEFAULT_VEHICLE_LENGTH_M, tie_tolerance_m: float = 0.001, direction_consistency_min: float = 0.9) -> PlatoonResult

Apply the platoon consistency of Montanino & Punzo (Eq. 2e/3l), then compute the surroundings again.

Runs after compute_surroundings of page 10 (method on page 05 of the pipeline steps 01-10, docs/pipeline/05_kinematics.md); off in the preset drone_hgv_paper. Requires the columns id, datum, pos_lon [m], speed [km/h], acceleration [m/s^2] and id_front on the output grid at mp.rate_hz; changes pos_lon, speed and acceleration of followers that come closer than mp.h_min_m to their leader and recomputes the surroundings columns. Skipped with a warning on another grid.

Example

from trajlab.processing.kinematics.platoon import enforce_platoon_consistency result = enforce_platoon_consistency(on_grid_with_surroundings, output_rate_hz=10.0) # doctest: +SKIP

Parameters:

Name Type Description Default
tracks TrackFrame

Samples on the output grid with the surroundings. Not modified.

required
mp MontaninoPunzoConfig | None

Montanino & Punzo parameters (h_min_m, rate_hz, the reconstruction parameters); None uses MontaninoPunzoConfig().

None
output_rate_hz float | None

Rate [Hz] of the output grid of tracks. Defaults to 10.0.

10.0
default_vehicle_length_m float

Length [m] of vehicles without a length. Defaults to 4.5.

DEFAULT_VEHICLE_LENGTH_M
tie_tolerance_m float

Tie tolerance [m] of compute_surroundings. Defaults to 0.001.

0.001
direction_consistency_min float

Minimum share (0-1) of vehicles whose pos_lon increases. Defaults to 0.9.

0.9

Returns:

Type Description
PlatoonResult

The samples and the report.

Smooth one track with a Savitzky-Golay filter and derive speed and acceleration (generic smoothing).

pos_lon [m] runs along the travel direction, pos_lat [m] to the left. The Montanino & Punzo (2015) reconstruction, the pipeline default, is in processing.kinematics.montanino_punzo.

odd_window

odd_window(n: float, minimum: int = 5) -> int

Round a window length to an odd number of samples of at least minimum.

Savitzky-Golay and median filters need an odd window; the processing and the quality measures share this rule.

Parameters:

Name Type Description Default
n float

Window length [samples], e.g. seconds / dt.

required
minimum int

Shortest window [samples].

5

Returns:

Type Description
int

max(round(n), minimum), plus 1 if even.

apply_kinematic_smoothing

apply_kinematic_smoothing(x_pos: FloatArray, y_pos: FloatArray, timestamps: NDArray[datetime64] | FloatArray, smooth_window_frames: int | None = None, smooth_window_sec: float = 4.0, poly_order: int = 2) -> tuple[FloatArray, FloatArray, FloatArray, FloatArray]

Smooth one vehicle's track and derive speed and acceleration (Step 3).

A Savitzky-Golay filter fits a local polynomial of order poly_order over a moving window and evaluates the fitted value and its analytic first and second derivatives (generic smoothing; the Montanino & Punzo reconstruction is in montanino_punzo). To avoid the filter's distortion at the track ends, the positions are first extended by one window length at both ends with constant velocity (estimated from the first and last 5 samples); the padded part is cut off afterwards.

Window length: smooth_window_frames if given (made odd), otherwise smooth_window_sec divided by the median sampling interval, rounded to an odd number of at least 5 frames (121 frames for 4 s at 30 Hz).

Tracks shorter than the window (or with window <= poly_order) are not filtered: positions are returned unchanged and speed/acceleration come from first differences. Time steps of 0 s are treated as 0.04 s.

Parameters:

Name Type Description Default
x_pos FloatArray

Longitudinal positions pos_lon [m], in time order.

required
y_pos FloatArray

Lateral positions pos_lat [m], same length.

required
timestamps NDArray[datetime64] | FloatArray

Time stamps (datetime64 or seconds as floats), same length.

required
smooth_window_frames int | None

Fixed window in frames (made odd); wins over smooth_window_sec when positive.

None
smooth_window_sec float

Window [s], used when smooth_window_frames is None or not positive.

4.0
poly_order int

Polynomial order.

2

Returns:

Type Description
FloatArray

(x_smooth, y_smooth, speed_kmh, acc_ms2), each of the input length: smoothed longitudinal and lateral

FloatArray

position [m], speed [km/h] (absolute value of the longitudinal derivative) and longitudinal acceleration

FloatArray

[m/s^2] (signed, along increasing pos_lon). Tracks with fewer than 2 points return the positions

FloatArray

unchanged and zero speed and acceleration.

Estimate a spatially fixed longitudinal position error per lane (time-half cross-validation) and correct it.

Drone recordings stitched from orthophotos or georeferenced with a lens model can carry a position error that is fixed in space: every vehicle passing a place is shifted by about the same amount along the road. Differentiated twice it looks like braking and accelerating at fixed places. The error is estimated per recording, direction and lane (one call per pipeline run, i.e. one recording and direction):

  1. per vehicle, the 10-Hz residual of pos_lon around a cubic 4-s Savitzky-Golay trend (the noise band; the first and last 2 s are dropped), located at the trend position;
  2. per lane, the profile p(s) = mean residual per s bin of width w; w is chosen from widths by cross-validation over time: the profile of the first half of the recording predicts the residuals of the second half and vice versa, and the mean held-out explained variance R2_cv is maximised;
  3. a lane is corrected only if it has enough data (min_samples residual samples and min_vehicles vehicles in each half) and the held-out R2 exceeds r2_min in both directions. Every other lane keeps its positions; its status says why.

apply_spatial_correction subtracts p(s) from pos_lon for the corrected lanes and writes the flag column spatial_corrected (False on uncorrected lanes and outside the profiles). Lanes are found from pos_lat with the lateral bands stored in the profile table, so the correction can run before lanes are assigned (Step 3).

Checks against real behaviour (leftmost lane, traffic-state halves, cars vs HGVs) are dataset studies and stay outside this module.

residuals

residuals(df: TrackFrame, lane_col: str, rate_hz: float = 10.0, trend_s: float = 4.0, edge_s: float = 2.0) -> pd.DataFrame

Return the residuals of pos_lon around a smooth trend on a regular grid for all vehicles in df.

Each vehicle is averaged onto a rate_hz grid; vehicles with gaps on the grid or too few grid samples are skipped. The residual is signed along the vehicle's direction of motion and located at the trend position.

Parameters:

Name Type Description Default
df TrackFrame

Frame with id, datum, pos_lon, pos_lat and lane_col (raw, not smoothed positions).

required
lane_col str

Lane per row; rows with a lane below 1 (or not numeric) are dropped.

required
rate_hz float

Grid rate [Hz].

10.0
trend_s float

Window of the cubic Savitzky-Golay trend [s].

4.0
edge_s float

Time dropped at both track ends [s].

2.0

Returns:

Type Description
DataFrame

Columns vid, t_s (grid time since the first sample of df [s]), s (trend position [m]),

DataFrame

r (residual [m]), lane and lat (mean pos_lat [m]).

estimate_spatial_bias

estimate_spatial_bias(df: TrackFrame, lane_col: str, *, widths: Sequence[float] = WIDTHS_M, r2_min: float = 0.05, min_samples: int = 2000, min_vehicles: int = 20) -> tuple[pd.DataFrame, pd.DataFrame]

Estimate the spatial error profiles of one recording and direction.

Parameters:

Name Type Description Default
df TrackFrame

Raw positions with lanes (see residuals).

required
lane_col str

Lane column.

required
widths Sequence[float]

Candidate bin widths [m].

WIDTHS_M
r2_min float

Minimum held-out explained variance in both directions of the time-half cross-validation.

0.05
min_samples int

Minimum 10-Hz residual samples per lane and half.

2000
min_vehicles int

Minimum vehicles per lane and half.

20

Returns:

Type Description
DataFrame

(profiles, lanes): profiles with lane, s_bin (bin number floor(s / width_m)),

DataFrame

width_m [m], p [m], lat_lo / lat_hi (lateral band of the lane [m], halfway to the

tuple[DataFrame, DataFrame]

neighbouring lane centres) and corrected, for every lane with enough data (p from all data);

tuple[DataFrame, DataFrame]

lanes with one row per lane: lane, n, n_vehicles, width_m, r2_first_to_second,

tuple[DataFrame, DataFrame]

r2_second_to_first, r2_cv, status (STATUS_*).

apply_spatial_correction

apply_spatial_correction(df: TrackFrame, profiles: DataFrame) -> TrackFrame

Subtract the error profile p(s) from pos_lon on the corrected lanes.

The lane of a row comes from its pos_lat and the lateral bands of profiles. Rows outside a corrected lane or outside the profile keep their position.

Parameters:

Name Type Description Default
df TrackFrame

Samples with pos_lon and pos_lat [m].

required
profiles DataFrame

Profiles of estimate_spatial_bias.

required

Returns:

Type Description
TrackFrame

A copy of df with corrected pos_lon and the flag column spatial_corrected.

Cut the track ends after the kinematic reconstruction (page 05 of the pipeline steps 01-10).

trim_track_ends removes the ends whose acceleration Step 1 of Montanino & Punzo left outside its outlier bounds, trim_track_ends_fixed a fixed time at both ends (the start-up transient of a zero-phase filter). reconstruct_kinematics calls both when its parameters ask for it.

trim_track_ends

trim_track_ends(df: TrackFrame, max_depth_s: float, a_min: float, a_max: float) -> tuple[TrackFrame, dict[str, int]]

Cut the track ends whose acceleration Step 1 of Montanino & Punzo left outside its outlier bounds.

Step 1 never moves the first or last position of a track (the spline needs reference points on both sides), so outliers at the track ends stay in the output. Per track and end, all rows up to and including the deepest row within max_depth_s of that end whose acceleration lies outside [a_min, a_max] are removed; tracks without such rows are unchanged. Interior rows are never touched.

Parameters:

Name Type Description Default
df TrackFrame

Samples with id, datum and acceleration [m/s^2].

required
max_depth_s float

Depth [s] from each track end that is searched.

required
a_min float

Lower acceleration bound [m/s^2] (Step 1 deceleration threshold).

required
a_max float

Upper acceleration bound [m/s^2] (Step 1 acceleration threshold).

required

Returns:

Type Description
TrackFrame

(df, report): the remaining rows (original order and index) and rows_removed, ends_cut,

dict[str, int]

tracks_removed.

trim_track_ends_fixed

trim_track_ends_fixed(df: TrackFrame, cut_s: float) -> TrackFrame

Drop a fixed time at both ends of every track (the start-up transient of a reconstruction).

Parameters:

Name Type Description Default
df TrackFrame

Samples with id and datum (a TrackFrame).

required
cut_s float

Time [s] removed at each track end.

required

Returns:

Type Description
TrackFrame

The rows at least cut_s from both ends of their track (original order and index); tracks shorter than

TrackFrame

2 * cut_s vanish.

Reconstruct speed and acceleration per vehicle (page 05 of the pipeline steps 01-10).

reconstruct_kinematics is the entry function of the step: Savitzky-Golay smoothing of both coordinates, or the Montanino & Punzo reconstruction (montanino_punzo, or a filter of filters) of pos_lon with Savitzky-Golay for pos_lat; optionally a spatial correction before (spatial_correction) and the cut of the track ends after (track_ends).

KinematicsParams dataclass

KinematicsParams(method: str = 'montanino_punzo', smooth_window_sec: float = 4.0, smooth_window_frames: int | None = None, poly_order: int = 2, max_reversal_m: float = 15.0, lateral_smooth_window_sec: float | None = None, direction_consistency_min: float = 0.9, mp: MontaninoPunzoConfig = MontaninoPunzoConfig(), reconstruction: Mapping[str, Any] | None = None, spatial_correction_profiles: DataFrame | None = None)

Parameters of reconstruct_kinematics; defaults of the preset drone_hgv_paper.

Attributes:

Name Type Description
method str

"montanino_punzo" (Montanino & Punzo for pos_lon) or "savgol" (Savitzky-Golay for both coordinates). Defaults to "montanino_punzo".

smooth_window_sec float

Savitzky-Golay window [s]. Defaults to 4.0.

smooth_window_frames int | None

Explicit window in frames; wins over smooth_window_sec when set. Defaults to None.

poly_order int

Savitzky-Golay polynomial order. Defaults to 2.

max_reversal_m float

Vehicles moving backwards by more than this [m] are dropped. Defaults to 15.0.

lateral_smooth_window_sec float | None

Savitzky-Golay window [s] of pos_lat with montanino_punzo; None uses the longitudinal window. Defaults to None.

direction_consistency_min float

Minimum share (0-1) of vehicles whose pos_lon increases. Defaults to 0.9.

mp MontaninoPunzoConfig

Parameters of the Montanino & Punzo reconstruction (trim_track_ends_sec = 2.0 s as in the preset).

reconstruction Mapping[str, Any] | None

Filter spec that replaces the Montanino & Punzo steps (filters.track_kinematics); None for Montanino & Punzo. Defaults to None.

spatial_correction_profiles DataFrame | None

Profiles of spatial_correction.estimate_spatial_bias to remove a spatially fixed position error first; None for no correction. Defaults to None.

__post_init__

__post_init__() -> None

Check method.

Raises:

Type Description
ValueError

If method is not in KINEMATICS_METHODS.

KinematicsResult dataclass

KinematicsResult(tracks: TrackFrame, mp_tracks: dict[Hashable, TrackKinematics], counters: dict[str, Any], spatial_corrected_share: float | None = None)

Result of reconstruct_kinematics.

Attributes:

Name Type Description
tracks TrackFrame

The samples with smoothed positions, speed [km/h] and acceleration [m/s^2].

mp_tracks dict[Hashable, TrackKinematics]

Vehicle ID -> its Montanino & Punzo reconstruction (TrackKinematics, with the 10 Hz grid values); empty for savgol.

counters dict[str, Any]

Counters of the Montanino & Punzo reconstruction (vehicles, too short, the track-end report); empty for savgol.

spatial_corrected_share float | None

Share of the rows on corrected lanes; None without a spatial correction.

reconstruct_kinematics

reconstruct_kinematics(tracks: TrackFrame, *, params: KinematicsParams | None = None) -> KinematicsResult

Smooth the positions and derive speed [km/h] and acceleration [m/s^2] per vehicle.

Entry function of page 05 of the pipeline steps 01-10 (docs/pipeline/05_kinematics.md). Requires the columns id, datum, pos_lon and pos_lat [m] (project_to_reference_line); smooths pos_lon and pos_lat and adds speed [km/h], acceleration [m/s^2] and, with Montanino & Punzo, mp_reconstructed [bool]. Vehicles moving backwards by more than max_reversal_m are dropped. Method: Montanino & Punzo (2013, 2015) for pos_lon, Savitzky-Golay (1964) for pos_lat (and for both with method="savgol").

Example

import trajlab from trajlab.processing.kinematics import KinematicsParams, reconstruct_kinematics from trajlab.processing.reference_line import project_to_reference_line raw = trajlab.examples.synthetic_motorway() ref_east, _ = trajlab.estimate_ref_lines(raw) tracks = project_to_reference_line(raw[raw["orientation"] > 0], ref_east) smoothed = reconstruct_kinematics(tracks, params=KinematicsParams(method="savgol")).tracks

Parameters:

Name Type Description Default
tracks TrackFrame

Samples of one direction of travel (a DataFrame or a GeoDataFrame). Not modified.

required
params KinematicsParams | None

Parameters; None uses KinematicsParams().

None

Returns:

Type Description
KinematicsResult

The tracks, the per-vehicle Montanino & Punzo results and the counters.

Step 07, lane-change detection from the smoothed lateral speed (docs/pipeline/07_lane_change_detection.md).

Entry function: detect_lane_changes (returns the event table). Modules in run order: lateral_speed (median filter and SEWMA of the lateral speed), maneuvers (thresholds, intervals, event attributes). The former module lane_changes.detector is this package.

LaneChangeParams dataclass

LaneChangeParams(lat_speed_threshold_mps: float = 0.1, min_displacement_m: float = 1.5, median_kernel_sec: float = 0.167, sewma_halfwidth_sec: float = 0.5, sewma_width_sec: float = SEWMA_WIDTH_DEFAULT_SEC)

Settings of the lane-change detector (detect_lane_changes), as the lane assignment takes them.

Attributes:

Name Type Description
lat_speed_threshold_mps float

Threshold [m/s] on the smoothed lateral speed. Defaults to 0.1.

min_displacement_m float

Minimum lateral displacement [m] of an interval. Defaults to 1.5.

median_kernel_sec float

Width of the median filter [s]. Defaults to 0.167.

sewma_halfwidth_sec float

Half-width of the SEWMA kernel [s]. Defaults to 0.5.

sewma_width_sec float

Kernel width T of the SEWMA [s]. Defaults to SEWMA_WIDTH_DEFAULT_SEC (0.316 s).

sewma_alpha

sewma_alpha(width_sec: float, dt_s: float) -> float

Return the per-sample decay factor alpha = exp(-dt / T) of a SEWMA kernel of width T.

Thiemann et al. (2008) write the kernel as exp(-|i - k| / Delta) with Delta = T / dt samples; alpha ** |k| is the same kernel.

Parameters:

Name Type Description Default
width_sec float

Kernel width T [s].

required
dt_s float

Sampling interval dt [s].

required

Returns:

Type Description
float

The decay factor per sample, in (0, 1) for positive arguments.

sewma_filter

sewma_filter(data: ArrayLike, alpha: float = 0.8, window_size: int = 5) -> FloatArray

Smooth a 1-D signal with the symmetric exponentially weighted moving average (SEWMA).

The signal is convolved with an exponentially decaying kernel that is symmetric (causal and anti-causal at the same time). This avoids the phase shift of a one-sided EWMA, so the peaks of the lateral speed during a lane change are not delayed.

The kernel weight at offset k is alpha ** |k|, normalized so the filtered values lie in the same range as the input. This is the symmetric exponential kernel of Thiemann, Treiber & Kesting (2008), exp(-|k| / Delta) with Delta = T / dt samples. alpha is per sample: the same alpha means a different width in seconds at another sampling rate, so the pipeline derives it from a width in seconds (sewma_alpha). Thiemann et al. truncate the kernel at 3 * Delta; here the half-width window_size is set separately.

Parameters:

Name Type Description Default
data ArrayLike

1-D signal values (for example the lateral speed [m/s]).

required
alpha float

Per-sample decay factor, in (0, 1). Higher values give the distant samples more weight (wider kernel, more smoothing).

0.8
window_size int

Half-width of the kernel in samples; the full kernel spans 2 * window_size + 1 samples. It is clamped so that the kernel does not exceed the data length.

5

Returns:

Type Description
FloatArray

The smoothed signal, same length as data (the input as float array if it is empty).

sewma_width_from_alpha

sewma_width_from_alpha(alpha: float, rate_hz: float = 30.0) -> float

Return the kernel width that a per-sample decay factor has at a given sampling rate.

Inverse of sewma_alpha: T = -dt / ln(alpha) with dt = 1 / rate_hz.

Parameters:

Name Type Description Default
alpha float

Per-sample decay factor, in (0, 1).

required
rate_hz float

Sampling rate [Hz].

30.0

Returns:

Type Description
float

Kernel width T [s].

smooth_lateral_speed

smooth_lateral_speed(t_seconds: ArrayLike, lat: ArrayLike, median_kernel_sec: float = 0.167, sewma_halfwidth_sec: float = 0.5, sewma_width_sec: float = SEWMA_WIDTH_DEFAULT_SEC, alpha: float | None = None) -> FloatArray

Return the smoothed lateral speed of one track, as the lane-change detector computes it.

d lat / dt (np.gradient), median-filtered over median_kernel_sec (odd number of samples) and smoothed with the symmetric exponential kernel (SEWMA, width sewma_width_sec, half-width sewma_halfwidth_sec) of Thiemann, Treiber & Kesting (2008); widths in seconds, converted with the track's median sampling interval. Used by detect_lane_changes and by the merge detection of trajlab.analysis (which passes the lateral position relative to the auxiliary lane's centre line).

Parameters:

Name Type Description Default
t_seconds ArrayLike

Sample times [s], increasing.

required
lat ArrayLike

Lateral position [m], same length.

required
median_kernel_sec float

Width of the median filter [s], rounded to an odd number of samples.

0.167
sewma_halfwidth_sec float

Half-width of the SEWMA kernel [s].

0.5
sewma_width_sec float

Kernel width T of the SEWMA [s].

SEWMA_WIDTH_DEFAULT_SEC
alpha float | None

Per-sample SEWMA decay factor that overrides sewma_width_sec (deprecated path of detect_lane_changes); None derives it from sewma_width_sec.

None

Returns:

Type Description
FloatArray

Smoothed lateral speed [m/s], same length as lat; all NaN for fewer than 5 samples or a non-positive

FloatArray

median sampling interval.

detect_lane_changes

detect_lane_changes(df_points: TrackFrame, lat_speed_threshold_mps: float = 0.1, alpha: float | None = None, n_cores: int | None = None, frame_rate: float = 30.0, min_displacement_m: float = 1.5, median_kernel_sec: float = 0.167, sewma_halfwidth_sec: float = 0.5, sewma_width_sec: float = SEWMA_WIDTH_DEFAULT_SEC) -> EventFrame

Detect all lane changes and return their start, crossing and end with kinematics and neighbors.

Entry function of page 07 of the pipeline steps 01-10 (docs/pipeline/07_lane_change_detection.md). Requires the columns id, datum, pos_lon [m], pos_lat [m], lane and speed; returns an event table and leaves the tracks unchanged. Inside the pipeline assign_lanes (pages 08 and 09) calls it at the native frame rate; run_pipeline_detailed(...).events is that table, classified and enriched with neighbor attributes. Calling this function on the resampled (10 Hz) output detects the events again on fewer samples and can give slightly different times; use it for standalone data. Method: Thiemann, Treiber & Kesting (2008), Hofinger & Fellendorf (2023).

Example

import trajlab from trajlab.processing.lane_changes import detect_lane_changes raw = trajlab.examples.synthetic_motorway() ref_east, _ = trajlab.estimate_ref_lines(raw) tracks = trajlab.run_pipeline(raw[raw["orientation"] > 0], ref_east) events = detect_lane_changes(tracks, lat_speed_threshold_mps=0.1)

For each vehicle, the lateral speed d pos_lat / dt [m/s] is median-filtered and smoothed with the symmetric exponential kernel of Thiemann, Treiber & Kesting (2008) (SEWMA, width sewma_width_sec). As in Hofinger & Fellendorf (2023), a threshold on the smoothed lateral speed marks the start and the end of a lane change: intervals in which the smoothed lateral speed exceeds lat_speed_threshold_mps and whose lateral displacement exceeds min_displacement_m are accepted. Filter widths are given in seconds and converted to samples with each vehicle's median sampling interval, so the result does not depend on the frame rate.

The defaults reproduce the former behaviour at 30 Hz (threshold 0.003 per pseudo-frame of 1/33.3 s, median kernel 5 samples, SEWMA half-width 15 samples).

Parameters:

Name Type Description Default
df_points TrackFrame

Trajectory samples in the pipeline schema. Needs at least id, datum (time), pos_lon, pos_lat, lane and speed; class, orientation and the neighbour columns (id_front_left, clearance_front, ...) are read if present (missing neighbour columns are NaN).

required
lat_speed_threshold_mps float

Threshold [m/s] on the smoothed lateral speed that marks a lane-change interval.

0.1
alpha float | None

Deprecated per-sample SEWMA decay factor. If given, it is used as is for every vehicle (dependent on the sampling rate) and a DeprecationWarning is emitted; None uses sewma_width_sec.

None
n_cores int | None

Number of worker processes for the per-vehicle detection; None or <= 1 runs sequentially, which is faster here (see the note at the dispatch). Parallelise around whole recordings instead.

None
frame_rate float

Recording frame rate [Hz], used only to express the crossing time as a frame number (frame_lc).

30.0
min_displacement_m float

Minimum lateral displacement [m] over the interval for it to count as a lane change.

1.5
median_kernel_sec float

Width of the median filter [s], rounded to an odd number of samples.

0.167
sewma_halfwidth_sec float

Half-width of the SEWMA kernel [s].

0.5
sewma_width_sec float

Kernel width T of the SEWMA [s]; per vehicle alpha = exp(-dt / T) with its median sampling interval dt. The default (0.3164 s) is the former alpha = 0.9 at 30 Hz.

SEWMA_WIDTH_DEFAULT_SEC

Returns:

Type Description
EventFrame

One row per detected lane change (an empty DataFrame without columns if there is none) with the columns

EventFrame

id, class, lc_direction (+1 left, i.e. towards larger pos_lat and a higher lane ID; -1

EventFrame

right), direction (the vehicle's orientation), frame_lc (crossing time in frames since the

EventFrame

vehicle's first sample), time_start, time_lc, time_end [datetime] (start, peak of the smoothed

EventFrame

lateral speed, end), duration_sec [s], lane_start, lane_end, speed_start, speed_lc,

EventFrame

speed_end (unit of the speed column, km/h in the pipeline), pos_lon_lc [m] and the neighbour

EventFrame

attributes id_*, rel_speed_* (unit of speed), clearance_* [m] and headway_* [m]

EventFrame

(centre distance) of front and rear at the start (*_start, on the target side) and at the end

EventFrame

(*_end, in the own lane).

Smoothed lateral speed of one vehicle: median filter and symmetric exponential smoothing (SEWMA).

The lateral speed d pos_lat / dt [m/s] is median-filtered and smoothed with the symmetric exponential kernel (SEWMA) of Thiemann, Treiber & Kesting (2008). Filter widths are given in seconds and converted to samples with the vehicle's median sampling interval. maneuvers.detect_lane_changes thresholds the result.

sewma_alpha

sewma_alpha(width_sec: float, dt_s: float) -> float

Return the per-sample decay factor alpha = exp(-dt / T) of a SEWMA kernel of width T.

Thiemann et al. (2008) write the kernel as exp(-|i - k| / Delta) with Delta = T / dt samples; alpha ** |k| is the same kernel.

Parameters:

Name Type Description Default
width_sec float

Kernel width T [s].

required
dt_s float

Sampling interval dt [s].

required

Returns:

Type Description
float

The decay factor per sample, in (0, 1) for positive arguments.

sewma_width_from_alpha

sewma_width_from_alpha(alpha: float, rate_hz: float = 30.0) -> float

Return the kernel width that a per-sample decay factor has at a given sampling rate.

Inverse of sewma_alpha: T = -dt / ln(alpha) with dt = 1 / rate_hz.

Parameters:

Name Type Description Default
alpha float

Per-sample decay factor, in (0, 1).

required
rate_hz float

Sampling rate [Hz].

30.0

Returns:

Type Description
float

Kernel width T [s].

sewma_filter

sewma_filter(data: ArrayLike, alpha: float = 0.8, window_size: int = 5) -> FloatArray

Smooth a 1-D signal with the symmetric exponentially weighted moving average (SEWMA).

The signal is convolved with an exponentially decaying kernel that is symmetric (causal and anti-causal at the same time). This avoids the phase shift of a one-sided EWMA, so the peaks of the lateral speed during a lane change are not delayed.

The kernel weight at offset k is alpha ** |k|, normalized so the filtered values lie in the same range as the input. This is the symmetric exponential kernel of Thiemann, Treiber & Kesting (2008), exp(-|k| / Delta) with Delta = T / dt samples. alpha is per sample: the same alpha means a different width in seconds at another sampling rate, so the pipeline derives it from a width in seconds (sewma_alpha). Thiemann et al. truncate the kernel at 3 * Delta; here the half-width window_size is set separately.

Parameters:

Name Type Description Default
data ArrayLike

1-D signal values (for example the lateral speed [m/s]).

required
alpha float

Per-sample decay factor, in (0, 1). Higher values give the distant samples more weight (wider kernel, more smoothing).

0.8
window_size int

Half-width of the kernel in samples; the full kernel spans 2 * window_size + 1 samples. It is clamped so that the kernel does not exceed the data length.

5

Returns:

Type Description
FloatArray

The smoothed signal, same length as data (the input as float array if it is empty).

smooth_lateral_speed

smooth_lateral_speed(t_seconds: ArrayLike, lat: ArrayLike, median_kernel_sec: float = 0.167, sewma_halfwidth_sec: float = 0.5, sewma_width_sec: float = SEWMA_WIDTH_DEFAULT_SEC, alpha: float | None = None) -> FloatArray

Return the smoothed lateral speed of one track, as the lane-change detector computes it.

d lat / dt (np.gradient), median-filtered over median_kernel_sec (odd number of samples) and smoothed with the symmetric exponential kernel (SEWMA, width sewma_width_sec, half-width sewma_halfwidth_sec) of Thiemann, Treiber & Kesting (2008); widths in seconds, converted with the track's median sampling interval. Used by detect_lane_changes and by the merge detection of trajlab.analysis (which passes the lateral position relative to the auxiliary lane's centre line).

Parameters:

Name Type Description Default
t_seconds ArrayLike

Sample times [s], increasing.

required
lat ArrayLike

Lateral position [m], same length.

required
median_kernel_sec float

Width of the median filter [s], rounded to an odd number of samples.

0.167
sewma_halfwidth_sec float

Half-width of the SEWMA kernel [s].

0.5
sewma_width_sec float

Kernel width T of the SEWMA [s].

SEWMA_WIDTH_DEFAULT_SEC
alpha float | None

Per-sample SEWMA decay factor that overrides sewma_width_sec (deprecated path of detect_lane_changes); None derives it from sewma_width_sec.

None

Returns:

Type Description
FloatArray

Smoothed lateral speed [m/s], same length as lat; all NaN for fewer than 5 samples or a non-positive

FloatArray

median sampling interval.

Detect lane changes from the smoothed lateral speed (page 07 of the pipeline steps 01-10).

As in Hofinger & Fellendorf (2023), the interval in which the smoothed lateral speed (lateral_speed) exceeds a threshold marks the start and the end of a lane change; the interval is kept if its lateral displacement is large enough. detect_lane_changes runs the detection per vehicle and returns the event table.

Conventions: pos_lon [m] runs along the travel direction, pos_lat [m] is positive to the left; lane 0 is the auxiliary or ramp lane, 1 the rightmost main lane, -1 not assigned. lc_direction is +1 for a change to the left (larger pos_lat, higher lane ID) and -1 for a change to the right.

LaneChangeParams dataclass

LaneChangeParams(lat_speed_threshold_mps: float = 0.1, min_displacement_m: float = 1.5, median_kernel_sec: float = 0.167, sewma_halfwidth_sec: float = 0.5, sewma_width_sec: float = SEWMA_WIDTH_DEFAULT_SEC)

Settings of the lane-change detector (detect_lane_changes), as the lane assignment takes them.

Attributes:

Name Type Description
lat_speed_threshold_mps float

Threshold [m/s] on the smoothed lateral speed. Defaults to 0.1.

min_displacement_m float

Minimum lateral displacement [m] of an interval. Defaults to 1.5.

median_kernel_sec float

Width of the median filter [s]. Defaults to 0.167.

sewma_halfwidth_sec float

Half-width of the SEWMA kernel [s]. Defaults to 0.5.

sewma_width_sec float

Kernel width T of the SEWMA [s]. Defaults to SEWMA_WIDTH_DEFAULT_SEC (0.316 s).

detect_lane_changes

detect_lane_changes(df_points: TrackFrame, lat_speed_threshold_mps: float = 0.1, alpha: float | None = None, n_cores: int | None = None, frame_rate: float = 30.0, min_displacement_m: float = 1.5, median_kernel_sec: float = 0.167, sewma_halfwidth_sec: float = 0.5, sewma_width_sec: float = SEWMA_WIDTH_DEFAULT_SEC) -> EventFrame

Detect all lane changes and return their start, crossing and end with kinematics and neighbors.

Entry function of page 07 of the pipeline steps 01-10 (docs/pipeline/07_lane_change_detection.md). Requires the columns id, datum, pos_lon [m], pos_lat [m], lane and speed; returns an event table and leaves the tracks unchanged. Inside the pipeline assign_lanes (pages 08 and 09) calls it at the native frame rate; run_pipeline_detailed(...).events is that table, classified and enriched with neighbor attributes. Calling this function on the resampled (10 Hz) output detects the events again on fewer samples and can give slightly different times; use it for standalone data. Method: Thiemann, Treiber & Kesting (2008), Hofinger & Fellendorf (2023).

Example

import trajlab from trajlab.processing.lane_changes import detect_lane_changes raw = trajlab.examples.synthetic_motorway() ref_east, _ = trajlab.estimate_ref_lines(raw) tracks = trajlab.run_pipeline(raw[raw["orientation"] > 0], ref_east) events = detect_lane_changes(tracks, lat_speed_threshold_mps=0.1)

For each vehicle, the lateral speed d pos_lat / dt [m/s] is median-filtered and smoothed with the symmetric exponential kernel of Thiemann, Treiber & Kesting (2008) (SEWMA, width sewma_width_sec). As in Hofinger & Fellendorf (2023), a threshold on the smoothed lateral speed marks the start and the end of a lane change: intervals in which the smoothed lateral speed exceeds lat_speed_threshold_mps and whose lateral displacement exceeds min_displacement_m are accepted. Filter widths are given in seconds and converted to samples with each vehicle's median sampling interval, so the result does not depend on the frame rate.

The defaults reproduce the former behaviour at 30 Hz (threshold 0.003 per pseudo-frame of 1/33.3 s, median kernel 5 samples, SEWMA half-width 15 samples).

Parameters:

Name Type Description Default
df_points TrackFrame

Trajectory samples in the pipeline schema. Needs at least id, datum (time), pos_lon, pos_lat, lane and speed; class, orientation and the neighbour columns (id_front_left, clearance_front, ...) are read if present (missing neighbour columns are NaN).

required
lat_speed_threshold_mps float

Threshold [m/s] on the smoothed lateral speed that marks a lane-change interval.

0.1
alpha float | None

Deprecated per-sample SEWMA decay factor. If given, it is used as is for every vehicle (dependent on the sampling rate) and a DeprecationWarning is emitted; None uses sewma_width_sec.

None
n_cores int | None

Number of worker processes for the per-vehicle detection; None or <= 1 runs sequentially, which is faster here (see the note at the dispatch). Parallelise around whole recordings instead.

None
frame_rate float

Recording frame rate [Hz], used only to express the crossing time as a frame number (frame_lc).

30.0
min_displacement_m float

Minimum lateral displacement [m] over the interval for it to count as a lane change.

1.5
median_kernel_sec float

Width of the median filter [s], rounded to an odd number of samples.

0.167
sewma_halfwidth_sec float

Half-width of the SEWMA kernel [s].

0.5
sewma_width_sec float

Kernel width T of the SEWMA [s]; per vehicle alpha = exp(-dt / T) with its median sampling interval dt. The default (0.3164 s) is the former alpha = 0.9 at 30 Hz.

SEWMA_WIDTH_DEFAULT_SEC

Returns:

Type Description
EventFrame

One row per detected lane change (an empty DataFrame without columns if there is none) with the columns

EventFrame

id, class, lc_direction (+1 left, i.e. towards larger pos_lat and a higher lane ID; -1

EventFrame

right), direction (the vehicle's orientation), frame_lc (crossing time in frames since the

EventFrame

vehicle's first sample), time_start, time_lc, time_end [datetime] (start, peak of the smoothed

EventFrame

lateral speed, end), duration_sec [s], lane_start, lane_end, speed_start, speed_lc,

EventFrame

speed_end (unit of the speed column, km/h in the pipeline), pos_lon_lc [m] and the neighbour

EventFrame

attributes id_*, rel_speed_* (unit of speed), clearance_* [m] and headway_* [m]

EventFrame

(centre distance) of front and rear at the start (*_start, on the target side) and at the end

EventFrame

(*_end, in the own lane).

Steps 06, 08 and 09, lane geometry and lane assignment (pages 06, 08 and 09 of docs/pipeline/).

Entry function of step 06: estimate_lane_geometry (parameters LaneGeometryParams) in geometry_estimation, which runs the rolling GMM tracker of geometry. Entry function of steps 08 and 09: assign_lanes (parameters LaneAssignmentParams) in assignment; it runs the lane-change detection of step 07, then the heuristic of correction or the hidden Markov model of hmm. geometric and lane_sources derive lane layouts from maps and trajectories outside the chain.

LaneGeometryParams dataclass

LaneGeometryParams(lon_step_m: float = 50.0, window_size_m: float = 200.0, max_drift_m: float = 2.0, gmm_model: str = 'restricted', gmm_prior_eta_m: float = 3.75, gmm_prior_kappa: float = 100.0, gmm_prior_nu: float = 3.0, gmm_prior_varsigma2_m2: float = 0.25, direction_consistency_min: float = 0.9)

Parameters of estimate_lane_geometry; defaults of the preset drone_hgv_paper.

Attributes:

Name Type Description
lon_step_m float

Step of the rolling window along pos_lon [m]. Defaults to 50.0.

window_size_m float

Length of the rolling window [m]. Defaults to 200.0.

max_drift_m float

Largest lateral drift [m] of a tracked lane center between two windows. Defaults to 2.0.

gmm_model str

"restricted" (equal lane widths, Chen & Krumm 2010) or "free". Defaults to "restricted".

gmm_prior_eta_m float

Prior lane width [m] of the restricted GMM. Defaults to 3.75.

gmm_prior_kappa float

Prior strength of the lane width. Defaults to 100.0.

gmm_prior_nu float

Prior degrees of freedom of the lane variance. Defaults to 3.0.

gmm_prior_varsigma2_m2 float

Prior lane variance [m^2]. Defaults to 0.25.

direction_consistency_min float

Minimum share (0-1) of vehicles whose pos_lon increases. Defaults to 0.9.

priors

priors() -> dict[str, float]

Return the GMM priors as the tracker takes them.

Returns:

Type Description
dict[str, float]

eta, kappa, nu and varsigma2.

LaneGeometryResult dataclass

LaneGeometryResult(tracks: TrackFrame, centers: DataFrame, diagnostics: dict[str, Any] | None)

Result of estimate_lane_geometry.

Attributes:

Name Type Description
tracks TrackFrame

The samples with lane.

centers DataFrame

Lane centers per window (km_bin, lane, center_y [m]), lanes numbered like lane; empty if no sample was labeled.

diagnostics dict[str, Any] | None

Stability of the geometry (lane_geometry_diagnostics); None if no sample was labeled.

HmmLaneParams dataclass

HmmLaneParams(rate_in_event: float = 2.0, rate_background: float = 0.001, sigma_floor_m: float = 0.4, epsilon: float = 0.001, emission_floor: str = 'relative', initial_geometry: str = 'labels', zone_margin_m: float = 10.0, merge_gap_s: float = 1.0, max_dwell_s: float = 2.0, aux_lane_fallback: bool = True, conflict_margin_m: float = 1.0, conflict_penalty: float = float(np.log(0.0001)), max_conflict_iterations: int = 10, duplicate_min_overlap_sec: float = 1.0, duplicate_min_confidence: float = 0.9, duplicate_max_lateral_m: float = 0.5, max_em_iterations: int = 3, em_tolerance: float = 0.001, em_bin_m: float = 10.0, em_smooth_sigma_m: float = 30.0, min_points_per_bin: int = 10, conflict_damping: bool = True, conflict_min_duration_sec: float = 1.0, conflict_hold_sec: float = 2.0, min_aux_zone_m: float = 50.0)

Parameters of the hidden-Markov-model lane assignment (method="hmm"); defaults of drone_hgv_paper.

Rates are per second and converted per sample with p = 1 - exp(-rate * dt).

Attributes:

Name Type Description
rate_in_event float

Rate [1/s] of a switch towards the detected side inside a detector interval. Defaults to 2.0.

rate_background float

Rate [1/s] of any other switch. Defaults to 1e-3.

sigma_floor_m float

Minimum lateral spread of a lane [m]. Defaults to 0.4.

epsilon float

Weight of the outlier floor in the emission. Defaults to 1e-3.

emission_floor str

"relative" or "uniform" (hmm.emission_logprob). Defaults to "relative".

initial_geometry str

"labels" (medians of the step 06 labels) or "tracker" (the step 06 lane centers, passed as lane_centers). Defaults to "labels".

zone_margin_m float

Lane 0 is valid up to this distance [m] beyond an auxiliary-lane zone. Defaults to 10.0.

merge_gap_s float

Detector intervals closer than this [s] form one maneuver. Defaults to 1.0.

max_dwell_s float

A -> B -> A is collapsed to A if the time in B is at most this [s]. Defaults to 2.0.

aux_lane_fallback bool

Keep lane 0 (center one lane width right of lane 1) when step 06 gave it no points. Defaults to True.

conflict_margin_m float

Margin [m] of the feasibility test of two vehicles in one lane. Defaults to 1.0.

conflict_penalty float

Log-penalty for the occupied lane on conflict frames. Defaults to log(1e-4).

max_conflict_iterations int

Re-decoding rounds. Defaults to 10.

duplicate_min_overlap_sec float

Minimum conflict length [s] of a suspected duplicate track. Defaults to 1.0.

duplicate_min_confidence float

Minimum lane confidence (0-1) of both vehicles of a duplicate. Defaults to 0.9.

duplicate_max_lateral_m float

Maximum lateral distance [m] of a duplicate. Defaults to 0.5.

max_em_iterations int

Alternating estimation of lane centers and labels. Defaults to 3.

em_tolerance float

Stop when less than this share of labels changes. Defaults to 0.001.

em_bin_m float

Bin length [m] of the center re-estimation. Defaults to 10.0.

em_smooth_sigma_m float

Gaussian smoothing [m] of the center profile. Defaults to 30.0.

min_points_per_bin int

Minimum points of a lane in a bin. Defaults to 10.

conflict_damping bool

Damped conflict resolution (conflict_min_duration_sec, conflict_hold_sec). Defaults to True.

conflict_min_duration_sec float

Shortest conflict episode [s] that is resolved. Defaults to 1.0.

conflict_hold_sec float

Shortest penalty window [s] of a re-assigned vehicle. Defaults to 2.0.

min_aux_zone_m float

Auxiliary-lane zones shorter than this [m] are not offered to the HMM. Defaults to 50.0.

LaneAssignmentParams dataclass

LaneAssignmentParams(method: str = 'hmm', lane_changes: LaneChangeParams = LaneChangeParams(), resolve_conflicts: bool = True, keep_unresolved_lane: bool = False, edge_buffer_m: float = 30.0, direction_consistency_min: float = 0.9, hmm: HmmLaneParams = HmmLaneParams())

Parameters of assign_lanes; defaults of the preset drone_hgv_paper.

Attributes:

Name Type Description
method str

"hmm" (hidden Markov model, page 09) or "heuristic" (crossover correction, page 08). Defaults to "hmm".

lane_changes LaneChangeParams

Settings of the lane-change detector. Defaults to LaneChangeParams().

resolve_conflicts bool

Resolve two vehicles in one lane at the same time. Defaults to True.

keep_unresolved_lane bool

Keep the lane before the conflict resolution in lane_fixed_unresolved. Defaults to False.

edge_buffer_m float

Events within this distance [m] of either road end are flagged near_road_end. Defaults to 30.0.

direction_consistency_min float

Minimum share (0-1) of vehicles whose pos_lon increases. Defaults to 0.9.

hmm HmmLaneParams

Parameters of the hidden Markov model. Defaults to HmmLaneParams().

__post_init__

__post_init__() -> None

Check method.

Raises:

Type Description
ValueError

If method is not in LANE_ASSIGNMENT_METHODS.

LaneAssignmentResult dataclass

LaneAssignmentResult(tracks: TrackFrame, events: EventFrame | None, hmm_geometry: LaneGeometry | None = None, em_history: list[dict[str, float]] = list(), conflict_history: list[dict[str, int]] = list())

Result of assign_lanes.

Attributes:

Name Type Description
tracks TrackFrame

The samples with the corrected lanes.

events EventFrame | None

One row per detected lateral maneuver, classified (event_type) and flagged near_road_end; None for an empty input.

hmm_geometry LaneGeometry | None

The lane geometry of the hidden Markov model; None for the heuristic.

em_history list[dict[str, float]]

One record per EM iteration of the hidden Markov model; empty for the heuristic.

conflict_history list[dict[str, int]]

One record per conflict round of the hidden Markov model; empty for the heuristic.

estimate_lane_geometry

estimate_lane_geometry(tracks: TrackFrame, *, params: LaneGeometryParams | None = None, layout: LaneLayout | None = None) -> LaneGeometryResult

Track the lanes with a rolling GMM along the road and label every sample with its lane.

Entry function of page 06 of the pipeline steps 01-10 (docs/pipeline/06_lane_geometry.md). Requires the columns id, datum, pos_lon and pos_lat [m] (project_to_reference_line, best after align_lateral_positions) and adds lane (0 auxiliary lane, 1 rightmost main lane, -1 not assigned). Method: Gaussian mixtures in rolling windows along pos_lon, restricted to equal lane widths after Chen & Krumm (2010), lane centers tracked from window to window.

Example

import trajlab from trajlab.processing.lanes import estimate_lane_geometry from trajlab.processing.reference_line import project_to_reference_line from trajlab.road_layout import LaneLayout raw = trajlab.examples.synthetic_motorway() ref_east, _ = trajlab.estimate_ref_lines(raw) tracks = project_to_reference_line(raw[raw["orientation"] > 0], ref_east) labeled = estimate_lane_geometry(tracks, layout=LaneLayout(n_main_lanes=3)).tracks

Parameters:

Name Type Description Default
tracks TrackFrame

Samples of one direction of travel. Not modified.

required
params LaneGeometryParams | None

Parameters; None uses LaneGeometryParams().

None
layout LaneLayout | None

Number of main lanes and the zones of the site; None uses LaneLayout() (3 lanes, no zones).

None

Returns:

Type Description
LaneGeometryResult

The labeled samples, the lane centers and the diagnostics.

assign_lanes

assign_lanes(tracks: TrackFrame, *, params: LaneAssignmentParams | None = None, layout: LaneLayout | None = None, lane_centers: DataFrame | None = None, road_length_m: float | None = None) -> LaneAssignmentResult

Detect the lane changes, correct the lane of every sample and resolve conflicts between vehicles.

Entry function of pages 08 (heuristic) and 09 (hidden Markov model) of the pipeline steps 01-10 (docs/pipeline/08_lane_assignment_heuristic.md, docs/pipeline/09_lane_assignment_hmm.md). Requires the columns id, datum, pos_lon, pos_lat [m], lane (estimate_lane_geometry) and speed [km/h] (reconstruct_kinematics). Adds lane_fixed, is_changing_lane, is_lateral_excursion, lane_conflict_resolved, optionally lane_fixed_unresolved and, with the hidden Markov model, lane_confidence, lane_posterior_margin, suspected_duplicate_track and lane_conflict_unresolved; lane is overwritten with lane_fixed. Method: lane-change detection of Hofinger & Fellendorf (2023), then a crossover correction (heuristic) or a hidden Markov model with EM re-estimation of the lane centers.

Example

import trajlab from trajlab.processing.kinematics import reconstruct_kinematics from trajlab.processing.lanes import assign_lanes, estimate_lane_geometry from trajlab.processing.reference_line import project_to_reference_line raw = trajlab.examples.synthetic_motorway() ref_east, _ = trajlab.estimate_ref_lines(raw) tracks = project_to_reference_line(raw[raw["orientation"] > 0], ref_east) tracks = estimate_lane_geometry(reconstruct_kinematics(tracks).tracks).tracks result = assign_lanes(tracks, road_length_m=ref_east.length) lanes, events = result.tracks, result.events

Parameters:

Name Type Description Default
tracks TrackFrame

Samples of one direction of travel. Not modified.

required
params LaneAssignmentParams | None

Parameters; None uses LaneAssignmentParams().

None
layout LaneLayout | None

Number of main lanes and the zones of the site; None uses LaneLayout() (3 lanes, no zones).

None
lane_centers DataFrame | None

Lane centers of step 06 (LaneGeometryResult.centers), used by the hidden Markov model with initial_geometry="tracker". Defaults to None.

None
road_length_m float | None

Length of the road [m] for the near_road_end flag; None uses the largest pos_lon.

None

Returns:

Type Description
LaneAssignmentResult

The tracks, the event table and, for the hidden Markov model, its geometry and histories.

Assign the lanes after the lane-change detection (pages 08 and 09 of the pipeline steps 01-10).

assign_lanes is the entry function of both methods: it detects the lateral maneuvers (detect_lane_changes, page 07), corrects the lane labels of the lane geometry (page 06) with the heuristic crossover correction (correction, page 08) or the hidden Markov model (hmm, page 09), resolves conflicts between vehicles in one lane and returns the classified event table.

HmmLaneParams dataclass

HmmLaneParams(rate_in_event: float = 2.0, rate_background: float = 0.001, sigma_floor_m: float = 0.4, epsilon: float = 0.001, emission_floor: str = 'relative', initial_geometry: str = 'labels', zone_margin_m: float = 10.0, merge_gap_s: float = 1.0, max_dwell_s: float = 2.0, aux_lane_fallback: bool = True, conflict_margin_m: float = 1.0, conflict_penalty: float = float(np.log(0.0001)), max_conflict_iterations: int = 10, duplicate_min_overlap_sec: float = 1.0, duplicate_min_confidence: float = 0.9, duplicate_max_lateral_m: float = 0.5, max_em_iterations: int = 3, em_tolerance: float = 0.001, em_bin_m: float = 10.0, em_smooth_sigma_m: float = 30.0, min_points_per_bin: int = 10, conflict_damping: bool = True, conflict_min_duration_sec: float = 1.0, conflict_hold_sec: float = 2.0, min_aux_zone_m: float = 50.0)

Parameters of the hidden-Markov-model lane assignment (method="hmm"); defaults of drone_hgv_paper.

Rates are per second and converted per sample with p = 1 - exp(-rate * dt).

Attributes:

Name Type Description
rate_in_event float

Rate [1/s] of a switch towards the detected side inside a detector interval. Defaults to 2.0.

rate_background float

Rate [1/s] of any other switch. Defaults to 1e-3.

sigma_floor_m float

Minimum lateral spread of a lane [m]. Defaults to 0.4.

epsilon float

Weight of the outlier floor in the emission. Defaults to 1e-3.

emission_floor str

"relative" or "uniform" (hmm.emission_logprob). Defaults to "relative".

initial_geometry str

"labels" (medians of the step 06 labels) or "tracker" (the step 06 lane centers, passed as lane_centers). Defaults to "labels".

zone_margin_m float

Lane 0 is valid up to this distance [m] beyond an auxiliary-lane zone. Defaults to 10.0.

merge_gap_s float

Detector intervals closer than this [s] form one maneuver. Defaults to 1.0.

max_dwell_s float

A -> B -> A is collapsed to A if the time in B is at most this [s]. Defaults to 2.0.

aux_lane_fallback bool

Keep lane 0 (center one lane width right of lane 1) when step 06 gave it no points. Defaults to True.

conflict_margin_m float

Margin [m] of the feasibility test of two vehicles in one lane. Defaults to 1.0.

conflict_penalty float

Log-penalty for the occupied lane on conflict frames. Defaults to log(1e-4).

max_conflict_iterations int

Re-decoding rounds. Defaults to 10.

duplicate_min_overlap_sec float

Minimum conflict length [s] of a suspected duplicate track. Defaults to 1.0.

duplicate_min_confidence float

Minimum lane confidence (0-1) of both vehicles of a duplicate. Defaults to 0.9.

duplicate_max_lateral_m float

Maximum lateral distance [m] of a duplicate. Defaults to 0.5.

max_em_iterations int

Alternating estimation of lane centers and labels. Defaults to 3.

em_tolerance float

Stop when less than this share of labels changes. Defaults to 0.001.

em_bin_m float

Bin length [m] of the center re-estimation. Defaults to 10.0.

em_smooth_sigma_m float

Gaussian smoothing [m] of the center profile. Defaults to 30.0.

min_points_per_bin int

Minimum points of a lane in a bin. Defaults to 10.

conflict_damping bool

Damped conflict resolution (conflict_min_duration_sec, conflict_hold_sec). Defaults to True.

conflict_min_duration_sec float

Shortest conflict episode [s] that is resolved. Defaults to 1.0.

conflict_hold_sec float

Shortest penalty window [s] of a re-assigned vehicle. Defaults to 2.0.

min_aux_zone_m float

Auxiliary-lane zones shorter than this [m] are not offered to the HMM. Defaults to 50.0.

LaneAssignmentParams dataclass

LaneAssignmentParams(method: str = 'hmm', lane_changes: LaneChangeParams = LaneChangeParams(), resolve_conflicts: bool = True, keep_unresolved_lane: bool = False, edge_buffer_m: float = 30.0, direction_consistency_min: float = 0.9, hmm: HmmLaneParams = HmmLaneParams())

Parameters of assign_lanes; defaults of the preset drone_hgv_paper.

Attributes:

Name Type Description
method str

"hmm" (hidden Markov model, page 09) or "heuristic" (crossover correction, page 08). Defaults to "hmm".

lane_changes LaneChangeParams

Settings of the lane-change detector. Defaults to LaneChangeParams().

resolve_conflicts bool

Resolve two vehicles in one lane at the same time. Defaults to True.

keep_unresolved_lane bool

Keep the lane before the conflict resolution in lane_fixed_unresolved. Defaults to False.

edge_buffer_m float

Events within this distance [m] of either road end are flagged near_road_end. Defaults to 30.0.

direction_consistency_min float

Minimum share (0-1) of vehicles whose pos_lon increases. Defaults to 0.9.

hmm HmmLaneParams

Parameters of the hidden Markov model. Defaults to HmmLaneParams().

__post_init__

__post_init__() -> None

Check method.

Raises:

Type Description
ValueError

If method is not in LANE_ASSIGNMENT_METHODS.

LaneAssignmentResult dataclass

LaneAssignmentResult(tracks: TrackFrame, events: EventFrame | None, hmm_geometry: LaneGeometry | None = None, em_history: list[dict[str, float]] = list(), conflict_history: list[dict[str, int]] = list())

Result of assign_lanes.

Attributes:

Name Type Description
tracks TrackFrame

The samples with the corrected lanes.

events EventFrame | None

One row per detected lateral maneuver, classified (event_type) and flagged near_road_end; None for an empty input.

hmm_geometry LaneGeometry | None

The lane geometry of the hidden Markov model; None for the heuristic.

em_history list[dict[str, float]]

One record per EM iteration of the hidden Markov model; empty for the heuristic.

conflict_history list[dict[str, int]]

One record per conflict round of the hidden Markov model; empty for the heuristic.

assign_lanes

assign_lanes(tracks: TrackFrame, *, params: LaneAssignmentParams | None = None, layout: LaneLayout | None = None, lane_centers: DataFrame | None = None, road_length_m: float | None = None) -> LaneAssignmentResult

Detect the lane changes, correct the lane of every sample and resolve conflicts between vehicles.

Entry function of pages 08 (heuristic) and 09 (hidden Markov model) of the pipeline steps 01-10 (docs/pipeline/08_lane_assignment_heuristic.md, docs/pipeline/09_lane_assignment_hmm.md). Requires the columns id, datum, pos_lon, pos_lat [m], lane (estimate_lane_geometry) and speed [km/h] (reconstruct_kinematics). Adds lane_fixed, is_changing_lane, is_lateral_excursion, lane_conflict_resolved, optionally lane_fixed_unresolved and, with the hidden Markov model, lane_confidence, lane_posterior_margin, suspected_duplicate_track and lane_conflict_unresolved; lane is overwritten with lane_fixed. Method: lane-change detection of Hofinger & Fellendorf (2023), then a crossover correction (heuristic) or a hidden Markov model with EM re-estimation of the lane centers.

Example

import trajlab from trajlab.processing.kinematics import reconstruct_kinematics from trajlab.processing.lanes import assign_lanes, estimate_lane_geometry from trajlab.processing.reference_line import project_to_reference_line raw = trajlab.examples.synthetic_motorway() ref_east, _ = trajlab.estimate_ref_lines(raw) tracks = project_to_reference_line(raw[raw["orientation"] > 0], ref_east) tracks = estimate_lane_geometry(reconstruct_kinematics(tracks).tracks).tracks result = assign_lanes(tracks, road_length_m=ref_east.length) lanes, events = result.tracks, result.events

Parameters:

Name Type Description Default
tracks TrackFrame

Samples of one direction of travel. Not modified.

required
params LaneAssignmentParams | None

Parameters; None uses LaneAssignmentParams().

None
layout LaneLayout | None

Number of main lanes and the zones of the site; None uses LaneLayout() (3 lanes, no zones).

None
lane_centers DataFrame | None

Lane centers of step 06 (LaneGeometryResult.centers), used by the hidden Markov model with initial_geometry="tracker". Defaults to None.

None
road_length_m float | None

Length of the road [m] for the near_road_end flag; None uses the largest pos_lon.

None

Returns:

Type Description
LaneAssignmentResult

The tracks, the event table and, for the hidden Markov model, its geometry and histories.

Correct the lane assignment with the detected lateral manoeuvres and resolve in-lane conflicts.

apply_lane_correction classifies each detected lateral manoeuvre (detect_lane_changes) as a lane change or a lateral excursion and sets the corrected lane lane_fixed between the crossovers of the lane changes; resolve_in_lane_conflicts reassigns vehicles that overlap in the same lane at the same time. The lane-change detector itself lives in processing.lane_changes and is re-exported here.

Conventions: pos_lon [m] runs along the travel direction, pos_lat [m] is positive to the left; lane 0 is the auxiliary or ramp lane, 1 the rightmost main lane (increasing to the left), -1 not assigned.

estimate_lane_axis_sign

estimate_lane_axis_sign(df_points: TrackFrame, lane_col: str = C.LANE, lat_col: str = C.POS_LAT) -> int

Determine whether the lateral coordinate grows with the lane index.

Two conventions meet in this package and they are not the same thing. compute_surroundings names a neighbour "left" when it sits at lane + 1 and "right" at lane - 1: a lane-index convention. Manoeuvre detection can only see the lateral coordinate, and whether a vehicle moving towards a larger pos_lat moves towards a larger or a smaller lane index is a property of how the dataset was built, not something either module may assume.

Getting it backwards does not fail loudly. The manoeuvre is still detected and its start and end lanes are still right, because those are read from the lane column. Only the neighbours in the target lane at the start of the manoeuvre are read from the wrong side. On an edge lane that yields NaN; anywhere else it yields the neighbours of the lane the vehicle was moving away from, which looks entirely plausible in the output.

The relation is therefore measured rather than assumed: the sign of the slope of the per-lane median lateral position against the lane index.

Since lane IDs follow conventions (lane 1 rightmost, increasing to the left) and pos_lat > 0 is left of travel, the pipeline itself no longer needs this; the function is kept as a diagnostic, and returns +1 for any output that follows the conventions.

Parameters:

Name Type Description Default
df_points TrackFrame

Trajectory samples with a lane column and a lateral coordinate.

required
lane_col str

Column of the lane index.

LANE
lat_col str

Column of the lateral coordinate [m]. Must be the absolute lateral position, not an offset from the lane centre: an offset has the same median in every lane and carries no slope.

POS_LAT

Returns:

Type Description
int

+1 if the lateral coordinate grows with the lane index, -1 if it falls. Falls back to +1 when a

int

column is missing or fewer than two lanes are present, that being the convention of a lateral axis measured

int

from the right-hand road edge with lane indices counting towards the left.

get_closest_lane

get_closest_lane(pos_lat: float, lane_centers: Mapping[int, float]) -> int

Return the lane whose centre is closest to a lateral position.

Parameters:

Name Type Description Default
pos_lat float

Lateral position [m].

required
lane_centers Mapping[int, float]

Lane ID -> lateral centre [m].

required

Returns:

Type Description
int

The lane ID with the smallest |pos_lat - centre| (the first one in lane_centers order on ties).

apply_lane_correction

apply_lane_correction(df: TrackFrame, lat_speed_threshold_mps: float = 0.1, min_displacement_m: float = 1.5, median_kernel_sec: float = 0.167, sewma_halfwidth_sec: float = 0.5, alpha: float | None = None, sewma_width_sec: float = SEWMA_WIDTH_DEFAULT_SEC) -> tuple[TrackFrame, EventFrame, dict[int, float]]

Classify the lateral manoeuvres and correct the lane assignment at the crossovers.

Runs detect_lane_changes to find the lateral manoeuvre intervals of every vehicle and classifies each interval:

  • "lane_change": during the interval the lateral position crosses the boundary between the start-lane centre and the next lane centre in the direction of the movement, and the corrected lane (lane_fixed) before time_start differs from the one after time_end. For a track that starts (ends) inside the interval, the lane nearest to its first (last) observed position counts as the lane before (after).
  • "lateral_excursion": otherwise. This includes moves that stay inside a lane and aborted lane changes: a vehicle that crosses the boundary during the interval but then returns (slowly enough that the return is not detected as a manoeuvre of its own) has the same lane before and after, so the interval is an excursion. A return that is fast enough to be detected is a second interval; the two crossings then form a lane change and a lane change back.

Only lane changes create crossover points and set is_changing_lane. The crossover is the first sample beyond the boundary midpoint between the two lane centres. Between crossovers, lane_fixed is the lane whose centre is nearest to the segment's mean pos_lat. Excursions leave lane_fixed unchanged and set is_lateral_excursion for their window.

Vehicles without any lane change are handled by comparing the lateral median at the start vs. end of the trajectory. If they differ (a lane change too slow to be detected), a single crossover is placed where the boundary is crossed (the middle sample if it never is); its direction comes from the lane-centre positions, and is_changing_lane is set within 3 s of it. Vehicles whose start and end lanes agree get the lane nearest to their median pos_lat throughout.

Lane centres are the median pos_lat of the lanes with more than 100 samples (the auxiliary lane with any number; all assigned lanes if none qualifies).

Parameters:

Name Type Description Default
df TrackFrame

Trajectory samples with at least id, datum, pos_lon, pos_lat, lane and speed. It is not modified.

required
lat_speed_threshold_mps float

Detection threshold on the smoothed lateral speed [m/s] (detect_lane_changes).

0.1
min_displacement_m float

Minimum lateral displacement of an interval [m] (detect_lane_changes).

1.5
median_kernel_sec float

Width of the median filter [s] (detect_lane_changes).

0.167
sewma_halfwidth_sec float

Half-width of the SEWMA kernel [s] (detect_lane_changes).

0.5
alpha float | None

Deprecated per-sample SEWMA decay factor (see detect_lane_changes); None uses sewma_width_sec.

None
sewma_width_sec float

SEWMA kernel width [s].

SEWMA_WIDTH_DEFAULT_SEC

Returns:

Type Description
TrackFrame

(df_corrected, events, lane_centers):

EventFrame
  • df_corrected: the samples sorted by id and time with the added columns lane_fixed (corrected lane), is_changing_lane and is_lateral_excursion (bool).
dict[int, float]
  • events: one row per detected interval (detect_lane_changes columns) plus event_type (EVENT_LANE_CHANGE or EVENT_LATERAL_EXCURSION), time_cross (boundary crossing, lane changes only), lane_before / lane_after (lane_fixed just before time_start / just after time_end) and max_lateral_offset_m [m] (excursions only: the largest signed offset from the start-lane centre in the interval, positive = left). Time columns keep the time zone of df.
tuple[TrackFrame, EventFrame, dict[int, float]]
  • lane_centers: lane ID -> median lateral position [m].

resolve_in_lane_conflicts

resolve_in_lane_conflicts(df: TrackFrame, lane_centers: Mapping[int, float], aux_lane_zones: Sequence[AuxLaneZone] | None = None) -> TrackFrame

Resolve space-time overlaps where two vehicles share the same lane position.

Scans each time stamp (and recording, if present) for pairs of vehicles assigned to the same lane whose longitudinal extents overlap (distance of the positions < sum of the half-lengths + 1 m; vehicles without length use conventions.DEFAULT_VEHICLE_LENGTH_M). Each conflicting pair is reassigned to the lane pair (lower pos_lat to the lane with the lower centre) with the smallest total lateral distance to the lane centres.

Before that, vehicles flagged as is_changing_lane at the very start or end of their observation are snapped to the laterally nearest lane centre over these edge segments.

Lane validity: the auxiliary lane (0) is a candidate only for points whose pos_lon lies inside one of aux_lane_zones; outside the zones neither the overlap reassignment nor the edge snapping can choose lane 0. The numbers of conflicts found and resolved are logged.

Parameters:

Name Type Description Default
df TrackFrame

Trajectory samples with id, datum, pos_lon, pos_lat, lane_fixed and is_changing_lane; length [m] and recording are used if present.

required
lane_centers Mapping[int, float]

Lane ID -> median lateral position [m] (from apply_lane_correction).

required
aux_lane_zones Sequence[AuxLaneZone] | None

AuxLaneZone intervals (pos_lon [m]) in which lane 0 may be assigned; None for none (lane 0 is never chosen where other lanes exist).

None

Returns:

Type Description
TrackFrame

A copy of df sorted by time and pos_lon with lane_fixed updated and the boolean column

TrackFrame

lane_conflict_resolved, True on every row whose lane_fixed this function changed (edge snapping and

TrackFrame

overlap reassignment), so that such rows can be filtered downstream.

Derive the lane geometry of a site: lane tracks, ramp classification, lane assignment and label checks.

The functions work in the Frenet frame of a processing.reference_line.road_reference.RoadReference that runs parallel to the lanes, so that a physical lane has a nearly constant lateral offset d along s. The lane layout comes from a map (direction_reference + RoadReference.lane_layout on OpenDRIVE boundaries) or, for sites without a map, from the vehicles (layout_from_trajectories: peaks of the lateral-position density per section).

  • lane_tracks: links the lane intervals of consecutive sections into tracks (one per physical lane), with start, end, width at the ends, the drift of d and the map types along the track.
  • classify_site: main lanes (tracks continuous over the observed section, counted from the left) and the auxiliary lane next to the rightmost main lane, classified as acceleration_lane_drop (enters from a ramp or starts inside the section and ends with a taper in view), lane_add (continues to the end of view and the main lane count grows), weaving (leaves as an exit lane), diverge (exit lanes only) or unclear; with the evidence used.
  • assign_lanes_geometric: lane per point in the pipeline convention (1 = rightmost main lane, increasing to the left; 0 = auxiliary lane next to lane 1; -1 elsewhere), with a hysteresis band at the lane boundaries.
  • check_labels: provider labels that cover two physical lanes (bimodal d within one label and section) or two labels that describe one physical lane.

Runs shorter than 1 s are merged later by the pipeline's lane cleaning (trajectory_frame), as for every source.

Lane convention: 1 = rightmost main lane, increasing to the left; 0 = auxiliary lane; -1 = not assigned. s [m] runs along the travel direction, d [m] is positive to the left.

direction_reference

direction_reference(boundaries: DataFrame, x: ArrayLike, y: ArrayLike, ids: ArrayLike, bin_m: float = 5.0, ds: float = 0.5) -> tuple[RoadReference, pd.DataFrame]

Build the reference line of one travel direction parallel to its lanes from an OpenDRIVE map.

  1. A provisional reference from the vehicles (RoadReference.from_trajectories), oriented along travel.
  2. The map's drivable lanes are projected; lanes outside the lateral range of the vehicles (opposite carriageway) are dropped.
  3. In bins along s the leftmost drivable driving lane is taken; its centre points (continuous across roads) give the final reference by a smoothing spline. Main lanes are then parallel to it.

Parameters:

Name Type Description Default
boundaries DataFrame

OpenDRIVE lane boundaries (rows as read for RoadReference.lane_layout, with type, x_centre, y_centre).

required
x ArrayLike

Vehicle x positions of the direction [m], map coordinates.

required
y ArrayLike

Vehicle y positions [m], same length.

required
ids ArrayLike

Vehicle ID per point, used to orient the line along travel.

required
bin_m float

Bin length along s [m] for picking the leftmost lane.

5.0
ds float

Sample spacing of the reference line [m].

0.5

Returns:

Type Description
RoadReference

(reference, layout): the reference line and the lane layout (RoadReference.lane_layout columns)

DataFrame

projected into its frame and restricted to the lateral range of the direction's vehicles.

layout_from_trajectories

layout_from_trajectories(s: ArrayLike, d: ArrayLike, bin_m: float = 25.0, bw: float = 0.35, min_share: float = 0.03, min_sep: float = 2.5) -> pd.DataFrame

Estimate the lane centres per section from the vehicles alone, for sites without a map.

Per bin_m section the peaks of a Gaussian kernel density of d are the lane centres; the boundaries lie halfway between neighbouring centres (outer lanes: half the median lane width, 3.6 m with a single lane). Sections with fewer than 50 points are skipped.

Parameters:

Name Type Description Default
s ArrayLike

Longitudinal positions [m].

required
d ArrayLike

Lateral positions [m], same length.

required
bin_m float

Section length [m].

25.0
bw float

Kernel bandwidth [m].

0.35
min_share float

Minimum share of the section's points within +-1 m of a peak.

0.03
min_sep float

Minimum distance between two centres [m] (the higher peak wins).

2.5

Returns:

Type Description
DataFrame

One row per (section, lane) with the columns of RoadReference.lane_layout: road ("est"),

DataFrame

section, lane (0 = rightmost, counted to the left), side, type ("estimated"), width

DataFrame

[m], s_ref (section centre [m]), d_centre, d_inner, d_outer [m].

lane_tracks

lane_tracks(layout: DataFrame, bin_m: float = 10.0, link_m: float = 1.5, min_width: float = 0.5) -> pd.DataFrame

Link the lanes of consecutive sections into tracks, one per physical lane.

Per section of bin_m the lanes (median over duplicate map lanes less than 1 m apart in d) are linked to the previous section's lanes by the nearest d within link_m; unlinked lanes start a new track.

Parameters:

Name Type Description Default
layout DataFrame

Lane layout (RoadReference.lane_layout or layout_from_trajectories columns).

required
bin_m float

Section length [m].

10.0
link_m float

Maximum lateral distance [m] to link a lane to a track of the previous section.

1.5
min_width float

Lanes narrower than this [m] are ignored.

0.5

Returns:

Type Description
DataFrame

One row per (track, section) with track, k (section index), s (section centre [m]), d [m],

DataFrame

width [m] and type.

classify_site

classify_site(tracks: DataFrame, s_range: tuple[float, float], coverage: float = 0.9, taper_m: float = 2.0, occupancy: DataFrame | None = None, empty_share: float = 0.05) -> dict[str, Any]

Identify the main lanes, the auxiliary lane and the ramp class of one direction (see module docstring).

A track is a main lane if it covers at least coverage of the observed sections, is not of an exit type and is a through lane (driving or estimated) where the view begins. The auxiliary lane is, among the tracks right of the rightmost main lane and less than 5.5 m from it, the longest one.

With occupancy (track_occupancy) a track counts as used in a section when it holds at least empty_share of its median occupancy over the sections where it is used; a track's start and end are then taken from its use, and a map lane that is empty where the view begins (e.g. a hatched area that later becomes an added lane) is not a main lane.

Parameters:

Name Type Description Default
tracks DataFrame

Lane tracks (lane_tracks).

required
s_range tuple[float, float]

Observed section (s_min, s_max) [m] (the vehicles' 1-99 % range of s).

required
coverage float

Minimum share of the observed sections a main lane covers.

0.9
taper_m float

Width [m] at the end below which the auxiliary lane counts as tapered.

2.0
occupancy DataFrame | None

Points per (track, section) (track_occupancy); None ignores the use of the lanes.

None
empty_share float

Share of a track's median occupancy below which it counts as unused in a section.

0.05

Returns:

Type Description
dict[str, Any]

A dict with class ("acceleration_lane_drop", "lane_add", "weaving", "diverge",

dict[str, Any]

"no_auxiliary_lane" or "unclear") and evidence (text); with main lanes also n_main_lanes,

dict[str, Any]

main_tracks (track IDs from the left) and d_main [m]; with an auxiliary lane also aux_track,

dict[str, Any]

aux_s (start and end [m]) and aux_d [m].

nearest_track

nearest_track(s: ArrayLike, d: ArrayLike, tracks: DataFrame) -> tuple[npt.NDArray[np.int_], npt.NDArray[np.int_], FloatArray]

Return per point the nearest lane track of its section.

Points beyond the last section use the last one, points before the first section the first one.

Parameters:

Name Type Description Default
s ArrayLike

Longitudinal positions [m].

required
d ArrayLike

Lateral positions [m], same length.

required
tracks DataFrame

Lane tracks (lane_tracks).

required

Returns:

Type Description
NDArray[int_]

(track_id, k, to_boundary): the nearest track (-1 if farther than half its width + 0.5 m), the section

NDArray[int_]

index and the distance [m] to the nearest boundary between neighbouring lanes (inf with a single lane).

track_occupancy

track_occupancy(s: ArrayLike, d: ArrayLike, tracks: DataFrame) -> pd.DataFrame

Count the vehicle points per (track, section): which lanes are actually used where.

Parameters:

Name Type Description Default
s ArrayLike

Longitudinal positions [m].

required
d ArrayLike

Lateral positions [m], same length.

required
tracks DataFrame

Lane tracks (lane_tracks).

required

Returns:

Type Description
DataFrame

Columns track, k (section index) and n (number of points); points outside every track are left

DataFrame

out.

assign_lanes_geometric

assign_lanes_geometric(s: ArrayLike, d: ArrayLike, tracks: DataFrame, site: Mapping[str, Any], ids: ArrayLike | None = None, hysteresis_m: float = 0.3) -> npt.NDArray[np.int_]

Return the lane per point in the pipeline convention from the lane tracks and the site classification.

Main lanes are numbered 1 (rightmost) upwards, 0 is the auxiliary lane, -1 elsewhere (other ramps, shoulders, outside a lane). Per point the nearest lane centre of its section decides (nearest_track).

Parameters:

Name Type Description Default
s ArrayLike

Longitudinal positions [m].

required
d ArrayLike

Lateral positions [m], same length.

required
tracks DataFrame

Lane tracks (lane_tracks).

required
site Mapping[str, Any]

Classification of the direction (classify_site); uses main_tracks and aux_track.

required
ids ArrayLike | None

Vehicle ID per point (points in time order per vehicle) for the hysteresis; None disables it.

None
hysteresis_m float

A point within this distance [m] of the boundary between two lanes keeps the lane of the previous point of the same vehicle; 0 disables it.

0.3

Returns:

Type Description
NDArray[int_]

Lane per point.

check_labels

check_labels(s: ArrayLike, d: ArrayLike, labels: ArrayLike, bin_m: float = 50.0, min_n: int = 200, split_m: float = 2.5) -> pd.DataFrame

Check provider lane labels against the lateral geometry.

A label covers two lanes in a section when the density of d has two peaks, each holding at least 15 % of the label's points there, at least split_m apart (layout_from_trajectories); two labels describe one lane when their medians differ by less than 1 m in the same section.

Parameters:

Name Type Description Default
s ArrayLike

Longitudinal positions [m].

required
d ArrayLike

Lateral positions [m], same length.

required
labels ArrayLike

Provider lane label per point.

required
bin_m float

Section length [m].

50.0
min_n int

Minimum number of points of a label in a section to check it.

200
split_m float

Minimum distance [m] between the two peaks of a bimodal label.

2.5

Returns:

Type Description
DataFrame

One row per checked (section, label) with k (section index), label, n, median [m],

DataFrame

spread (p5-p95 range [m]), bimodal and same_as (the next label to the left with a median less

DataFrame

than 1 m away, or empty); empty without columns if no label has min_n points in a section.

opendrive_site_geometry

opendrive_site_geometry(boundaries: DataFrame, x: ArrayLike, y: ArrayLike, ids: ArrayLike, offset: tuple[float, float] = (0.0, 0.0), bin_m: float = 10.0) -> dict[str, Any]

Derive reference, layout, lane tracks and classification of one travel direction from an OpenDRIVE map.

Parameters:

Name Type Description Default
boundaries DataFrame

OpenDRIVE lane boundaries (see direction_reference).

required
x ArrayLike

Vehicle x positions of the direction [m] in the map frame (map = UTM minus offset).

required
y ArrayLike

Vehicle y positions [m], same length.

required
ids ArrayLike

Vehicle ID per point.

required
offset tuple[float, float]

(x, y) offset [m] of the map frame against UTM.

(0.0, 0.0)
bin_m float

Section length of the lane tracks [m].

10.0

Returns:

Type Description
dict[str, Any]

A dict with reference (RoadReference shifted back by offset, i.e. in UTM), layout (in the

dict[str, Any]

Frenet frame), tracks (lane_tracks), site (classify_site) and s_range (the vehicles'

dict[str, Any]

1-99 % range of s [m]).

Estimate the lane centres of a direction from the lateral positions and assign a lane to each sample.

A sliding window along pos_lon fits a Gaussian mixture to the lateral positions (free components selected by BIC, or the restricted mixture of Chen & Krumm 2010 with equally spaced lanes); the window centres are tracked across windows by Hungarian matching and every sample gets the nearest tracked centre. The raw track IDs are then numbered by lateral order (collapse_and_standardize_lanes).

Conventions: pos_lon [m] runs along the travel direction, pos_lat [m] is positive to the left; lane 0 is the auxiliary or ramp lane, 1 the rightmost main lane (increasing to the left), -1 not assigned.

fit_restricted_gmm

fit_restricted_gmm(y: ArrayLike, k: int, eta: float = 3.75, kappa: float = 100.0, nu: float = 3.0, varsigma2: float = 0.25, aux: bool = False, init: dict[str, Any] | None = None, max_iter: int = 200, tol: float = 1e-06) -> dict[str, Any]

Fit the restricted Gaussian mixture of Chen & Krumm (2010) to lateral positions by MAP-EM.

Main-lane component j = 1..k has mean mu + (j - 1) dmu (lanes equally spaced, lane 1 the rightmost = lowest d) and the shared variance sigma2. Priors (Chen & Krumm 2010, Sec. 3.3): weights and mu uniform; sigma2 ~ Inv-Gamma(nu / 2, varsigma2 / 2) (prior mean varsigma2 / (nu - 2)); dmu | sigma2 ~ N(eta, sigma2 / kappa). With aux an extra component (auxiliary lane, right of lane 1) with its own mean and variance (same variance prior) is fitted outside the spacing constraint.

M-step (closed form; g_ij responsibilities, N_j = sum_i g_ij, S_j = sum_i g_ij y_i, c_j = j - 1):

  • w_j = N_j / n;
  • (mu, dmu) solve [[sum N_j, sum c_j N_j], [sum c_j N_j, sum c_j^2 N_j + kappa]] (mu, dmu)^T = (sum S_j, sum c_j S_j + kappa eta)^T (weighted least squares with the prior on dmu);
  • sigma2 = (varsigma2 + kappa (dmu - eta)^2 + SS) / (N_main + nu + 3) with SS = sum_ij g_ij (y_i - mu - c_j dmu)^2.

These are the updates of Chen & Krumm (2010), Appendix A (their system A (mu, dmu)^T = b is the one above divided by n). Addition for auxiliary-lane zones (not in the paper): a free component with a = S_0 / N_0 and tau2 = (varsigma2 + SS_0) / (N_0 + nu + 2) (same variance prior, flat prior on its mean).

Parameters:

Name Type Description Default
y ArrayLike

Lateral positions [m].

required
k int

Number of main lanes.

required
eta float

Prior mean of the lane spacing dmu [m].

3.75
kappa float

Prior strength of the lane spacing (dmu | sigma2 ~ N(eta, sigma2 / kappa)).

100.0
nu float

Degrees of freedom of the inverse-gamma prior on the variances.

3.0
varsigma2 float

Scale of the inverse-gamma prior on the variances [m^2].

0.25
aux bool

If True, add the auxiliary-lane component.

False
init dict[str, Any] | None

Start values {"mu", "dmu", "sigma2", "weights", "aux_mean", "aux_var"} (warm start from the previous window, e.g. a previous result of this function); None starts from a grid search over mu with dmu = eta.

None
max_iter int

Maximum number of EM iterations.

200
tol float

Stopping tolerance on the relative change of the log posterior [-].

1e-06

Returns:

Type Description
dict[str, Any]

A dict with mu [m] (centre of lane 1), dmu [m] (lane spacing), sigma2 [m^2], weights

dict[str, Any]

(main lanes, lane 1 first), means [m] (main-lane centres, lane 1 first), aux_mean [m],

dict[str, Any]

aux_var [m^2] and aux_weight (NaN, NaN and 0 without aux), n_iter and log_posterior.

estimate_lanes_rolling_tracker

estimate_lanes_rolling_tracker(df_direction: TrackFrame, lon_step: float = 50.0, window_size: float = 200.0, max_lanes: int = 4, max_drift: float = 2.0, lon_col: str = C.POS_LON, lat_col: str = C.POS_LAT, aux_lane_zones: Sequence[AuxLaneZone] | None = None, gmm_model: Literal['free', 'restricted'] = 'free', gmm_priors: dict[str, float] | None = None, lane_count_zones: list[LaneCountZone] | None = None) -> tuple[TrackFrame, pd.DataFrame, pd.DataFrame]

Extract and track the lanes of one direction with a rolling GMM and Hungarian matching.

Processes trajectory data using a sliding longitudinal window. Within each window, fits Gaussian Mixture Models (GMM) of varying component counts to the lateral positions and selects the best-fitting number of lanes using the Bayesian Information Criterion (BIC). A minimum lane separation of 2.5 m is enforced to prevent spurious components.

Lane identities are tracked across windows using the Hungarian algorithm (linear sum assignment) to minimise the total drift distance between consecutive GMM centroids. Lanes that miss more than MAX_MISSED_FRAMES (10) consecutive windows are removed. Each point is then assigned to the nearest active lane centroid.

The returned lane IDs are raw tracking IDs (1, 2, ... in order of appearance, never 0); collapse_and_standardize_lanes numbers them by lateral order afterwards. Points that are never assigned stay -1.

Auxiliary lanes: inside an AuxLaneZone every point to the right of the rightmost main lane (its local centre minus half the local lane width) gets lane 0 and is left out of the GMM fit, so that the auxiliary lane does not take one of the main-lane components. In windows that touch a zone the GMM may use max_lanes + 1 components; if it does, the rightmost one is the auxiliary lane and is not tracked as a main lane (needed when a zone starts at the beginning of the section and no main lane is known yet). Outside zones lane 0 never occurs.

If the DataFrame contains a class column, GMM fitting is performed only on Car-class points; all points are classified against the fitted centroids.

Parameters:

Name Type Description Default
df_direction TrackFrame

Samples of one direction in the Frenet frame (lon_col, lat_col), optionally with a class column for the car-only fit.

required
lon_step float

Longitudinal step between window centres [m].

50.0
window_size float

Full length of the sliding window [m].

200.0
max_lanes int

Maximum number of GMM components ("free": BIC selects up to this number) or the number of main lanes ("restricted").

4
max_drift float

Maximum lateral drift [m] when matching a window centre to a tracked lane; pairs beyond it start a new lane.

2.0
lon_col str

Column of the longitudinal position [m].

POS_LON
lat_col str

Column of the lateral position [m].

POS_LAT
aux_lane_zones Sequence[AuxLaneZone] | None

AuxLaneZone intervals (pos_lon [m]) in which an auxiliary lane is assigned; None for none.

None
gmm_model Literal['free', 'restricted']

"free" (BIC over 1..max_lanes free components) or "restricted" (fit_restricted_gmm with exactly max_lanes equally spaced components, started from the grid search and from the previous window, keeping the higher posterior; plus the auxiliary-lane component in zones).

'free'
gmm_priors dict[str, float] | None

Priors of the restricted model (eta, kappa, nu, varsigma2) overriding RESTRICTED_GMM_PRIORS.

None
lane_count_zones list[LaneCountZone] | None

LaneCountZone intervals (lane gain or drop). Each window uses the main-lane count at its centre (max_lanes outside the zones): exactly that many components for "restricted", at most that many for "free". Tracked lanes left without a centre where the count drops are removed at once, and lane centres are not back-filled over more than one window (a lane that starts later must not appear earlier).

None

Returns:

Type Description
TrackFrame

(df_labeled, df_lane_boundaries, df_lane_centers):

DataFrame
  • df_labeled: copy of the input with the column lane: raw main-lane tracking IDs (>= 1), 0 for the auxiliary lane, -1 for unassigned samples.
DataFrame
  • df_lane_boundaries: columns km (window centre, pos_lon [m]) and boundary (lateral position of a lane boundary [m]).
tuple[TrackFrame, DataFrame, DataFrame]
  • df_lane_centers: columns km_bin (window centre [m]), lane (raw ID) and center_y (tracked lane centre [m]). Its attrs["windows"] holds one row per window: km_bin, n_fit (main-lane centres of the window fit), n_tracked (tracked lanes before the window), n_matched and lane_lost (a tracked lane got no centre of the window fit). The attrs entry is missing when no lane centre was found.

Raises:

Type Description
ValueError

If gmm_model is neither "free" nor "restricted" (checked after the early return for fewer than 10 samples).

collapse_and_standardize_lanes

collapse_and_standardize_lanes(df: TrackFrame, max_lanes: int, lat_col: str = C.POS_LAT, random_state: int = 42) -> TrackFrame

Number the main lanes by lateral order and collapse surplus tracks.

After the rolling-window GMM tracker runs, raw main-lane IDs are in order of appearance and may be fragmented (e.g. 1, 4, 7) or more than the road has lanes. This function always renumbers them strictly by lateral position: the lowest pos_lat band (rightmost lane) becomes 1, the next one to the left 2, and so on.

  • If there are at most max_lanes raw main lanes, they are ranked by their median lateral position.
  • Otherwise 1D KMeans with max_lanes clusters is fitted on the lateral positions of the main-lane points (on a reproducible random sample of at most 10 000 points), and each raw lane is mapped to its nearest cluster centre, numbered from right to left.

The auxiliary lane (0) and unassigned points (-1) are kept as they are and never mapped to a main-lane ID.

Parameters:

Name Type Description Default
df TrackFrame

Samples with a lane column (raw lane IDs) and the lateral position column.

required
max_lanes int

Number of main lanes (PipelineConfig.n_main_lanes).

required
lat_col str

Column of the lateral position [m] used to order the lanes.

POS_LAT
random_state int

Seed of the KMeans sample and initialisation.

42

Returns:

Type Description
TrackFrame

A copy of df with the main lanes renumbered to 1..max_lanes (or fewer if fewer lanes are observed);

TrackFrame

unchanged copy if df is empty, has no lane column or no main-lane sample.

Estimate the lane geometry and label every sample with a lane (page 06 of the pipeline steps 01-10).

estimate_lane_geometry is the entry function of the step: the rolling GMM lane tracker (geometry) labels the samples, the labels are numbered from the right and the lane centers are summarized with their stability diagnostics (lane_geometry_diagnostics).

LaneGeometryParams dataclass

LaneGeometryParams(lon_step_m: float = 50.0, window_size_m: float = 200.0, max_drift_m: float = 2.0, gmm_model: str = 'restricted', gmm_prior_eta_m: float = 3.75, gmm_prior_kappa: float = 100.0, gmm_prior_nu: float = 3.0, gmm_prior_varsigma2_m2: float = 0.25, direction_consistency_min: float = 0.9)

Parameters of estimate_lane_geometry; defaults of the preset drone_hgv_paper.

Attributes:

Name Type Description
lon_step_m float

Step of the rolling window along pos_lon [m]. Defaults to 50.0.

window_size_m float

Length of the rolling window [m]. Defaults to 200.0.

max_drift_m float

Largest lateral drift [m] of a tracked lane center between two windows. Defaults to 2.0.

gmm_model str

"restricted" (equal lane widths, Chen & Krumm 2010) or "free". Defaults to "restricted".

gmm_prior_eta_m float

Prior lane width [m] of the restricted GMM. Defaults to 3.75.

gmm_prior_kappa float

Prior strength of the lane width. Defaults to 100.0.

gmm_prior_nu float

Prior degrees of freedom of the lane variance. Defaults to 3.0.

gmm_prior_varsigma2_m2 float

Prior lane variance [m^2]. Defaults to 0.25.

direction_consistency_min float

Minimum share (0-1) of vehicles whose pos_lon increases. Defaults to 0.9.

priors

priors() -> dict[str, float]

Return the GMM priors as the tracker takes them.

Returns:

Type Description
dict[str, float]

eta, kappa, nu and varsigma2.

LaneGeometryResult dataclass

LaneGeometryResult(tracks: TrackFrame, centers: DataFrame, diagnostics: dict[str, Any] | None)

Result of estimate_lane_geometry.

Attributes:

Name Type Description
tracks TrackFrame

The samples with lane.

centers DataFrame

Lane centers per window (km_bin, lane, center_y [m]), lanes numbered like lane; empty if no sample was labeled.

diagnostics dict[str, Any] | None

Stability of the geometry (lane_geometry_diagnostics); None if no sample was labeled.

estimate_lane_geometry

estimate_lane_geometry(tracks: TrackFrame, *, params: LaneGeometryParams | None = None, layout: LaneLayout | None = None) -> LaneGeometryResult

Track the lanes with a rolling GMM along the road and label every sample with its lane.

Entry function of page 06 of the pipeline steps 01-10 (docs/pipeline/06_lane_geometry.md). Requires the columns id, datum, pos_lon and pos_lat [m] (project_to_reference_line, best after align_lateral_positions) and adds lane (0 auxiliary lane, 1 rightmost main lane, -1 not assigned). Method: Gaussian mixtures in rolling windows along pos_lon, restricted to equal lane widths after Chen & Krumm (2010), lane centers tracked from window to window.

Example

import trajlab from trajlab.processing.lanes import estimate_lane_geometry from trajlab.processing.reference_line import project_to_reference_line from trajlab.road_layout import LaneLayout raw = trajlab.examples.synthetic_motorway() ref_east, _ = trajlab.estimate_ref_lines(raw) tracks = project_to_reference_line(raw[raw["orientation"] > 0], ref_east) labeled = estimate_lane_geometry(tracks, layout=LaneLayout(n_main_lanes=3)).tracks

Parameters:

Name Type Description Default
tracks TrackFrame

Samples of one direction of travel. Not modified.

required
params LaneGeometryParams | None

Parameters; None uses LaneGeometryParams().

None
layout LaneLayout | None

Number of main lanes and the zones of the site; None uses LaneLayout() (3 lanes, no zones).

None

Returns:

Type Description
LaneGeometryResult

The labeled samples, the lane centers and the diagnostics.

lane_geometry_diagnostics

lane_geometry_diagnostics(windows: DataFrame, centers: DataFrame, gmm_model: str) -> dict[str, Any]

Summarise the stability of the Step 4 geometry: lost-lane windows and the spread of each lane centre along s.

Parameters:

Name Type Description Default
windows DataFrame

Per-window records of the tracker (attrs["windows"] of its centre table).

required
centers DataFrame

Standardised lane centres (km_bin, lane, center_y [m]).

required
gmm_model str

The GMM model used ("free" or "restricted"), recorded as is.

required

Returns:

Type Description
dict[str, Any]

A dict with gmm_model, windows and, if available, windows_lane_lost, windows_lane_lost_share

dict[str, Any]

(share of the windows with tracked lanes in which a tracked lane got no centre of the window fit) and

dict[str, Any]

centre_sd_m (per standardised lane, the standard deviation [m] of its centre over the windows; on a

dict[str, Any]

road of constant cross-section after alignment ideally ~0).

Assign lanes with a hidden Markov model (lanes.assignment_method = "hmm").

Plain-language overview:

The lane a vehicle is in cannot be observed directly; only its lateral position d (pos_lat) is measured, with noise and with the vehicle wandering inside its lane. A hidden Markov model (HMM) describes this with two ingredients:

  • Emission: how likely a measured d is if the vehicle is in lane k. Here: a bell curve (Gaussian) around the lane centre c_k(s) at the vehicle's longitudinal position s, with the lane's lateral spread sigma_k; a small floor epsilon keeps single outliers from forcing a lane change (see emission_logprob for the two floor variants).
  • Transition: how likely the vehicle switches to a neighbouring lane between two samples. Switching is rare in general (rate_background per second) but likely inside an interval in which the lane-change detector of Step 5 saw a lateral manoeuvre, towards the detected side (rate_in_event per second). Rates are per second and converted to a probability per sample with p = 1 - exp(-rate * dt), so the model behaves the same at 10, 25 or 30 Hz. Jumps over more than one lane per sample are impossible.

From these, two standard algorithms compute

  • the single most probable lane sequence of the whole track (Viterbi): it trades off "stay close to a lane centre" against "do not switch without reason" over the whole trajectory at once, instead of deciding each sample on its own;
  • for every sample the probability of each lane given all measurements of the track (forward-backward; this probability is the posterior). The posterior of the chosen lane is reported as lane_confidence and its lead over the second-best lane as lane_posterior_margin.

All computations run in log space (sums of logarithms instead of products of small probabilities; log-sum-exp for sums of probabilities), which is numerically stable. Many vehicles are processed together as one padded array, so the cost is O(T * K) per vehicle with K <= 6 lanes, vectorised over vehicles.

Events:

Every change of the decoded lane is a lane change at the first sample in the new lane. If it lies inside a detector interval, the interval gives start and end (detected_by = "detector+hmm"); otherwise start and end are found by following the smoothed lateral velocity backwards and forwards until it drops below the detector threshold (detected_by = "hmm", e.g. slow drifts the detector misses). A detector interval without a lane change is a lateral_excursion. A change A -> B -> A inside one detector interval is collapsed to A and the interval counts as an excursion (as in the heuristic correction). Consecutive detector intervals less than merge_gap_s (1 s) apart count as one interval here: the detector often splits an excursion into the move out and the move back.

Space-time feasibility (resolve_conflicts_hmm) and the alternating estimation of lanes and lane geometry (em_lane_assignment) build on the per-vehicle decoding.

Conventions: pos_lon (s) [m] runs along the travel direction, pos_lat (d) [m] is positive to the left; lane 0 is the auxiliary or ramp lane, 1 the rightmost main lane (increasing to the left), -1 not assigned.

LaneGeometry dataclass

LaneGeometry(s: FloatArray, centers: dict[int, FloatArray], sigma: dict[int, float], zones: list[AuxLaneZone] = list(), lat_range: tuple[float, float] = (-5.0, 15.0), zone_margin_m: float = 10.0, extrapolate: bool = True, extrapolate_margin_m: float = 25.0)

Lane centres along the road and lateral spreads.

Attributes:

Name Type Description
s FloatArray

Increasing longitudinal positions [m] at which the centres are given.

centers dict[int, FloatArray]

Lane ID -> centre [m] at s (NaN where the lane is not known; interpolated between the known values by center_at).

sigma dict[int, float]

Lane ID -> lateral spread [m].

zones list[AuxLaneZone]

AuxLaneZone list; lane 0 is a valid state only inside.

lat_range tuple[float, float]

(min, max) of the observed lateral positions [m], for the uniform outlier floor.

zone_margin_m float

Lane 0 stays valid this far [m] beyond both ends of a zone, so that a vehicle observed from (until) the very end of a zone is not forced into lane 1 by a few samples just outside it.

extrapolate bool

True (default) holds the centres constant beyond a lane's known range. False (set when lane-count zones are configured): a lane exists only within its known range +- extrapolate_margin_m and is an impossible state elsewhere (lane gain or drop).

extrapolate_margin_m float

Margin [m] of the known range when extrapolate is False.

lanes property

lanes: list[int]

Lane IDs in increasing order.

center_at

center_at(lane: int, s: FloatArray) -> FloatArray

Return the centre of one lane at the given longitudinal positions.

Linear between the known values, constant beyond the known range (with extrapolate; NaN beyond the range plus margin without it); all NaN if the lane has no known value.

Parameters:

Name Type Description Default
lane int

Lane ID (a key of centers).

required
s FloatArray

Longitudinal positions [m].

required

Returns:

Type Description
FloatArray

Lateral centre of the lane per position [m].

in_zone

in_zone(s: FloatArray) -> npt.NDArray[np.bool_]

Return whether each position lies in an auxiliary-lane zone, i.e. where lane 0 is a valid state.

Parameters:

Name Type Description Default
s FloatArray

Longitudinal positions [m].

required

Returns:

Type Description
NDArray[bool_]

Boolean mask, True inside a zone extended by zone_margin_m at both ends.

HmmParams dataclass

HmmParams(rate_in_event: float = 2.0, rate_background: float = 0.001, sigma_floor_m: float = 0.4, epsilon: float = 0.001, emission_floor: Literal['relative', 'uniform'] = 'relative', merge_gap_s: float = 1.0, max_dwell_s: float = 2.0, aux_lane_fallback: bool = True, batch_samples: int = 2000000)

Model parameters (see config.HmmConfig).

Attributes:

Name Type Description
rate_in_event float

Rate [1/s] of a lane switch towards the detected side inside a detector interval.

rate_background float

Rate [1/s] of any other lane switch.

sigma_floor_m float

Minimum lateral spread of a lane [m].

epsilon float

Weight of the outlier floor of the emission.

emission_floor Literal['relative', 'uniform']

"relative" or "uniform" (emission_logprob).

merge_gap_s float

Detector intervals less than this apart [s] count as one manoeuvre.

max_dwell_s float

Maximum time [s] in the other lane for an A -> B -> A over joined intervals to be collapsed.

aux_lane_fallback bool

Give the auxiliary lane a fallback centre when it has no samples (geometry_from_labels).

batch_samples int

Maximum number of samples decoded in one padded batch.

estimate_sigma

estimate_sigma(df: TrackFrame, geometry: LaneGeometry, label_col: str, exclude: NDArray[bool_], floor_m: float) -> dict[int, float]

Estimate the robust lateral spread per lane: 1.4826 * MAD of d - c_k(s) of the labelled points.

Parameters:

Name Type Description Default
df TrackFrame

Samples with pos_lon, pos_lat and label_col.

required
geometry LaneGeometry

Lane geometry (centers are used).

required
label_col str

Column of the lane labels.

required
exclude NDArray[bool_]

Per row of df: leave the sample out (e.g. inside detector intervals).

required
floor_m float

Minimum spread [m].

required

Returns:

Type Description
dict[int, float]

Lane ID -> spread [m], at least floor_m; max(floor_m, 0.5) for lanes with fewer than 20 samples.

geometry_from_tracker

geometry_from_tracker(lane_centers: DataFrame, df: TrackFrame, zones: Iterable[AuxLaneZone] | None, exclude: NDArray[bool_], sigma_floor_m: float = 0.4, label_col: str = C.LANE) -> LaneGeometry

Build the lane geometry from the Step 4 GMM tracker centres.

Lane 0 (auxiliary) has no tracker centre: with zones it is the median of the points labelled 0 per 50 m bin, or, where there are none, c_1 - lane width. sigma_k comes from estimate_sigma on the Step 4 labels outside exclude (detector intervals).

Parameters:

Name Type Description Default
lane_centers DataFrame

Tracker centres with km_bin [m], lane and center_y [m] (estimate_lanes_rolling_tracker); only main lanes are used.

required
df TrackFrame

Samples of the direction with pos_lon, pos_lat and label_col.

required
zones Iterable[AuxLaneZone] | None

AuxLaneZone intervals; None or empty for none.

required
exclude NDArray[bool_]

Per row of df: leave the sample out of the spread estimate.

required
sigma_floor_m float

Minimum lateral spread [m].

0.4
label_col str

Column of the Step 4 lane labels.

LANE

Returns:

Type Description
LaneGeometry

The lane geometry.

geometry_from_labels

geometry_from_labels(df: TrackFrame, label_col: str, exclude: NDArray[bool_], zones: Iterable[AuxLaneZone] | None, bin_m: float = 10.0, smooth_sigma_m: float = 30.0, min_points: int = 20, sigma_floor_m: float = 0.4, lanes: list[int] | None = None, aux_fallback: bool = True) -> LaneGeometry

Re-estimate the lane geometry from labelled points (update step of em_lane_assignment).

Per lane: median d per bin_m bin of the points with that label outside exclude; a lane exists in a bin only with at least min_points points; the profile is smoothed with a Gaussian of smooth_sigma_m. A lane without any such bin but with at least min_points points in total gets a constant centre at its median (a sparsely used lane must not disappear). sigma_k as in estimate_sigma.

Parameters:

Name Type Description Default
df TrackFrame

Samples with pos_lon, pos_lat and label_col.

required
label_col str

Column of the lane labels.

required
exclude NDArray[bool_]

Per row of df: leave the sample out (lane changes and excursions).

required
zones Iterable[AuxLaneZone] | None

AuxLaneZone intervals; None or empty for none.

required
bin_m float

Bin length along pos_lon [m].

10.0
smooth_sigma_m float

Standard deviation of the Gaussian smoothing along pos_lon [m].

30.0
min_points int

Minimum number of samples of a lane per bin.

20
sigma_floor_m float

Minimum lateral spread [m].

0.4
lanes list[int] | None

Lanes to estimate; None (or empty) uses all labels >= 0 in df. Lanes without a centre anywhere are dropped.

None
aux_fallback bool

If True and zones are given, an auxiliary lane without samples gets a centre one lane width right of lane 1 (lane width: median distance of lanes 1 and 2, else 3.75 m).

True

Returns:

Type Description
LaneGeometry

The lane geometry on bin centres covering the pos_lon range of df.

emission_logprob

emission_logprob(d: FloatArray, s: FloatArray, geometry: LaneGeometry, lanes: Sequence[int], epsilon: float, floor: Literal['relative', 'uniform'] = 'relative') -> FloatArray

Return log p(d | k) for every sample and lane: Gaussian around c_k(s) with an outlier floor.

floor = "uniform" (the specification): p(d | k) = (1 - epsilon) * N(d; c_k(s), sigma_k^2) + epsilon * U with U uniform over the observed lateral range.

floor = "relative" (default): p(d | k) = (1 - epsilon) * N_k + epsilon * max_j N_j. Both bound the influence of a single sample (no lane can be worse than the best lane by more than log(1/epsilon)), but the uniform floor also flattens the emission between two lanes: with sigma = 0.2 m and epsilon = 1e-3 both Gaussians sit on the floor in the middle 1.9 m between two centres 3.75 m apart, so the decoded crossing can fall anywhere in that band. The relative floor keeps "the closest lane wins" there.

Lane 0 outside the auxiliary-lane zones (and lanes without a centre) get log p = NEG_INF.

Parameters:

Name Type Description Default
d FloatArray

Lateral positions [m].

required
s FloatArray

Longitudinal positions [m], same length.

required
geometry LaneGeometry

Lane geometry (lanes without a sigma use 0.5 m).

required
lanes Sequence[int]

Lane IDs of the states, in increasing order.

required
epsilon float

Weight of the outlier floor, in (0, 1).

required
floor Literal['relative', 'uniform']

"relative" or "uniform" (see above).

'relative'

Returns:

Type Description
FloatArray

Log-probabilities, shape (len(d), len(lanes)).

Raises:

Type Description
ValueError

If floor is not one of EMISSION_FLOORS.

transition_logprobs

transition_logprobs(dt_s: ArrayLike, event_dir: NDArray[integer[Any]], n_states: int, rate_in_event: float, rate_background: float) -> tuple[FloatArray, FloatArray, FloatArray]

Return the log transition probabilities for the steps of one track (tridiagonal: stay, up, down).

A rate r per second becomes the probability p = 1 - exp(-r * dt) per step.

Parameters:

Name Type Description Default
dt_s ArrayLike

Time steps [s] (length T-1).

required
event_dir NDArray[integer[Any]]

Direction of a detector interval at the arrival sample of each step: +1 (left, higher lane index), -1, or 0 (none).

required
n_states int

Number of states (lanes, in increasing order).

required
rate_in_event float

Rate [1/s] of a switch towards the detected side inside a detector interval.

required
rate_background float

Rate [1/s] of any other switch.

required

Returns:

Type Description
FloatArray

(log_up, log_down, log_stay), each of shape (T-1, n_states): from state k to k+1, to k-1 and

FloatArray

staying (-inf up from the top state and down from the bottom state).

transition_tables

transition_tables(dt_s: ArrayLike, event_dir: ArrayLike, n_states: int, rate_in_event: float, rate_background: float) -> tuple[npt.NDArray[np.intp], FloatArray, FloatArray, FloatArray, FloatArray, FloatArray, FloatArray]

Return the transition probabilities as small tables plus a key per step.

dt and the detector direction take only a few distinct values, so the probabilities are computed once per distinct (dt, direction) pair (dt rounded to microseconds). Key 0 is reserved for padding (stay with probability 1).

Parameters:

Name Type Description Default
dt_s ArrayLike

Time steps [s] (length T-1).

required
event_dir ArrayLike

Detector direction at the arrival sample of each step (+1, -1 or 0).

required
n_states int

Number of states K.

required
rate_in_event float

Rate [1/s] of a switch towards the detected side inside a detector interval.

required
rate_background float

Rate [1/s] of any other switch.

required

Returns:

Type Description
NDArray[intp]

(keys, log_up, log_down, log_stay, p_up, p_down, p_stay): keys (T-1,) index into the tables;

FloatArray

tables (n_keys, K) with the (log-)probabilities from state k to k+1, to k-1 and of staying.

viterbi_batch

viterbi_batch(log_e: FloatArray, stay: FloatArray, from_below: FloatArray, from_above: FloatArray) -> npt.NDArray[np.int64]

Return the most probable state sequence of every track in a padded batch (time-major arrays).

The arrays are time-major, (T, N, K), so that every step of the time recursion reads one contiguous block of memory.

Parameters:

Name Type Description Default
log_e FloatArray

(T, N, K) emission log-probabilities (0 beyond a track's end).

required
stay FloatArray

(T-1, N, K) log-probability of staying in state k at the step t -> t+1 (0 beyond a track's end).

required
from_below FloatArray

(T-1, N, K) log-probability of arriving in k from k-1.

required
from_above FloatArray

(T-1, N, K) log-probability of arriving in k from k+1 (both NEG_INF beyond a track's end).

required

Returns:

Type Description
NDArray[int64]

(N, T) state indices; beyond a track's length the last state repeats.

forward_backward_batch

forward_backward_batch(log_e: FloatArray, stay: FloatArray, from_below: FloatArray, from_above: FloatArray, lengths: NDArray[int_], renorm_every: int = 16) -> FloatArray

Return the posteriors P(state_t = k | all samples) for a padded batch (time-major arrays).

Same transition arrays as viterbi_batch but as probabilities. Runs in probability space with periodic normalisation (the standard scaled forward-backward, numerically equivalent to the log-space recursion): emissions are exponentiated after subtracting their per-sample maximum, so per step the total mass shrinks by at most the emission floor; normalising every renorm_every steps keeps it far above the float64 limit.

Parameters:

Name Type Description Default
log_e FloatArray

(T, N, K) emission log-probabilities.

required
stay FloatArray

(T-1, N, K) probability of staying in state k.

required
from_below FloatArray

(T-1, N, K) probability of arriving in k from k-1.

required
from_above FloatArray

(T-1, N, K) probability of arriving in k from k+1.

required
lengths NDArray[int_]

(N,) number of valid samples per track.

required
renorm_every int

Normalisation interval in steps.

16

Returns:

Type Description
FloatArray

(N, T, K) posteriors; padded samples repeat the last valid one.

decode_tracks

decode_tracks(tracks: Sequence[Mapping[str, Any]], geometry: LaneGeometry, params: HmmParams, penalties: Mapping[int, FloatArray] | None = None) -> list[dict[str, Any]]

Return the Viterbi path and the posteriors for a list of tracks.

Tracks are decoded in padded batches of similar length (at most params.batch_samples samples per batch).

Parameters:

Name Type Description Default
tracks Sequence[Mapping[str, Any]]

One dict per track with t_s [s], s [m], d [m] and event_dir (per sample, see _event_direction).

required
geometry LaneGeometry

Lane geometry.

required
params HmmParams

Model parameters.

required
penalties Mapping[int, FloatArray] | None

{track index: (n_samples, K) array} added to the emission log-probabilities (conflict penalties of resolve_conflicts_hmm); None for none.

None

Returns:

Type Description
list[dict[str, Any]]

One dict per track, in the order of tracks, with lanes (decoded lane IDs), confidence

list[dict[str, Any]]

(posterior of the decoded lane) and margin (best minus second-best posterior; 1 with a single lane).

vehicle_events

vehicle_events(vid: object, times: NDArray[datetime64], lat: FloatArray, lanes: NDArray[int_], intervals: EventFrame, v_lat: FloatArray, threshold_mps: float) -> list[dict[Hashable, Any]]

Derive the lane-change and excursion events of one vehicle from its decoded lanes (see the module docstring).

Parameters:

Name Type Description Default
vid object

Vehicle ID.

required
times NDArray[datetime64]

Sample times (datetime64, time-zone naive).

required
lat FloatArray

Lateral positions [m].

required
lanes NDArray[int_]

Decoded lane per sample.

required
intervals EventFrame

The vehicle's detector intervals (detect_lane_changes columns).

required
v_lat FloatArray

Smoothed lateral velocity [m/s] (_filtered_lateral_velocity).

required
threshold_mps float

Detector threshold [m/s] that bounds a lane change outside detector intervals.

required

Returns:

Type Description
list[dict[Hashable, Any]]

One dict per lane change (event_type "lane_change", the interval's columns if the change lies in a

list[dict[Hashable, Any]]

detector interval, detected_by "detector+hmm" or "hmm") and per unused interval

list[dict[Hashable, Any]]

("lateral_excursion", detected_by "detector"), with time_cross, lane_before,

list[dict[Hashable, Any]]

lane_after and max_lateral_offset_m [m] (excursions: the largest offset from the interval's first

list[dict[Hashable, Any]]

sample).

interval_mask

interval_mask(df: TrackFrame, intervals: EventFrame | None) -> npt.NDArray[np.bool_]

Return per row of df (any order) whether it lies inside a detector interval of its vehicle.

Parameters:

Name Type Description Default
df TrackFrame

Samples with id and datum.

required
intervals EventFrame | None

Detector intervals with id, time_start and time_end; None or empty for none.

required

Returns:

Type Description
NDArray[bool_]

Boolean mask, one entry per row of df (time zones are dropped before comparing).

assign_lanes_hmm

assign_lanes_hmm(df: TrackFrame, intervals: EventFrame, geometry: LaneGeometry, params: HmmParams, threshold_mps: float = 0.1, median_kernel_sec: float = 0.167, sewma_halfwidth_sec: float = 0.5, sewma_width_sec: float = C.SEWMA_WIDTH_DEFAULT_SEC, penalties: Mapping[Hashable, FloatArray] | None = None) -> tuple[TrackFrame, EventFrame]

Decode the lanes of all vehicles with the HMM and derive the events.

Parameters:

Name Type Description Default
df TrackFrame

One direction at the native rate after Step 4 (id, datum, pos_lon, pos_lat).

required
intervals EventFrame

Detector intervals (detect_lane_changes: id, time_start, time_lc, time_end, lc_direction, ...).

required
geometry LaneGeometry

Lane geometry (geometry_from_tracker / geometry_from_labels).

required
params HmmParams

Model parameters.

required
threshold_mps float

Detector threshold [m/s], used to find start and end of lane changes the detector missed.

0.1
median_kernel_sec float

Width of the detector's median filter [s].

0.167
sewma_halfwidth_sec float

Half-width of the detector's SEWMA kernel [s].

0.5
sewma_width_sec float

Width of the detector's SEWMA kernel [s].

SEWMA_WIDTH_DEFAULT_SEC
penalties Mapping[Hashable, FloatArray] | None

{vehicle id: (n_samples, K) array} of extra emission log-probabilities (conflict penalties of resolve_conflicts_hmm), in the sample order of the vehicle sorted by time; None for none.

None

Returns:

Type Description
TrackFrame

(df_out, events): df sorted by (id, datum) with a fresh index and the columns lane_fixed,

EventFrame

lane_confidence, lane_posterior_margin, is_changing_lane, is_lateral_excursion (all

tuple[TrackFrame, EventFrame]

unassigned / NaN / False if df is empty or the geometry has no lane); and the event table (one row

tuple[TrackFrame, EventFrame]

per lane change or excursion, columns as in the heuristic apply_lane_correction plus

tuple[TrackFrame, EventFrame]

detected_by), sorted by id and time_start.

find_conflicts

find_conflicts(df: TrackFrame, margin_m: float, default_length_m: float = C.DEFAULT_VEHICLE_LENGTH_M) -> pd.DataFrame

Find pairs of rows in the same lane at the same time whose vehicles overlap longitudinally.

Two vehicles conflict if |s1 - s2| < (L1 + L2) / 2 + margin_m (centre positions). Only neighbours in pos_lon order within one (time, lane) group are compared; unassigned rows (lane_fixed -1) are ignored.

Parameters:

Name Type Description Default
df TrackFrame

Samples with id, datum, lane_fixed, pos_lon and optionally length [m].

required
margin_m float

Extra longitudinal margin [m].

required
default_length_m float

Vehicle length [m] where length is missing.

DEFAULT_VEHICLE_LENGTH_M

Returns:

Type Description
DataFrame

One row per conflict with row_a, row_b (index labels of df, row_a behind), id_a,

DataFrame

id_b and time.

resolve_conflicts_hmm

resolve_conflicts_hmm(df: TrackFrame, intervals: EventFrame, geometry: LaneGeometry, params: HmmParams, detector: Mapping[str, Any], events: EventFrame, margin_m: float = 1.0, penalty: float = float(np.log(0.0001)), max_iterations: int = 10, duplicate_min_overlap_s: float = 1.0, duplicate_min_confidence: float = 0.9, duplicate_max_lateral_m: float = 0.5, damping: tuple[float, float] | None = None) -> tuple[TrackFrame, EventFrame, list[dict[str, int]]]

Remove space-time conflicts by penalising and re-decoding the less confident vehicle.

In every round: find all conflicts (find_conflicts); for each pair of vehicles, the one with the lower mean lane_confidence over the conflict frames gets penalty added to its emission for the lane it occupies on those frames, and only the penalised vehicles are decoded again. Penalties accumulate over rounds. A pair that overlaps for longer than duplicate_min_overlap_s while both are confident (mean lane_confidence > duplicate_min_confidence) and laterally less than duplicate_max_lateral_m apart is probably one vehicle tracked twice: it is flagged suspected_duplicate_track and not re-assigned. Rows still in a conflict after max_iterations rounds get lane_conflict_unresolved.

Parameters:

Name Type Description Default
df TrackFrame

Output of assign_lanes_hmm (sorted by id and datum, index 0..n-1).

required
intervals EventFrame

Detector intervals.

required
geometry LaneGeometry

Lane geometry.

required
params HmmParams

Model parameters.

required
detector Mapping[str, Any]

Keyword arguments for assign_lanes_hmm (threshold_mps and the filter widths).

required
events EventFrame

Event table of assign_lanes_hmm.

required
margin_m float

Extra longitudinal margin [m] of find_conflicts.

1.0
penalty float

Log-probability added per round to the loser's emission for the occupied lane.

float(log(0.0001))
max_iterations int

Maximum number of re-decoding rounds.

10
duplicate_min_overlap_s float

Minimum conflict time [s] (conflict frames x sampling interval) of a suspected duplicate.

1.0
duplicate_min_confidence float

Minimum mean lane_confidence of both vehicles of a suspected duplicate.

0.9
duplicate_max_lateral_m float

Maximum median lateral distance [m] of a suspected duplicate.

0.5
damping tuple[float, float] | None

None (frozen behaviour) or (t_min_s, t_hold_s) [s]: the frames of a pair are split into conflict episodes (gaps of more than 1.5 sampling steps); only episodes of at least t_min_s are resolved; the penalty window of the loser covers the episode extended to at least t_hold_s (forward, else backward), without entering the loser's detector intervals; an episode that was resolved once is not penalised again.

None

Returns:

Type Description
TrackFrame

(df, events, history): the updated samples (plus suspected_duplicate_track and

EventFrame

lane_conflict_unresolved), the updated events (sorted by id and time_start) and one dict per

list[dict[str, int]]

round (iteration, conflict_rows, pairs, penalised_vehicles, duplicate_pairs).

em_lane_assignment

em_lane_assignment(df: TrackFrame, intervals: EventFrame, geometry: LaneGeometry, params: HmmParams, detector: Mapping[str, Any], max_iterations: int = 3, tolerance: float = 0.001, bin_m: float = 10.0, smooth_sigma_m: float = 30.0, min_points: int = 20) -> tuple[TrackFrame, EventFrame, LaneGeometry, list[dict[str, float]]]

Alternate between decoding the lanes and re-estimating the lane geometry (EM-like).

Iteration 0 decodes with the initial geometry. Each further iteration re-estimates c_k(s) and sigma_k from the HMM labels of all points outside lane changes and excursions (geometry_from_labels: median per bin_m bin, Gaussian smoothing smooth_sigma_m, at least min_points per bin) and decodes again. The loop stops when less than tolerance of the labels change or after max_iterations re-estimations. Lanes that lose all support keep their previous centre and spread.

Parameters:

Name Type Description Default
df TrackFrame

One direction at the native rate after Step 4 (see assign_lanes_hmm).

required
intervals EventFrame

Detector intervals.

required
geometry LaneGeometry

Initial lane geometry.

required
params HmmParams

Model parameters.

required
detector Mapping[str, Any]

Keyword arguments for assign_lanes_hmm (threshold_mps and the filter widths).

required
max_iterations int

Maximum number of re-estimations.

3
tolerance float

Share of changed labels below which the loop stops.

0.001
bin_m float

Bin length of the re-estimated centres [m].

10.0
smooth_sigma_m float

Gaussian smoothing of the re-estimated centres [m].

30.0
min_points int

Minimum samples of a lane per bin.

20

Returns:

Type Description
TrackFrame

(df, events, geometry, history): the output of the last assign_lanes_hmm, the geometry it used and

EventFrame

one dict per iteration (iteration, share_changed, mean_confidence).

Assign lanes from sources other than the pipeline: a lanelet map (INTERACTION ZS) and a two-to-one lane drop (MONA).

Same lane sources as the earlier field merge tables; the site parameters (lane chains, map file, drop thresholds) come from the site files (trajlab/sites).

Lane convention: 0 = auxiliary or ramp lane (the ending lane of a lane drop), 1 = rightmost main lane (the continuing lane), -1 = not assigned.

lanelet_polygons

lanelet_polygons(map_path: str | Path) -> tuple[list[int], list[Any]]

Read the lanelets of a Lanelet2 .osm_xy map as polygons in the coordinates of the track files.

Parameters:

Name Type Description Default
map_path str | Path

Path of the .osm_xy map.

required

Returns:

Type Description
list[int]

(ids, polygons): the lanelet relation IDs and one shapely Polygon per lanelet (left boundary

list[Any]

followed by the reversed right boundary, buffer(0)-repaired), in the same order.

map_lanes

map_lanes(out: TrackFrame, track_file: str | Path, map_path: str | Path, lane_chains: Mapping[Any, Mapping[int, Sequence[int]]], base_timestamp: Timestamp) -> npt.NDArray[np.int_]

Return the lane of each row of a pipeline output from a lanelet map.

Each sample is located by its position in the INTERACTION track file (matched on track_id and timestamp_ms); the lanelet it lies in gives the lane of that lanelet's chain. The lanelets of the two carriageways are disjoint, so the lane does not depend on the unit's direction (orientation flips between track files).

Parameters:

Name Type Description Default
out TrackFrame

Pipeline output with id (the INTERACTION track_id) and datum.

required
track_file str | Path

INTERACTION track CSV with track_id, timestamp_ms, x, y.

required
map_path str | Path

Lanelet2 .osm_xy map of the site.

required
lane_chains Mapping[Any, Mapping[int, Sequence[int]]]

Per direction {lane: [lanelet IDs]}.

required
base_timestamp Timestamp

Time stamp of timestamp_ms = 0 in datum.

required

Returns:

Type Description
NDArray[int_]

Lane per row of out; -1 where the sample is missing from the track file, lies off the carriageway or in

NDArray[int_]

a lanelet of no chain.

lane_drop_lanes

lane_drop_lanes(out: TrackFrame, bin_m: float = 5.0, min_separation_m: float = 2.0, min_share: float = 0.1) -> npt.NDArray[np.int_]

Return the lanes of a two-to-one lane drop from the lateral position.

Upstream of the drop each bin_m bin holds two lane centres (1-D two-means), downstream one. The lane whose centre lies farther from the single downstream lane is the ending one (0), the other the continuing one (1); downstream all samples are lane 1. The boundary between the two lanes is the rolling median (5 bins) of the midpoints of the two centres.

Parameters:

Name Type Description Default
out TrackFrame

Samples with pos_lon [m] and pos_lat [m].

required
bin_m float

Bin length along pos_lon [m]; bins with fewer than 200 samples are skipped.

5.0
min_separation_m float

Minimum distance [m] of the two centres for a bin to hold two lanes.

2.0
min_share float

Minimum share of the smaller of the two clusters for a bin to hold two lanes.

0.1

Returns:

Type Description
NDArray[int_]

Lane per row of out (0, 1, or -1 where nothing could be assigned, e.g. all rows if no drop is found).

Step 02, perspective correction of tall vehicles (docs/pipeline/02_perspective_correction.md).

Entry function: correct_perspective (parameters PerspectiveParams) in hgv_offsets. Methods: view_offsets (one empirical HGV offset per camera view, with the view boundaries of views), the class offsets and the geometric model of correction and model, the joint estimate of joint_offset.

PerspectiveParams dataclass

PerspectiveParams(correction: str = 'class_offset_empirical_view', kappa: dict[str, float] | None = None, d_c_m: float | None = None, offset_m: dict[str, float] | None = None, min_points: int = 30, max_iter: int = 4, tol_m: float = 0.05, max_offset_m: float = 2.5, joint_offset_scope: str = 'global', joint_tau_m: float = 1.5, joint_lane_tau_m: float = 0.5, joint_lane_min_sep_m: float | None = 2.5, joint_section_m: float = 300.0, joint_smooth_tau_m: float = 0.3, joint_hgv_lane_alpha: float = 0.5, joint_hgv_exclude_left_lane: bool = True, joint_mode_tie_nats: float = 0.05, joint_profile: bool = True, joint_profile_range_m: float = 3.0, joint_profile_step_m: float = 0.05, joint_max_outer: int = 20, joint_tol_m: float = 0.01, joint_estimate: dict[str, Any] | None = None, view_detection: str = 'hgv_band', view_boundaries_m: Sequence[float] | None = None, view_offsets_m: Sequence[float] | None = None, view_bin_m: float = 50.0, view_min_segment_m: float = 150.0, view_min_jump_m: float = 0.6, view_min_hgv: int = 300, view_min_car: int = 1000, view_blend_m: float = 25.0, view_max_offset_m: float = 5.0, view_ambiguous_pp: float = 5.0, view_robust_reading: bool = True, view_robust_margin_pp: float = 10.0, view_max_abs_delta_m: float | None = None)

Parameters of correct_perspective; defaults of the preset drone_hgv_paper.

The fields and their meaning are those of the configuration section perspective (docs/configuration.md); only the default of correction differs (the method of the preset instead of "none").

Attributes:

Name Type Description
correction str

Method: "class_offset_empirical_view" (one iterated empirical HGV offset per camera view), "class_offset_empirical" (one iterated offset per direction), "constant_class_offset", "lateral_class_offset" (geometric model) or "joint_gmm" (experimental). Defaults to "class_offset_empirical_view".

kappa dict[str, float] | None

lateral_class_offset: class group -> kappa [-]; None estimates it. Defaults to None.

d_c_m float | None

lateral_class_offset: lateral position [m] of the ground point of the camera. Defaults to None.

offset_m dict[str, float] | None

constant_class_offset / class_offset_empirical: class group -> lateral shift [m]; None estimates it. Defaults to None.

min_points int

Minimum rows per class, lane and 50 m bin in a diagnostic pass. Defaults to 30.

max_iter int

Maximum diagnostic passes of the iterated estimates. Defaults to 4.

tol_m float

Stop when the absolute residual offset is below this [m]. Defaults to 0.05.

max_offset_m float

class_offset_empirical: safety limit [m]. Defaults to 2.5.

joint_offset_scope str

joint_gmm: "global", "lane" or "piecewise". Defaults to "global".

joint_tau_m float

joint_gmm: prior SD of the offset [m]. Defaults to 1.5.

joint_lane_tau_m float

joint_gmm: SD of the lane offsets around their mean [m]. Defaults to 0.5.

joint_lane_min_sep_m float | None

joint_gmm: minimum distance [m] of displaced HGV centers of adjacent lanes. Defaults to 2.5.

joint_section_m float

joint_gmm: section length [m]. Defaults to 300.0.

joint_smooth_tau_m float

joint_gmm: SD of the change between neighboring sections [m]. Defaults to 0.3.

joint_hgv_lane_alpha float

joint_gmm: strength of the Dirichlet prior favoring the right lanes. Defaults to 0.5.

joint_hgv_exclude_left_lane bool

joint_gmm: no HGVs in the leftmost of three or more lanes. Defaults to True.

joint_mode_tie_nats float

joint_gmm: tolerance [nats per HGV point] of equivalent modes. Defaults to 0.05.

joint_profile bool

joint_gmm: evaluate the profile log posterior. Defaults to True.

joint_profile_range_m float

joint_gmm: range of that profile [m]. Defaults to 3.0.

joint_profile_step_m float

joint_gmm: grid step of that profile [m]. Defaults to 0.05.

joint_max_outer int

joint_gmm: maximum outer iterations. Defaults to 20.

joint_tol_m float

joint_gmm: stop when the offset changes by less than this [m]. Defaults to 0.01.

joint_estimate dict[str, Any] | None

joint_gmm: estimate of an earlier run; skips the estimation. Defaults to None.

view_detection str

"hgv_band" or "seams": how the view boundaries are found. Defaults to "hgv_band".

view_boundaries_m Sequence[float] | None

Fixed view boundaries along pos_lon [m]. Defaults to None.

view_offsets_m Sequence[float] | None

With view_boundaries_m: fixed HGV offset per view [m]. Defaults to None.

view_bin_m float

Bin length of the HGV band profile [m]. Defaults to 50.0.

view_min_segment_m float

Minimum view length [m]. Defaults to 150.0.

view_min_jump_m float

Minimum offset step between views [m]. Defaults to 0.6.

view_min_hgv int

Minimum HGV samples per view. Defaults to 300.

view_min_car int

Minimum car samples per view. Defaults to 1000.

view_blend_m float

Offsets are blended over +- this around each boundary [m]. Defaults to 25.0.

view_max_offset_m float

Per-view safety limit [m]. Defaults to 5.0.

view_ambiguous_pp float

Readings closer than this [percentage points] are ambiguous. Defaults to 5.0.

view_robust_reading bool

Robust reading of the per-view offset. Defaults to True.

view_robust_margin_pp float

Margin of the robust reading [percentage points]. Defaults to 10.0.

view_max_abs_delta_m float | None

Readings with |delta| above this [m] are not considered. Defaults to None.

__post_init__

__post_init__() -> None

Check correction.

Raises:

Type Description
ValueError

If correction is not in PERSPECTIVE_CORRECTIONS.

PerspectiveResult dataclass

PerspectiveResult(tracks: TrackFrame, estimate: dict[str, Any])

Result of correct_perspective.

Attributes:

Name Type Description
tracks TrackFrame

The samples with the corrected pos_lat of tall vehicles.

estimate dict[str, Any]

What was estimated or applied (the perspective record of the run metadata).

correct_perspective

correct_perspective(tracks: TrackFrame, *, params: PerspectiveParams | None = None, layout: LaneLayout | None = None, lane_geometry: LaneGeometryParams | None = None, alignment: AlignmentParams | None = None, label_lanes: Callable[[TrackFrame], TrackFrame] | None = None) -> PerspectiveResult

Correct the lateral displacement of tall vehicles (HGVs) that the camera perspective causes.

Entry function of page 02 of the pipeline steps 01-10 (docs/pipeline/02_perspective_correction.md). Requires the columns pos_lon and pos_lat [m] (project_to_reference_line), class and, for the view method, id and datum; corrects pos_lat [m] of the HGVs and adds no column. The offsets are estimated on diagnostic passes that label the lanes of the uncorrected data: by default the alignment, Savitzky-Golay kinematics, the lane geometry and the heuristic lane assignment with the parameters given here. Method: the HGV-minus-car offset per lane and bin, iterated per camera view (Baumann, Grau & Vortisch, ANT 2027).

Example

import trajlab from trajlab.processing.perspective import PerspectiveParams, correct_perspective from trajlab.processing.reference_line import project_to_reference_line raw = trajlab.examples.synthetic_motorway() ref_east, _ = trajlab.estimate_ref_lines(raw) tracks = project_to_reference_line(raw[raw["orientation"] > 0], ref_east) result = correct_perspective(tracks, params=PerspectiveParams(correction="class_offset_empirical")) corrected, estimate = result.tracks, result.estimate

Parameters:

Name Type Description Default
tracks TrackFrame

Projected samples of one direction of travel. Not modified.

required
params PerspectiveParams | None

Parameters; None uses PerspectiveParams().

None
layout LaneLayout | None

Number of main lanes and the zones of the site; None uses LaneLayout() (3 lanes, no zones).

None
lane_geometry LaneGeometryParams | None

Lane-geometry parameters (GMM priors; window and step of joint_gmm); None uses LaneGeometryParams().

None
alignment AlignmentParams | None

Alignment parameters of the diagnostic pass and of joint_gmm; None uses AlignmentParams().

None
label_lanes Callable[[TrackFrame], TrackFrame] | None

The diagnostic pass: a function that returns the samples with lane_fixed; None uses diagnostic_lane_labels with the parameters above.

None

Returns:

Type Description
PerspectiveResult

The corrected samples and the estimate.

diagnostic_lane_labels

diagnostic_lane_labels(layout: LaneLayout, lane_geometry: LaneGeometryParams, alignment: AlignmentParams) -> Callable[[TrackFrame], TrackFrame]

Return the default diagnostic pass of correct_perspective: lane labels of the uncorrected data.

Parameters:

Name Type Description Default
layout LaneLayout

Number of main lanes and the zones of the site.

required
lane_geometry LaneGeometryParams

Lane-geometry parameters (also the direction_consistency_min of the pass).

required
alignment AlignmentParams

Alignment parameters.

required

Returns:

Type Description
Callable[[TrackFrame], TrackFrame]

A function tracks -> tracks with lane_fixed that runs align_lateral_positions,

Callable[[TrackFrame], TrackFrame]

reconstruct_kinematics (Savitzky-Golay), estimate_lane_geometry and assign_lanes (heuristic).

Correct the lateral perspective displacement of tall vehicles (optional step after the projection).

See trajlab.processing.perspective.model for the model and its estimation: the box centre of a vehicle of class group g is displaced laterally by kappa_g * (d - d_c) relative to a car, with d_c the lateral position of the camera's ground point. The correction subtracts this displacement from pos_lat. Cars (kappa = 0) and classes without a kappa are unchanged. The longitudinal component is not corrected: it needs the camera's longitudinal position, which is unknown in general.

apply_lateral_perspective_correction

apply_lateral_perspective_correction(df: TrackFrame, kappa: Mapping[str, float], d_c_m: float) -> TrackFrame

Remove the displacement kappa_g * (d - d_c_m) from pos_lat of every row of class group g.

The model displaces the true position d: d_obs = d + kappa (d - d_c), so the correction is the exact inverse d = d_obs - kappa / (1 + kappa) * (d_obs - d_c).

Parameters:

Name Type Description Default
df TrackFrame

Projected rows with pos_lat [m] and class.

required
kappa Mapping[str, float]

Class group ("hgv", "car", "motorcycle") -> kappa [-]; groups with kappa 0 are unchanged.

required
d_c_m float

Lateral position [m] of the camera's ground point in the same pos_lat frame.

required

Returns:

Type Description
TrackFrame

A copy of df with corrected pos_lat (unchanged, with a logged warning, without class column or

TrackFrame

without kappa).

apply_constant_class_offset

apply_constant_class_offset(df: TrackFrame, offset_m: Mapping[str, float]) -> TrackFrame

Subtract one constant lateral shift per class group from pos_lat (ablation alternative to the model).

Parameters:

Name Type Description Default
df TrackFrame

Projected rows with pos_lat [m] and class.

required
offset_m Mapping[str, float]

Class group -> shift [m], e.g. the median HGV-minus-car offset.

required

Returns:

Type Description
TrackFrame

A copy of df with corrected pos_lat (unchanged without class column or without offsets).

Correct the lateral perspective displacement of tall vehicles (page 02 of the pipeline steps 01-10).

correct_perspective is the entry function of the step. PerspectiveParams.correction selects the method: one empirical HGV offset per camera view (view_offsets, the method of the preset drone_hgv_paper), one iterated or constant offset per class group, the geometric model (model, correction) or the joint estimation with the lane geometry (joint_offset, experimental). The estimates come from diagnostic passes that label the lanes of the uncorrected data (label_lanes).

PerspectiveParams dataclass

PerspectiveParams(correction: str = 'class_offset_empirical_view', kappa: dict[str, float] | None = None, d_c_m: float | None = None, offset_m: dict[str, float] | None = None, min_points: int = 30, max_iter: int = 4, tol_m: float = 0.05, max_offset_m: float = 2.5, joint_offset_scope: str = 'global', joint_tau_m: float = 1.5, joint_lane_tau_m: float = 0.5, joint_lane_min_sep_m: float | None = 2.5, joint_section_m: float = 300.0, joint_smooth_tau_m: float = 0.3, joint_hgv_lane_alpha: float = 0.5, joint_hgv_exclude_left_lane: bool = True, joint_mode_tie_nats: float = 0.05, joint_profile: bool = True, joint_profile_range_m: float = 3.0, joint_profile_step_m: float = 0.05, joint_max_outer: int = 20, joint_tol_m: float = 0.01, joint_estimate: dict[str, Any] | None = None, view_detection: str = 'hgv_band', view_boundaries_m: Sequence[float] | None = None, view_offsets_m: Sequence[float] | None = None, view_bin_m: float = 50.0, view_min_segment_m: float = 150.0, view_min_jump_m: float = 0.6, view_min_hgv: int = 300, view_min_car: int = 1000, view_blend_m: float = 25.0, view_max_offset_m: float = 5.0, view_ambiguous_pp: float = 5.0, view_robust_reading: bool = True, view_robust_margin_pp: float = 10.0, view_max_abs_delta_m: float | None = None)

Parameters of correct_perspective; defaults of the preset drone_hgv_paper.

The fields and their meaning are those of the configuration section perspective (docs/configuration.md); only the default of correction differs (the method of the preset instead of "none").

Attributes:

Name Type Description
correction str

Method: "class_offset_empirical_view" (one iterated empirical HGV offset per camera view), "class_offset_empirical" (one iterated offset per direction), "constant_class_offset", "lateral_class_offset" (geometric model) or "joint_gmm" (experimental). Defaults to "class_offset_empirical_view".

kappa dict[str, float] | None

lateral_class_offset: class group -> kappa [-]; None estimates it. Defaults to None.

d_c_m float | None

lateral_class_offset: lateral position [m] of the ground point of the camera. Defaults to None.

offset_m dict[str, float] | None

constant_class_offset / class_offset_empirical: class group -> lateral shift [m]; None estimates it. Defaults to None.

min_points int

Minimum rows per class, lane and 50 m bin in a diagnostic pass. Defaults to 30.

max_iter int

Maximum diagnostic passes of the iterated estimates. Defaults to 4.

tol_m float

Stop when the absolute residual offset is below this [m]. Defaults to 0.05.

max_offset_m float

class_offset_empirical: safety limit [m]. Defaults to 2.5.

joint_offset_scope str

joint_gmm: "global", "lane" or "piecewise". Defaults to "global".

joint_tau_m float

joint_gmm: prior SD of the offset [m]. Defaults to 1.5.

joint_lane_tau_m float

joint_gmm: SD of the lane offsets around their mean [m]. Defaults to 0.5.

joint_lane_min_sep_m float | None

joint_gmm: minimum distance [m] of displaced HGV centers of adjacent lanes. Defaults to 2.5.

joint_section_m float

joint_gmm: section length [m]. Defaults to 300.0.

joint_smooth_tau_m float

joint_gmm: SD of the change between neighboring sections [m]. Defaults to 0.3.

joint_hgv_lane_alpha float

joint_gmm: strength of the Dirichlet prior favoring the right lanes. Defaults to 0.5.

joint_hgv_exclude_left_lane bool

joint_gmm: no HGVs in the leftmost of three or more lanes. Defaults to True.

joint_mode_tie_nats float

joint_gmm: tolerance [nats per HGV point] of equivalent modes. Defaults to 0.05.

joint_profile bool

joint_gmm: evaluate the profile log posterior. Defaults to True.

joint_profile_range_m float

joint_gmm: range of that profile [m]. Defaults to 3.0.

joint_profile_step_m float

joint_gmm: grid step of that profile [m]. Defaults to 0.05.

joint_max_outer int

joint_gmm: maximum outer iterations. Defaults to 20.

joint_tol_m float

joint_gmm: stop when the offset changes by less than this [m]. Defaults to 0.01.

joint_estimate dict[str, Any] | None

joint_gmm: estimate of an earlier run; skips the estimation. Defaults to None.

view_detection str

"hgv_band" or "seams": how the view boundaries are found. Defaults to "hgv_band".

view_boundaries_m Sequence[float] | None

Fixed view boundaries along pos_lon [m]. Defaults to None.

view_offsets_m Sequence[float] | None

With view_boundaries_m: fixed HGV offset per view [m]. Defaults to None.

view_bin_m float

Bin length of the HGV band profile [m]. Defaults to 50.0.

view_min_segment_m float

Minimum view length [m]. Defaults to 150.0.

view_min_jump_m float

Minimum offset step between views [m]. Defaults to 0.6.

view_min_hgv int

Minimum HGV samples per view. Defaults to 300.

view_min_car int

Minimum car samples per view. Defaults to 1000.

view_blend_m float

Offsets are blended over +- this around each boundary [m]. Defaults to 25.0.

view_max_offset_m float

Per-view safety limit [m]. Defaults to 5.0.

view_ambiguous_pp float

Readings closer than this [percentage points] are ambiguous. Defaults to 5.0.

view_robust_reading bool

Robust reading of the per-view offset. Defaults to True.

view_robust_margin_pp float

Margin of the robust reading [percentage points]. Defaults to 10.0.

view_max_abs_delta_m float | None

Readings with |delta| above this [m] are not considered. Defaults to None.

__post_init__

__post_init__() -> None

Check correction.

Raises:

Type Description
ValueError

If correction is not in PERSPECTIVE_CORRECTIONS.

PerspectiveResult dataclass

PerspectiveResult(tracks: TrackFrame, estimate: dict[str, Any])

Result of correct_perspective.

Attributes:

Name Type Description
tracks TrackFrame

The samples with the corrected pos_lat of tall vehicles.

estimate dict[str, Any]

What was estimated or applied (the perspective record of the run metadata).

correct_perspective

correct_perspective(tracks: TrackFrame, *, params: PerspectiveParams | None = None, layout: LaneLayout | None = None, lane_geometry: LaneGeometryParams | None = None, alignment: AlignmentParams | None = None, label_lanes: Callable[[TrackFrame], TrackFrame] | None = None) -> PerspectiveResult

Correct the lateral displacement of tall vehicles (HGVs) that the camera perspective causes.

Entry function of page 02 of the pipeline steps 01-10 (docs/pipeline/02_perspective_correction.md). Requires the columns pos_lon and pos_lat [m] (project_to_reference_line), class and, for the view method, id and datum; corrects pos_lat [m] of the HGVs and adds no column. The offsets are estimated on diagnostic passes that label the lanes of the uncorrected data: by default the alignment, Savitzky-Golay kinematics, the lane geometry and the heuristic lane assignment with the parameters given here. Method: the HGV-minus-car offset per lane and bin, iterated per camera view (Baumann, Grau & Vortisch, ANT 2027).

Example

import trajlab from trajlab.processing.perspective import PerspectiveParams, correct_perspective from trajlab.processing.reference_line import project_to_reference_line raw = trajlab.examples.synthetic_motorway() ref_east, _ = trajlab.estimate_ref_lines(raw) tracks = project_to_reference_line(raw[raw["orientation"] > 0], ref_east) result = correct_perspective(tracks, params=PerspectiveParams(correction="class_offset_empirical")) corrected, estimate = result.tracks, result.estimate

Parameters:

Name Type Description Default
tracks TrackFrame

Projected samples of one direction of travel. Not modified.

required
params PerspectiveParams | None

Parameters; None uses PerspectiveParams().

None
layout LaneLayout | None

Number of main lanes and the zones of the site; None uses LaneLayout() (3 lanes, no zones).

None
lane_geometry LaneGeometryParams | None

Lane-geometry parameters (GMM priors; window and step of joint_gmm); None uses LaneGeometryParams().

None
alignment AlignmentParams | None

Alignment parameters of the diagnostic pass and of joint_gmm; None uses AlignmentParams().

None
label_lanes Callable[[TrackFrame], TrackFrame] | None

The diagnostic pass: a function that returns the samples with lane_fixed; None uses diagnostic_lane_labels with the parameters above.

None

Returns:

Type Description
PerspectiveResult

The corrected samples and the estimate.

diagnostic_lane_labels

diagnostic_lane_labels(layout: LaneLayout, lane_geometry: LaneGeometryParams, alignment: AlignmentParams) -> Callable[[TrackFrame], TrackFrame]

Return the default diagnostic pass of correct_perspective: lane labels of the uncorrected data.

Parameters:

Name Type Description Default
layout LaneLayout

Number of main lanes and the zones of the site.

required
lane_geometry LaneGeometryParams

Lane-geometry parameters (also the direction_consistency_min of the pass).

required
alignment AlignmentParams

Alignment parameters.

required

Returns:

Type Description
Callable[[TrackFrame], TrackFrame]

A function tracks -> tracks with lane_fixed that runs align_lateral_positions,

Callable[[TrackFrame], TrackFrame]

reconstruct_kinematics (Savitzky-Golay), estimate_lane_geometry and assign_lanes (heuristic).

Estimate the lane geometry and the HGV lateral offset jointly (perspective.correction = "joint_gmm").

Experimental. Not part of the supported API: kept for reproducibility of documented experiments; interfaces may change or be removed without notice.

Instead of the nested diagnostic pipeline passes of class_offset_empirical, the HGV offset is a parameter of the restricted lane mixture of Chen & Krumm (2010) (fit_restricted_gmm_joint): in every rolling window cars and HGVs share the lane centres mu_j = mu + (j - 1) dmu; HGVs are displaced by delta. Lateral positions d [m] are positive to the left; lane 1 (index 0 in the arrays) is the rightmost main lane.

Positions are first referred to a road-edge profile computed from cars only (their positions are not displaced by perspective), so the profile is not pulled by displaced HGVs; the estimated offset is then subtracted from the projected HGV positions and the regular alignment follows.

Scopes (perspective.joint_offset_scope):

  • "global": one delta per recording and direction. The profile log posterior L(delta) (all other parameters maximised per window, windows weighted by step / window for their overlap) is evaluated on a grid; its maximum starts an alternating refinement (window fits with fixed delta -> closed-form global update from the pooled sufficient statistics).
  • "lane": one delta_k per lane with a hierarchical prior delta_k ~ N(delta_bar, lane_tau^2), delta_bar ~ N(0, tau^2) (a lane without cars falls back to delta_bar).
  • "piecewise": one delta_m per longitudinal section with delta_m ~ N(0, tau^2) and a smoothness prior delta_m - delta_{m-1} ~ N(0, smooth_tau^2).

right_lane_alpha

right_lane_alpha(k: int, strength: float = 0.5) -> FloatArray

Return a weak Dirichlet prior on the HGV lane weights favouring the right lanes: 1 + strength ... 1.

Parameters:

Name Type Description Default
k int

Number of lanes.

required
strength float

Extra weight of the rightmost lane, decreasing linearly to 0 for the leftmost lane.

0.5

Returns:

Type Description
FloatArray

Dirichlet parameters, rightmost lane first.

profile_log_posterior

profile_log_posterior(windows: Sequence[Window], grid: FloatArray, priors: Mapping[str, Any], tau: float, alpha_strength: float, weight: float, max_points: int = 2000) -> FloatArray

Return the profile log posterior L(delta) on grid.

L(delta) is the sum of the window log posteriors at fixed delta plus the prior of delta. Each grid point is fitted warm-started along the grid from both ends and fresh from the car-only geometry; the highest value is kept (warm starts alone can stay in a poor geometry over long stretches of the grid). For speed each window is thinned to max_points points of the larger class (same fraction for both classes) and its log posterior scaled back (diagnostic use; the estimate itself uses all points).

Parameters:

Name Type Description Default
windows Sequence[Window]

Rolling windows (_windows, with v0).

required
grid FloatArray

Offsets delta [m].

required
priors Mapping[str, Any]

Priors of the restricted mixture (eta, kappa, nu, varsigma2).

required
tau float

Standard deviation of the prior of delta [m].

required
alpha_strength float

Strength of the right-lane Dirichlet prior (right_lane_alpha); 0 for none.

required
weight float

Weight of a window (step / window size, for the overlap).

required
max_points int

Maximum points of the larger class per window.

2000

Returns:

Type Description
FloatArray

L(delta) per grid value (up to a constant).

profile_diagnosis

profile_diagnosis(grid: FloatArray, values: ArrayLike, threshold: float = 10.0) -> dict[str, Any]

Find the local maxima of L(delta) and flag a second mode within threshold.

Parameters:

Name Type Description Default
grid FloatArray

Offsets delta [m].

required
values ArrayLike

L(delta) per grid value (profile_log_posterior).

required
threshold float

Log-posterior difference [-] (nats); a second local maximum less than this below the best makes the profile multimodal.

10.0

Returns:

Type Description
dict[str, Any]

A dict with delta_at_max [m], n_local_maxima, local_maxima [m] (best first; maxima within 2

dict[str, Any]

grid steps of a better one are merged), second_mode [m] (or None), gap (log posterior difference

dict[str, Any]

to the second mode; inf without one) and multimodal.

estimate_joint_offset

estimate_joint_offset(df: TrackFrame, cfg: PerspectiveParams, lanes_cfg: LaneSettings, align_cfg: AlignmentParams) -> dict[str, Any]

Estimate the HGV offset jointly with the lane geometry; return the estimate and a per-row shift.

With cfg.joint_estimate set, the stored estimate is applied instead (for the lane and section scopes given only delta_global, the global stage is skipped and only the lane or section stage is estimated).

Parameters:

Name Type Description Default
df TrackFrame

Projected rows (pos_lon, pos_lat [m], class) of one direction.

required
cfg PerspectiveParams

PerspectiveParams (joint_* parameters; the section perspective of the configuration has the same attributes).

required
lanes_cfg LaneSettings

Window size and step, lane count, zones and priors (LaneSettings; e.g. the configuration section lanes).

required
align_cfg AlignmentParams

AlignmentParams (profile settings; the car-only profile is used here; or the configuration section alignment).

required

Returns:

Type Description
dict[str, Any]

A dict with scope, applied, shift (array [m] to subtract from pos_lat of every row; 0 for

dict[str, Any]

non-HGVs) and runtime_s [s]; when estimated also windows, delta_global [m],

dict[str, Any]

outer_iterations, modes, mode_by_posterior, optionally profile / profile_diagnosis,

dict[str, Any]

and per scope delta_lane, delta_bar, lane_start, lane_modes, hgv_lane_share,

dict[str, Any]

lane_max_convergence_m (lane) or delta_section (piecewise); from a stored estimate source

dict[str, Any]

and its delta* entries; with fewer than 30 HGV rows applied = False and reason.

Diagnose and model the perspective (relief-displacement) bias of tall vehicles.

Plain-language background:

Drone videos are taken from a few hundred metres with a slightly oblique view. The tracker reports the centre of each vehicle's bounding box in the image. For a tall object, the image of its upper part is displaced away from the point on the ground right below the camera (the nadir), roughly in proportion to object height / flight height x horizontal distance from the nadir (relief displacement). A 4 m high truck therefore appears shifted sideways (and along the road) compared with a car in the same lane.

Model:

The displacement of the box centre of class c is dp = kappa_c * (p - c), with c the camera's ground position and kappa_c = h_eff,c / H (effective height of the box centre over flight height). Relative to cars (kappa_car = 0 by definition) and in Frenet coordinates on a near-straight segment:

  • lateral: dd = kappa * (d - d_c): roughly constant along the road, but different per lane;
  • longitudinal: ds = kappa * (s - s_c): linear in s, zero at the nadir s_c.

With two or more lanes, kappa and d_c follow from the per-lane lateral offsets by least squares (fit_lateral_model). s_c cannot be identified from lateral offsets; without a known camera position only a bound on the longitudinal error is reported (longitudinal_bound).

References: Sanchez Morales et al., Accuracy characterization of the vehicle state estimation from aerial imagery (arXiv:2005.06314); Pancsics et al. (2024), VISAPP; Fonod et al. (2025), Transportation Research Part C, doi:10.1016/j.trc.2025.105205.

Conventions: pos_lon (s) [m] along the travel direction, pos_lat (d) [m] to the left; lane 1 is the rightmost main lane.

class_offsets

class_offsets(df: TrackFrame, lat_col: str = C.POS_LAT_RAW, lane_col: str = C.LANE_FIXED, bin_m: float = 50.0, min_points: int = 30, hgv_classes: tuple[str, ...] = HGV_CLASSES) -> pd.DataFrame

Return the median lateral position of each class group relative to cars, per lane and bin_m bin.

Only main-lane rows that are neither changing lane nor in a lateral excursion count. Class groups: car (reference), hgv; motorcycles are left out. A (lane, bin) needs at least min_points car rows and min_points rows of the class.

Parameters:

Name Type Description Default
df TrackFrame

Projected rows with pos_lon, lat_col, lane_col and class (all rows count as cars without it); is_changing_lane and is_lateral_excursion are used if present.

required
lat_col str

Column of the lateral position [m] (default: before any perspective correction).

POS_LAT_RAW
lane_col str

Column of the lane.

LANE_FIXED
bin_m float

Bin length along pos_lon [m].

50.0
min_points int

Minimum number of rows per (lane, bin) of cars and of the class.

30
hgv_classes tuple[str, ...]

Class labels (lower case) that form the hgv group.

HGV_CLASSES

Returns:

Type Description
DataFrame

One row per (lane, bin, group) with lane, bin (bin centre [m]), group, d_car (median car

DataFrame

position [m]), delta (class median minus car median [m]) and n (rows of the class).

summarise_offsets

summarise_offsets(offsets: DataFrame, group: str = 'hgv') -> dict[str, Any]

Summarise magnitude, sign and consistency of the offsets of one class group.

Parameters:

Name Type Description Default
offsets DataFrame

Output of class_offsets.

required
group str

Class group to summarise.

'hgv'

Returns:

Type Description
dict[str, Any]

A dict with bins, median_offset_m [m], iqr_m (25 % and 75 % quantiles [m]),

dict[str, Any]

sign_consistency (share of bins with the sign of the median; 0 for a zero median) and per lane

dict[str, Any]

median_offset_lane_<k> [m]; only bins (0), median_offset_m and sign_consistency (NaN) if the

dict[str, Any]

group has no bin.

fit_lateral_model

fit_lateral_model(offsets: DataFrame, group: str = 'hgv') -> dict[str, float]

Fit delta = kappa * (d_car - d_c) + beta * (s - s_mean) by least squares.

Written as delta = kappa * d_car + b0 + beta * (s - s_mean) with d_c = -b0 / kappa; observations weighted by sqrt(n). Needs at least two lanes and four bins.

Parameters:

Name Type Description Default
offsets DataFrame

Output of class_offsets.

required
group str

Class group to fit.

'hgv'

Returns:

Type Description
dict[str, float]

A dict with kappa [-], d_c_m [m] (NaN for |kappa| <= 1e-9), beta_per_km (trend of

dict[str, float]

the offset along the road [m/km]; a clear trend means a curved road or a camera not where the model

dict[str, float]

assumes), rmse_m [m], n_bins, n_lanes and s_mean_m [m]; if not identifiable, NaN for the

dict[str, float]

fitted values and no s_mean_m.

longitudinal_bound

longitudinal_bound(kappa: float, s_min: float, s_max: float, s_c: float | None = None) -> dict[str, Any]

Return the longitudinal displacement kappa * (s - s_c) of the class at the two ends of the section.

Without a known camera position s_c is assumed at the centre of the section; the values are then a plausible magnitude, not a correction. A car following an HGV (or the reverse) sees its clearance biased by the same amount.

Parameters:

Name Type Description Default
kappa float

Perspective factor of the class [-].

required
s_min float

Start of the section [m].

required
s_max float

End of the section [m].

required
s_c float | None

Longitudinal position of the camera's ground point [m]; None assumes the centre of the section.

None

Returns:

Type Description
dict[str, Any]

A dict with s_c_m [m], ds_start_m and ds_end_m [m] and assumed (bool).

One empirical HGV offset per camera view (class_offset_empirical_view, the method of the ANT 2027 paper).

estimate_view_offsets finds the view boundaries (configured, tracking seams or steps of the HGV band, views), starts every view from the HGV band, iterates the residual HGV-minus-car offset on diagnostic passes (offset_table) and picks the reading delta or delta +- dmu by the share of HGVs near a car lane centre and the keep-right share.

offset_table

offset_table(df: TrackFrame, label_lanes: Callable[[TrackFrame], TrackFrame], min_points: int) -> pd.DataFrame

Return the HGV-minus-car offsets per lane and 50 m bin (class_offsets) of a diagnostic pass.

Parameters:

Name Type Description Default
df TrackFrame

Samples to label (a copy is passed to label_lanes).

required
label_lanes Callable[[TrackFrame], TrackFrame]

The diagnostic pass: returns the samples with lane_fixed.

required
min_points int

Minimum rows per class, lane and bin.

required

Returns:

Type Description
DataFrame

The offset table of class_offsets.

estimate_view_offsets

estimate_view_offsets(df: TrackFrame, p: PerspectiveParams, layout: LaneLayout, priors: Mapping[str, float], label_lanes: Callable[[TrackFrame], TrackFrame]) -> tuple[TrackFrame, dict[str, Any]]

Apply class_offset_empirical_view: one iterated empirical HGV offset per camera view.

The views come from the configuration, the tracking seams or the HGV band (views); per view the offset is started from the band, iterated on diagnostic passes and its reading (delta or delta +- dmu) chosen by the share of HGVs near a car lane centre and the keep-right share.

Parameters:

Name Type Description Default
df TrackFrame

Projected samples with pos_lon, pos_lat [m], class, id and datum.

required
p PerspectiveParams

Settings of the correction (the view_* fields, max_iter, tol_m, min_points).

required
layout LaneLayout

Number of main lanes and the auxiliary-lane zones.

required
priors Mapping[str, float]

Priors of the restricted GMM (eta [m], kappa, nu, varsigma2 [m^2]).

required
label_lanes Callable[[TrackFrame], TrackFrame]

The diagnostic pass: returns the samples with lane_fixed (see correct_perspective).

required

Returns:

Type Description
tuple[TrackFrame, dict[str, Any]]

The corrected samples and the estimate (the perspective record of the run metadata).

Find the camera views along the road and apply an HGV offset per view.

Used by the option perspective.correction = "class_offset_empirical_view".

Drone recordings stitched from several camera views can carry a different relief displacement of tall vehicles in every view: in one of our campaigns the HGV offset steps by up to 3.5 m at the camera seams, so one offset per direction cannot correct it. This module finds the view boundaries along s and provides the per-row shift for one offset per view.

Two detectors (both label-free, on the projected rows before any correction):

  • seam_boundaries — tracking evidence of the camera seams: per 25 m bin the track starts/ends inside the section and the lateral jumps (|Δd| > 0.3 m between consecutive samples); bins with at least min_events and more than factor times the median bin are seam bins; neighbouring seam bins (gap <= merge_m) form one seam at their centre.
  • band_boundaries — the HGV band itself: per 50 m bin the car lane centres from a restricted GMM of the cars and the main peak of the HGV lateral positions relative to the lane-1 centre; the peak is unwrapped along s (of the readings p - j dmu the one nearest to the previous bin, starting with lane 1 at the upstream end) and segmented into constant pieces by binary segmentation (minimum segment min_segment_m, minimum jump min_jump_m).

Conventions: s (pos_lon) [m] along the travel direction, d (pos_lat) [m] to the left; lane 1 is the rightmost main lane.

seam_evidence

seam_evidence(ids: NDArray[Any], t: NDArray[Any], s: FloatArray, d: FloatArray, bin_m: float = 25.0, edge_m: float = 50.0) -> dict[str, npt.NDArray[Any]]

Count per bin_m bin the track starts/ends and the lateral jumps (> 0.3 m per sample).

Parameters:

Name Type Description Default
ids NDArray[Any]

Vehicle ID per sample.

required
t NDArray[Any]

Time per sample, in seconds [s] or as timestamps; only its order within a vehicle is used.

required
s FloatArray

Longitudinal position per sample [m].

required
d FloatArray

Lateral position per sample [m].

required
bin_m float

Bin length [m].

25.0
edge_m float

Bins whose centre is within this distance [m] of the observed ends are not interior.

50.0

Returns:

Type Description
dict[str, NDArray[Any]]

A dict of per-bin arrays: centre [m], interior (bool), ends (first and last samples of tracks)

dict[str, NDArray[Any]]

and jumps.

seam_boundaries

seam_boundaries(evidence: Mapping[str, NDArray[Any]], min_events: int = 5, factor: float = 5.0, merge_m: float = 75.0) -> list[float]

Return the seam positions from the tracking evidence (cluster centres of the seam bins).

Parameters:

Name Type Description Default
evidence Mapping[str, NDArray[Any]]

Output of seam_evidence.

required
min_events int

Minimum count of a seam bin (ends or jumps).

5
factor float

A seam bin has more than factor times the median count of the interior bins (at least 0.5).

5.0
merge_m float

Seam bins at most this far apart [m] form one seam.

75.0

Returns:

Type Description
list[float]

Seam positions s [m], increasing.

hgv_band_profile

hgv_band_profile(s: FloatArray, d: FloatArray, is_car: NDArray[bool_], is_hgv: NDArray[bool_], n_lanes: int, bin_m: float = 50.0, min_cars: int = 30, min_hgv: int = 20, priors: Mapping[str, Any] | None = None) -> dict[str, npt.NDArray[Any]]

Return per bin the car lane geometry and the main peak of the HGV lateral positions.

The car lane-1 centre mu and the spacing dmu come from a restricted GMM of the cars (fit_restricted_gmm); the peak p is the maximum of the HGV positions relative to mu in a 0.1 m histogram smoothed with a Gaussian of 0.2 m.

Parameters:

Name Type Description Default
s FloatArray

Longitudinal position per sample [m].

required
d FloatArray

Lateral position per sample [m].

required
is_car NDArray[bool_]

Per sample: car.

required
is_hgv NDArray[bool_]

Per sample: HGV.

required
n_lanes int

Number of main lanes.

required
bin_m float

Bin length [m].

50.0
min_cars int

Minimum number of car samples per bin for mu and dmu.

30
min_hgv int

Minimum number of HGV samples per bin for peak.

20
priors Mapping[str, Any] | None

Priors of fit_restricted_gmm; None uses its defaults.

None

Returns:

Type Description
dict[str, NDArray[Any]]

A dict of per-bin arrays: edges (n + 1 bin edges [m]), centre [m], mu [m], dmu [m],

dict[str, NDArray[Any]]

peak [m] (NaN where the bin has too few vehicles) and n_hgv.

unwrap_band

unwrap_band(profile: Mapping[str, NDArray[Any]], n_lanes: int) -> FloatArray

Return the HGV offset per bin [m], unwrapped along s.

Of the readings peak - j * dmu (HGVs in lane j + 1) the one nearest to the previous valid bin is taken; the first valid bin takes lane 1 (keep right).

Parameters:

Name Type Description Default
profile Mapping[str, NDArray[Any]]

Output of hgv_band_profile.

required
n_lanes int

Number of main lanes.

required

Returns:

Type Description
FloatArray

Offset of the HGV band relative to the lane-1 centre per bin [m]; NaN where the peak is unknown.

band_boundaries

band_boundaries(profile: Mapping[str, NDArray[Any]], offsets: FloatArray, min_segment_m: float = 150.0, min_jump_m: float = 0.6) -> list[float]

Return the change points of the unwrapped HGV offset (binary segmentation, least squares).

Neighbouring pieces whose median levels differ by less than min_jump_m are merged afterwards.

Parameters:

Name Type Description Default
profile Mapping[str, NDArray[Any]]

Output of hgv_band_profile (edges).

required
offsets FloatArray

Unwrapped offset per bin [m] (unwrap_band).

required
min_segment_m float

Minimum length of a piece [m] (at least two bins).

150.0
min_jump_m float

Minimum jump between neighbouring pieces [m].

0.6

Returns:

Type Description
list[float]

View boundaries s [m] (bin edges), increasing.

view_index

view_index(s: ArrayLike, boundaries: Sequence[float]) -> npt.NDArray[np.intp]

Return the camera view of each position: the number of view boundaries at or before it.

Parameters:

Name Type Description Default
s ArrayLike

Longitudinal positions [m].

required
boundaries Sequence[float]

View boundaries [m], increasing (e.g. from band_boundaries).

required

Returns:

Type Description
NDArray[intp]

View index per position (0 before the first boundary).

view_shift

view_shift(s: FloatArray, boundaries: Sequence[float], deltas: ArrayLike, blend_m: float = 25.0) -> FloatArray

Return the per-row offset: deltas[v] inside view v, blended linearly around each boundary.

Parameters:

Name Type Description Default
s FloatArray

Longitudinal positions [m].

required
boundaries Sequence[float]

View boundaries [m], increasing.

required
deltas ArrayLike

Offset per view [m] (len(boundaries) + 1 values).

required
blend_m float

Half-width [m] of the linear blend around each boundary.

25.0

Returns:

Type Description
FloatArray

Offset per position [m].

Run the trajectory pipeline: an ordered list of steps with explicit contracts.

Each processing step is described by a small PipelineStep record: its name, the columns it needs (requires), the columns that show it has already run (produces), a switch that says whether the configuration enables it, and the function that does the work. run_pipeline_detailed (and run_pipeline, which returns only its tracks) simply walks through the ordered list PIPELINE_STEPS. This keeps the order of the steps and the rules for skipping them in one place, so that a new step (or an alternative method for an existing one) can be added without touching the loop.

The work is done by the entry functions of the step packages, which take a DataFrame and keyword parameters and know nothing of the configuration (project_to_reference_line, correct_perspective, align_lateral_positions, stitch_fragments, impute_trajectories, reconstruct_kinematics, estimate_lane_geometry, assign_lanes, resample_tracks, compute_surroundings, enforce_platoon_consistency, add_event_neighbors). The private _run_<step> functions below read their parameters from the configuration (processing._config_adapter), call them and keep the extra results in PipelineContext.artifacts. Cache, progress (step statistics) and logging are done here, not in the steps.

Generic rules applied by the loop:

  • A disabled step is bypassed.
  • A step whose produces columns are all present already is skipped, unless cache="refresh" (force_recalculate of run_steps; incremental re-runs). Steps with an empty produces list (stitching, imputation, resampling) always run when enabled.
  • A step that runs but misses one of its requires columns raises a ValueError naming the step and the missing columns.
  • Every step that runs is logged with rows and vehicles before and after and its run time.

Conventions: pos_lon [m] runs along the travel direction, pos_lat [m] is positive to the left; lane 0 is the auxiliary or ramp lane, 1 the rightmost main lane, -1 not assigned; speed is in km/h, acceleration in m/s^2.

PipelineStep dataclass

PipelineStep(name: str, requires: tuple[str, ...], produces: tuple[str, ...], enabled: Callable[[PipelineConfig], bool], run: Callable[[TrackFrame, PipelineConfig, PipelineContext], TrackFrame], extra_outputs: tuple[str, ...] = ())

Contract of one pipeline step.

Attributes:

Name Type Description
name str

Short name used in logs and errors.

requires tuple[str, ...]

Columns that must be present when the step runs.

produces tuple[str, ...]

Columns whose presence means the step has already run (it is then skipped unless cache="refresh"). Empty for steps that always run when enabled.

enabled Callable[[PipelineConfig], bool]

Function config -> bool telling whether the step is on.

run Callable[[TrackFrame, PipelineConfig, PipelineContext], TrackFrame]

Function (df, config, context) -> df doing the work.

extra_outputs tuple[str, ...]

Further columns the step adds (documentation only).

PipelineContext dataclass

PipelineContext(ref_line: LineString | None = None, artifacts: dict[str, Any] = dict(), step_stats: list[dict[str, Any]] = list())

Inputs and intermediate results shared between steps that are not columns.

Attributes:

Name Type Description
ref_line LineString | None

Reference line for Step 1 (projection).

artifacts dict[str, Any]

Free-form results a step hands on to later steps (*_ARTIFACT keys).

step_stats list[dict[str, Any]]

One record per step with rows/vehicles in and out, the run time and what happened (ran, skipped, disabled).

PipelineResult dataclass

PipelineResult(tracks: TrackFrame, events: EventFrame, intermediates: dict[str, TrackFrame] = dict())

Full result of run_pipeline_detailed.

Attributes:

Name Type Description
tracks TrackFrame

The processed trajectories (a TrackFrame; all columns in docs/output_format.md) with the run metadata in tracks.attrs["trajlab"].

events EventFrame

The lane-change event table (an EventFrame; one row per lateral manoeuvre, see docs/output_format.md), empty if Step 5 did not run.

intermediates dict[str, TrackFrame]

Step name -> copy of the data after that step (only steps that ran; before rounding); empty unless keep_intermediates=True.

enrich_events_with_neighbours

enrich_events_with_neighbours(events: EventFrame, df: TrackFrame, tolerance_s: float) -> EventFrame

Add neighbour attributes from the (resampled) output to the event table.

For every event the values are taken from the output row of the same vehicle at the grid time nearest to the event time, if that grid time is at most tolerance_s away (otherwise NaN):

  • at time_start: the neighbours in the target lane (*_left for a left manoeuvre, *_right for a right one) -> <metric>_front_start, <metric>_rear_start;
  • at time_lc: the same-lane neighbours -> <metric>_front_lc, <metric>_rear_lc;
  • at time_end: the same-lane neighbours -> <metric>_front_end, <metric>_rear_end.

<metric> is id, rel_speed (km/h), clearance (m) and headway (m).

Parameters:

Name Type Description Default
events EventFrame

Event table from Step 5 (apply_lane_correction or the HMM).

required
df TrackFrame

Output of Step 6 (one row per vehicle and grid time).

required
tolerance_s float

Maximum distance [s] between an event time and the grid time used (half a grid step in the pipeline).

required

Returns:

Type Description
EventFrame

A copy of events with the neighbour columns filled in (unchanged copy if events is empty or df

EventFrame

has no neighbour columns).

flag_near_road_end

flag_near_road_end(events: EventFrame | None, df: TrackFrame, buffer_m: float, road_length_m: float | None) -> EventFrame | None

Add near_road_end to the event table: crossing (or peak) within buffer_m of either road end.

The position is the pos_lon of the vehicle at time_cross (lane changes) or time_lc (excursions), nearest sample of the same vehicle.

Parameters:

Name Type Description Default
events EventFrame | None

Event table (id, time_lc, optionally time_cross); None or empty is returned as is.

required
df TrackFrame

Samples with id, datum and pos_lon [m].

required
buffer_m float

Distance [m] from either end of the road.

required
road_length_m float | None

Length of the road [m] (pos_lon of its end); None (or 0) uses the largest pos_lon.

required

Returns:

Type Description
EventFrame | None

A copy of events with the boolean column near_road_end.

trim_track_ends

trim_track_ends(df: TrackFrame, max_depth_s: float, a_min: float, a_max: float) -> tuple[TrackFrame, dict[str, int]]

Cut the track ends whose acceleration Step 1 of Montanino & Punzo left outside its outlier bounds.

Step 1 never moves the first or last position of a track (the spline needs reference points on both sides), so outliers at the track ends stay in the output. Per track and end, all rows up to and including the deepest row within max_depth_s of that end whose acceleration lies outside [a_min, a_max] are removed; tracks without such rows are unchanged. Interior rows are never touched.

Parameters:

Name Type Description Default
df TrackFrame

Samples with id, datum and acceleration [m/s^2].

required
max_depth_s float

Depth [s] from each track end that is searched.

required
a_min float

Lower acceleration bound [m/s^2] (Step 1 deceleration threshold).

required
a_max float

Upper acceleration bound [m/s^2] (Step 1 acceleration threshold).

required

Returns:

Type Description
TrackFrame

(df, report): the remaining rows (original order and index) and rows_removed, ends_cut,

dict[str, int]

tracks_removed.

trim_track_ends_fixed

trim_track_ends_fixed(df: TrackFrame, cut_s: float) -> TrackFrame

Drop a fixed time at both ends of every track (the start-up transient of a reconstruction).

Parameters:

Name Type Description Default
df TrackFrame

Samples with id and datum (a TrackFrame).

required
cut_s float

Time [s] removed at each track end.

required

Returns:

Type Description
TrackFrame

The rows at least cut_s from both ends of their track (original order and index); tracks shorter than

TrackFrame

2 * cut_s vanish.

lane_geometry_diagnostics

lane_geometry_diagnostics(windows: DataFrame, centers: DataFrame, gmm_model: str) -> dict[str, Any]

Summarise the stability of the Step 4 geometry: lost-lane windows and the spread of each lane centre along s.

Parameters:

Name Type Description Default
windows DataFrame

Per-window records of the tracker (attrs["windows"] of its centre table).

required
centers DataFrame

Standardised lane centres (km_bin, lane, center_y [m]).

required
gmm_model str

The GMM model used ("free" or "restricted"), recorded as is.

required

Returns:

Type Description
dict[str, Any]

A dict with gmm_model, windows and, if available, windows_lane_lost, windows_lane_lost_share

dict[str, Any]

(share of the windows with tracked lanes in which a tracked lane got no centre of the window fit) and

dict[str, Any]

centre_sd_m (per standardised lane, the standard deviation [m] of its centre over the windows; on a

dict[str, Any]

road of constant cross-section after alignment ideally ~0).

run_pipeline

run_pipeline(gdf: GeoDataFrame, ref_line: LineString | None = None, config: PipelineConfig | None = None, *, cache: CacheMode = 'use', metadata_path: PathLike | None = None) -> TrackFrame

Run the complete trajectory preprocessing and lane-matching pipeline and return the processed tracks.

The same run as run_pipeline_detailed, which also returns the lane-change event table and, on request, the data after every step.

Parameters:

Name Type Description Default
gdf GeoDataFrame

Trajectory points. At minimum id (vehicle identifier), datum (datetime time stamps), and either geometry (UTM points) or pre-computed pos_lon/pos_lat columns. Not modified.

required
ref_line LineString | None

Shapely LineString along the road in the same CRS as gdf. Required for Step 1 (projection); can be omitted if pos_lon/pos_lat are already present.

None
config PipelineConfig | None

Configuration of the steps and their parameters; None uses PipelineConfig() with all standard steps enabled.

None
cache CacheMode

"use" skips a step whose output columns are already in gdf (resume from an intermediate result); "refresh" re-runs every enabled step.

'use'
metadata_path PathLike | None

Path of a JSON sidecar file for the run metadata; None writes no file.

None

Returns:

Type Description
TrackFrame

The processed GeoDataFrame (a TrackFrame; all columns in docs/output_format.md) with the run metadata

TrackFrame

in attrs["trajlab"]. An empty input is returned as an empty copy.

Raises:

Type Description
ValueError

If cache is not "use" or "refresh", or a step that runs misses a required column (or ref_line for the projection). Raised by the callee run_pipeline_detailed.

run_pipeline_detailed

run_pipeline_detailed(gdf: GeoDataFrame, ref_line: LineString | None = None, config: PipelineConfig | None = None, *, cache: CacheMode = 'use', metadata_path: PathLike | None = None, keep_intermediates: bool = False) -> PipelineResult

Run the complete trajectory preprocessing and lane-matching pipeline; return tracks, events and intermediates.

Executes the steps of PIPELINE_STEPS in order; each can be enabled, disabled, or skipped via the config flags and the presence of its output columns in the input data (see the module docstring for the rules).

Incremental execution: If the output columns of a step are already present in the input DataFrame and cache is "use", that step is skipped automatically. This allows the pipeline to resume from an intermediate result without recomputing completed work.

Minimum required input: id (int), datum (datetime), and geometry (UTM Point). docs/output_format.md lists the input and output columns.

Pipeline steps in order:

  1. projection (Step 1): Projects UTM geometry to Frenet coordinates pos_lon and pos_lat along ref_line, normalised to the direction of travel, and clamps 1 m at both ends of the line.
  2. perspective (optional): Lateral perspective correction of tall vehicles.
  3. alignment (Step 2): Horizontalises lateral positions to the right road edge.
  4. stitching (optional): Connects split vehicle track fragments.
  5. imputation (optional): Re-grids each track and fills short gaps.
  6. kinematics (Step 3): Savitzky-Golay smoothing or the Montanino & Punzo reconstruction, speed (km/h) and acceleration (m/s^2).
  7. lanes (Step 4): Rolling GMM lane tracking, lanes numbered from the right.
  8. lane_correction (Step 5): Crossover correction (heuristic or HMM) and space-time conflict resolution (lane_fixed, is_changing_lane).
  9. resampling: Common output grid (resampling.rate_hz, 10 Hz).
  10. surroundings (Step 6): Headway, clearance and relative speed for the 6 surrounding positions.
  11. platoon_consistency (optional, Montanino & Punzo): Spacing constraints, then Step 6 again.
  12. lane_change_events: Adds the neighbour attributes from the output grid to the lane-change event table of Step 5 (see enrich_events_with_neighbours). The events themselves are detected once, in Step 5 at the native frame rate.

Finally, all float64 columns are rounded to config.round_decimals decimals (2 by default; None disables rounding).

Reproducibility: the run metadata (configuration, library version and git commit, dependency versions, rows and vehicles per step, timestamp; see build_run_metadata) is attached to the tracks as tracks.attrs["trajlab"] (read it with trajlab.metadata.run_metadata) and, if metadata_path is given, written there as a JSON file. No columns are added.

Parameters:

Name Type Description Default
gdf GeoDataFrame

Trajectory points. At minimum id (vehicle identifier), datum (datetime time stamps), and either geometry (UTM points) or pre-computed pos_lon/pos_lat columns. Not modified.

required
ref_line LineString | None

Shapely LineString along the road in the same CRS as gdf. Required for Step 1 (projection); can be omitted if pos_lon/pos_lat are already present.

None
config PipelineConfig | None

Configuration of the steps and their parameters; None uses PipelineConfig() with all standard steps enabled.

None
cache CacheMode

"use" skips a step whose output columns are already in gdf (resume from an intermediate result); "refresh" re-runs every enabled step.

'use'
metadata_path PathLike | None

Path of a JSON sidecar file for the run metadata; None writes no file.

None
keep_intermediates bool

Keep a copy of the data after every step that ran (PipelineResult.intermediates); costs one copy of the data per step.

False

Returns:

Type Description
PipelineResult

The PipelineResult with the processed tracks, the lane-change events (empty if Step 5 did not run)

PipelineResult

and the intermediates. An empty input gives an empty copy of it, an empty event table and no

PipelineResult

intermediates.

Raises:

Type Description
ValueError

If cache is not "use" or "refresh", or if a step that runs misses a required column (or ref_line for the projection); the latter is raised by the callee run_steps and the step functions it runs (e.g. the projection).

run_steps

run_steps(df: TrackFrame, config: PipelineConfig, context: PipelineContext, steps: Sequence[PipelineStep] = PIPELINE_STEPS, force_recalculate: bool = False, intermediates: dict[str, TrackFrame] | None = None) -> TrackFrame

Run steps in order on df with the generic skip/require/log rules.

Parameters:

Name Type Description Default
df TrackFrame

Working copy of the trajectory data.

required
config PipelineConfig

Pipeline configuration.

required
context PipelineContext

Shared non-column inputs and results; step_stats is filled with one record per step.

required
steps Sequence[PipelineStep]

Ordered steps.

PIPELINE_STEPS
force_recalculate bool

Re-run steps whose produces columns exist.

False
intermediates dict[str, TrackFrame] | None

If given, a copy of the data after every step that ran is stored under the step name.

None

Returns:

Type Description
TrackFrame

The processed data.

Raises:

Type Description
ValueError

If a step that runs misses one of its requires columns.

build_run_metadata

build_run_metadata(config: PipelineConfig, context: PipelineContext, df_in: TrackFrame, df_out: TrackFrame) -> dict[str, Any]

Collect what is needed to reproduce a pipeline run.

Parameters:

Name Type Description Default
config PipelineConfig

The configuration used.

required
context PipelineContext

The run context (its step_stats and some artifacts are included).

required
df_in TrackFrame

Input data.

required
df_out TrackFrame

Output data.

required

Returns:

Type Description
dict[str, Any]

A JSON-compatible dict with the time stamp (UTC), library version and git commit, Python and dependency

dict[str, Any]

versions, the full configuration, input/output row and vehicle counts, one record per step and the

dict[str, Any]

perspective, lane_geometry and mp_counters results (None if absent).

Step 01, reference line and Frenet projection (docs/pipeline/01_reference_line_projection.md).

Entry function: project_to_reference_line. Modules in run order: reference_line (estimate the line before the step), projection (the projection and the end clamp); road_reference holds the geometry of a road reference used by the analyses.

project_to_reference_line

project_to_reference_line(tracks: GeoDataFrame, ref_line: LineString, *, direction_consistency_min: float = 0.9, end_margin_m: float = 1.0) -> TrackFrame

Project the trajectory points onto the reference line and drop the points near its ends.

Entry function of page 01 of the pipeline steps 01-10 (docs/pipeline/01_reference_line_projection.md). Requires the column geometry (UTM points; id and datum for the direction check) and adds pos_lon [m] (along the direction of travel), pos_lat [m] (positive to the left), pos_lon_ref [m] and ref_line_reversed [bool]. Method: projection onto the arc length of the line (Frenet frame), see project_onto_centerline.

Example

import trajlab from trajlab.processing.reference_line import project_to_reference_line raw = trajlab.examples.synthetic_motorway() ref_east, _ = trajlab.estimate_ref_lines(raw) tracks = project_to_reference_line(raw[raw["orientation"] > 0], ref_east)

Parameters:

Name Type Description Default
tracks GeoDataFrame

Trajectory points (a GeoDataFrame in the CRS of ref_line). Not modified.

required
ref_line LineString

Reference line along the road; it may be digitised in either direction.

required
direction_consistency_min float

Minimum share (0-1) of moving vehicles that must travel in the same direction. Defaults to 0.9 (preset drone_hgv_paper, projection.direction_consistency_min).

0.9
end_margin_m float

Points closer than this to either end of the line [m] are dropped. Defaults to 1.0.

1.0

Returns:

Type Description
TrackFrame

The projected points within the line, a new frame.

Project trajectories onto the reference line (Frenet frame).

After project_onto_centerline, pos_lon [m] increases in the direction of travel and pos_lat [m] is positive to the left of it, whichever way the reference line was digitised; check_pos_lon_increasing guards this convention in the later steps. The alignment of the lateral axis to the road edge (align_to_lower_bound) is in trajlab.processing.alignment.road_edge.

travel_direction_share

travel_direction_share(df: TrackFrame, lon_col: str = C.POS_LON, id_col: str = C.ID, time_col: str = C.TIME) -> tuple[float, int]

Measure how consistently the vehicles move along the longitudinal axis.

Parameters:

Name Type Description Default
df TrackFrame

Trajectory points with an ID, a time and a longitudinal column.

required
lon_col str

Column of the longitudinal position [m].

POS_LON
id_col str

Column of the vehicle ID.

ID
time_col str

Column of the time.

TIME

Returns:

Type Description
float

(share_increasing, n_moving): the share of moving vehicles (net displacement of at least

int

MIN_DIRECTION_DISPLACEMENT_M) whose lon_col increases over time, and the number of moving vehicles.

tuple[float, int]

share_increasing is NaN (and n_moving 0) when no vehicle moves or a column is missing.

check_pos_lon_increasing

check_pos_lon_increasing(df: TrackFrame, step: str, direction_consistency_min: float = 0.9, lon_col: str = C.POS_LON, time_col: str = C.TIME) -> None

Raise if pos_lon does not increase in the direction of travel.

Steps 3-6 rely on this convention, which Step 1 establishes. Input that skips Step 1 (pre-computed pos_lon) has to follow it as well.

Parameters:

Name Type Description Default
df TrackFrame

Trajectory points with id, the time and the longitudinal column.

required
step str

Name of the calling step, used in the error message.

required
direction_consistency_min float

Minimum share (0-1) of moving vehicles whose pos_lon must increase.

0.9
lon_col str

Column of the longitudinal position [m].

POS_LON
time_col str

Column of the time.

TIME

Raises:

Type Description
ValueError

If fewer than direction_consistency_min of the moving vehicles have an increasing pos_lon.

project_onto_centerline

project_onto_centerline(gdf: GeoDataFrame, ref_line: LineString, direction_consistency_min: float = 0.9) -> gpd.GeoDataFrame

Project UTM trajectory points onto a reference line in Frenet coordinates.

Computes the longitudinal position pos_lon (arc-length distance along the centerline) and the signed lateral offset pos_lat (perpendicular distance) for every trajectory point, then normalises both to the direction of travel:

  • The sign of the raw lateral offset comes from the cross product of the local tangent and the point-to-projection offset, i.e. it is relative to the digitising direction of ref_line.
  • The per-vehicle net displacement along the line decides the travel direction. If the moving vehicles travel against the digitising direction, pos_lon <- L - pos_lon and pos_lat <- -pos_lat with L = ref_line.length, which is the same as reversing the line.

Afterwards pos_lon increases in the direction of travel and pos_lat > 0 is left of it, whichever way the line was drawn.

Parameters:

Name Type Description Default
gdf GeoDataFrame

Points with a geometry column of UTM point coordinates (e.g. EPSG:25832) and, for the direction check, id and datum. Other columns are preserved.

required
ref_line LineString

Shapely LineString along the road, in the same CRS as gdf; it may be digitised in either direction.

required
direction_consistency_min float

Minimum share (0-1) of moving vehicles that must travel in the same direction along the line.

0.9

Returns:

Type Description
GeoDataFrame

A copy of gdf with the added columns pos_lon (distance along the line in the direction of travel

GeoDataFrame

[m]), pos_lat (signed lateral offset [m], positive to the left of the direction of travel),

GeoDataFrame

pos_lon_ref (distance from the start of ref_line as digitised [m], for mapping results back to the

GeoDataFrame

line) and ref_line_reversed (bool: the travel direction is opposite to the digitising direction).

Raises:

Type Description
ValueError

If the vehicles do not share one travel direction; the input then has to be split by direction.

project_to_reference_line

project_to_reference_line(tracks: GeoDataFrame, ref_line: LineString, *, direction_consistency_min: float = 0.9, end_margin_m: float = 1.0) -> TrackFrame

Project the trajectory points onto the reference line and drop the points near its ends.

Entry function of page 01 of the pipeline steps 01-10 (docs/pipeline/01_reference_line_projection.md). Requires the column geometry (UTM points; id and datum for the direction check) and adds pos_lon [m] (along the direction of travel), pos_lat [m] (positive to the left), pos_lon_ref [m] and ref_line_reversed [bool]. Method: projection onto the arc length of the line (Frenet frame), see project_onto_centerline.

Example

import trajlab from trajlab.processing.reference_line import project_to_reference_line raw = trajlab.examples.synthetic_motorway() ref_east, _ = trajlab.estimate_ref_lines(raw) tracks = project_to_reference_line(raw[raw["orientation"] > 0], ref_east)

Parameters:

Name Type Description Default
tracks GeoDataFrame

Trajectory points (a GeoDataFrame in the CRS of ref_line). Not modified.

required
ref_line LineString

Reference line along the road; it may be digitised in either direction.

required
direction_consistency_min float

Minimum share (0-1) of moving vehicles that must travel in the same direction. Defaults to 0.9 (preset drone_hgv_paper, projection.direction_consistency_min).

0.9
end_margin_m float

Points closer than this to either end of the line [m] are dropped. Defaults to 1.0.

1.0

Returns:

Type Description
TrackFrame

The projected points within the line, a new frame.

Extract a reference line per travel direction from the raw trajectories (ensemble average and B-spline).

The reference line defines the Frenet frame of the pipeline: pos_lon [m] along the line in the direction of travel, pos_lat [m] to the left of it.

estimate_ref_lines

estimate_ref_lines(gdf_raw: GeoDataFrame, s_step: float = 5.0, smoothing_factor: float | None = None, top_n_vehicles: int = 30, rms_tolerance_m: float | None = 0.75) -> tuple[LineString | None, LineString | None]

Extract smooth reference lines per travel direction from raw trajectories (ensemble average and B-spline).

Per travel direction (orientation > 0 and < 0):

  1. The road axis is the first principal component of the centred UTM coordinates, oriented in the direction of travel (the median net displacement of the vehicles along it is positive). All points are expressed in this axis frame: s along the axis, n across it.
  2. The top_n_vehicles trajectories with the largest extent along the axis form the ensemble. In bins of s_step metres along the axis, the mean s and the median n of their points are taken; this cancels individual lane changes and steering wobble.
  3. A smoothing cubic B-spline is fitted through the bin values in the direction of travel and transformed back to UTM. Its smoothing condition s = n_bins * rms_tolerance_m**2 lets the line deviate from the bin medians by at most rms_tolerance_m (RMS).

Because the bins follow the principal axis, the road may have any orientation (east-west, north-south, diagonal). Limitation: roads that curve by more than about 60-70 degrees within the recording area are not supported, because the trajectories are then no longer monotonic along a single axis; a UserWarning is emitted when a vehicle moves backwards along the axis by more than 5 m. Use a user-supplied reference line (for example from OSM) for such sites.

Without a time column the axis is oriented by the former convention (orientation > 0 towards increasing x). Without an orientation column (orientation or direction) all points form the first direction.

Parameters:

Name Type Description Default
gdf_raw GeoDataFrame

Raw trajectories with point geometry (UTM [m]), orientation and id (else vehicle_id, else the first column); datum (if present) orders each track in time for the direction check.

required
s_step float

Bin width along the axis [m].

5.0
smoothing_factor float | None

Deprecated B-spline smoothing multiplier (s = smoothing_factor * number of bins, i.e. an RMS tolerance of sqrt(smoothing_factor) m); overrides rms_tolerance_m with a DeprecationWarning. The former default 100 allowed 10 m RMS.

None
top_n_vehicles int

Number of trajectories with the largest extent along the axis used for the ensemble.

30
rms_tolerance_m float | None

Maximum RMS deviation [m] of the line from the binned median trajectory; may be None only together with smoothing_factor.

0.75

Returns:

Type Description
LineString | None

(ref_line_east, ref_line_west): shapely LineString (2000 points, UTM) for orientation > 0 and

LineString | None

orientation < 0, each digitised in its direction of travel; None for a direction with too little data

tuple[LineString | None, LineString | None]

(fewer than 4 bins with 3 points, or less than 10 m extent).

Raises:

Type Description
ValueError

If rms_tolerance_m is None without smoothing_factor.

Represent a road reference line and map points to and from its Frenet coordinates.

RoadReference is a densely sampled reference line (arc length s, map coordinates x / y, heading, curvature) with three sources:

  • from_opendrive_road: the reference line of one OpenDRIVE road (io.opendrive);
  • from_polyline: any ordered point sequence, smoothed by a cubic smoothing spline;
  • from_trajectories: estimated from vehicle positions of one travel direction, for sites without a map. Starting from an initial line (the pipeline's estimate_ref_lines or a principal-axis line), the points are projected, the median lateral offset is taken in bins along s (robust to lane changes and outliers), the line is shifted by it along its normals and smoothed again; this is repeated, so curved roads converge (a fixed principal axis does not).

project maps points to (s, d) (d positive to the left of the line's direction), to_xy maps back, curvature_at gives the signed curvature, line a shapely LineString for the pipeline's projection step (processing.reference_line.projection.project_onto_centerline), and lane_layout projects OpenDRIVE lane boundaries into the frame. lateral_kinematics gives the lateral speed and acceleration in the Frenet frame, free of the centripetal term a curved road adds to Cartesian derivatives.

RoadReference dataclass

RoadReference(s: FloatArray, x: FloatArray, y: FloatArray, hdg: FloatArray, kappa: FloatArray)

Densely sampled reference line with arc length, heading and curvature.

Attributes:

Name Type Description
s FloatArray

Arc length of the samples [m], increasing.

x FloatArray

Map x coordinate of the samples [m].

y FloatArray

Map y coordinate of the samples [m].

hdg FloatArray

Heading of the line [rad], unwrapped.

kappa FloatArray

Signed curvature [1/m] (positive for a left turn).

length property

length: float

Length of the line [m].

__post_init__

__post_init__() -> None

Build the k-d tree of the samples used by project.

from_samples classmethod

from_samples(x: ArrayLike, y: ArrayLike, ds: float = 0.5) -> RoadReference

Resample an ordered, smooth point sequence to arc-length steps ds [m]; heading and curvature from it.

Parameters:

Name Type Description Default
x ArrayLike

Map x coordinates [m] of the ordered points.

required
y ArrayLike

Map y coordinates [m].

required
ds float

Arc-length step [m].

0.5

Returns:

Type Description
RoadReference

The reference line starting at s = 0.

from_polyline classmethod

from_polyline(xy: ArrayLike, smooth_m: float = 0.5, ds: float = 0.5) -> RoadReference

Fit a smoothing spline through ordered points (cubic, linear for up to 3 points).

Parameters:

Name Type Description Default
xy ArrayLike

Ordered points (n x 2) [m].

required
smooth_m float

RMS deviation [m] the spline may have from the points.

0.5
ds float

Arc-length step of the result [m].

0.5

Returns:

Type Description
RoadReference

The reference line.

from_opendrive_road classmethod

from_opendrive_road(road: Any, ds: float = 0.5) -> RoadReference

Build the reference line of one OpenDRIVE road, resampled to arc-length steps ds.

The road's plan view is sampled at ds / 2 and passed to from_samples.

Parameters:

Name Type Description Default
road Any

An io.opendrive.Road (anything with a sample(step) method returning x / y [m]).

required
ds float

Arc-length step of the result [m].

0.5

Returns:

Type Description
RoadReference

The reference line starting at s = 0.

from_trajectories classmethod

from_trajectories(x: ArrayLike, y: ArrayLike, initial: RoadReference | None = None, bin_m: float = 5.0, smooth_m: float = 0.3, iterations: int = 4, min_points: int = 10, ds: float = 0.5) -> RoadReference

Estimate a robust reference from the positions of one travel direction (see module docstring).

The result runs along the median lateral position of all points (the middle of the used carriageway).

Parameters:

Name Type Description Default
x ArrayLike

Map x coordinates of the vehicle positions [m].

required
y ArrayLike

Map y coordinates [m].

required
initial RoadReference | None

Starting line; None uses the principal axis of the points between their 0.1 % and 99.9 % quantiles (its direction is the sign of the first singular vector, not checked against travel).

None
bin_m float

Bin length along s [m] for the median lateral offset.

5.0
smooth_m float

RMS deviation [m] of the smoothing spline per iteration.

0.3
iterations int

Maximum number of shift-and-smooth iterations (stops early with fewer than 4 bins).

4
min_points int

Minimum number of points per bin.

10
ds float

Arc-length step [m].

0.5

Returns:

Type Description
RoadReference

The reference line.

project

project(x: ArrayLike, y: ArrayLike) -> tuple[FloatArray, FloatArray]

Map points to Frenet coordinates.

Parameters:

Name Type Description Default
x ArrayLike

Map x coordinates [m].

required
y ArrayLike

Map y coordinates [m].

required

Returns:

Type Description
FloatArray

(s, d): arc length [m] of the foot point on the polyline (extrapolated linearly beyond the ends) and

FloatArray

signed lateral offset [m] (positive to the left of the line's direction).

to_xy

to_xy(s: ArrayLike, d: ArrayLike) -> tuple[FloatArray, FloatArray]

Map Frenet coordinates back to map coordinates (position and heading interpolated along the line).

Parameters:

Name Type Description Default
s ArrayLike

Arc length [m].

required
d ArrayLike

Signed lateral offset [m], positive to the left of the line's direction.

required

Returns:

Type Description
tuple[FloatArray, FloatArray]

(x, y): map coordinates [m].

curvature_at

curvature_at(s: ArrayLike) -> FloatArray

Return the signed curvature of the line at the given arc lengths.

Parameters:

Name Type Description Default
s ArrayLike

Arc lengths [m].

required

Returns:

Type Description
FloatArray

Curvature [1/m] (positive for a left turn), interpolated linearly and constant beyond the ends.

line

line() -> Any

Return the line as a shapely geometry, e.g. for plotting or spatial joins.

Returns:

Type Description
Any

A shapely LineString through the samples, in map coordinates [m].

lane_layout

lane_layout(boundaries: DataFrame, max_abs_d: float = 30.0) -> pd.DataFrame

Project OpenDRIVE lane boundaries (io.opendrive.lane_boundaries) into this frame.

Parameters:

Name Type Description Default
boundaries DataFrame

Lane boundary points with road, section, lane, side, type, width and the map coordinates x_/y_centre, x_/y_inner, x_/y_outer [m].

required
max_abs_d float

Points farther than this [m] from the line are dropped (as are points beyond its ends).

30.0

Returns:

Type Description
DataFrame

Columns road, section, lane, side, type, width [m], s_ref [m] and the lateral

DataFrame

offsets d_centre, d_inner, d_outer [m]; the index of boundaries is kept.

lateral_kinematics

lateral_kinematics(t: ArrayLike, d: ArrayLike, smooth_s: float = 1.0) -> tuple[FloatArray, FloatArray]

Return the lateral speed and acceleration from the Frenet offset (cubic Savitzky-Golay).

Parameters:

Name Type Description Default
t ArrayLike

Sample times [s].

required
d ArrayLike

Lateral offset [m].

required
smooth_s float

Window of the filter [s] (odd number of samples, at least 5).

1.0

Returns:

Type Description
FloatArray

(v_lat, a_lat) [m/s], [m/s^2]; plain np.gradient derivatives if the track is not longer than the

FloatArray

window.

Step 04, stitching of fragmented tracks and imputation (docs/pipeline/04_stitching_imputation.md).

Entry functions: stitch_fragments (the cascade with PAPER_STAGES, then the optional joint bridges) and impute_trajectories (re-grid and fill short gaps), both in the module cascade. merge_local holds repair tools outside the chain.

StitchingStage dataclass

StitchingStage(max_gap_sec: float = 6.0, base_x_error_m: float = 2.0, max_accel_x: float = 2.0, max_decel_x: float = 6.0, base_y_error_m: float = 1.0, max_vy_m_per_s: float = 1.5, absolute_max_lateral_m: float = 5.0, max_len_error_m: float = 2.0, y_weight: float = 5.0, max_lateral_ratio: float = 0.2, len_weight: float = 0.0, speed_weight: float = 0.0, dv_norm_m_per_s: float = 5.0, max_search_distance_m: float = np.inf, state_window_sec: float | None = None, max_dv_m_per_s: float = np.inf, max_dv_growth_m_per_s2: float = 0.25, exit_zones: Sequence[Mapping[str, float]] | None = None, entry_zones: Sequence[Mapping[str, float]] | None = None, max_overlap_sec: float = 0.0, overlap_max_dx_m: float = 10.0, overlap_max_dy_m: float = 1.5, overlap_offsets: Sequence[Mapping[str, float]] | None = None, overlap_sigma_x: tuple[float, float] | None = None, overlap_sigma_y: float | None = None, overlap_sigma_v: tuple[float, float] | None = None, overlap_gate_sigma_x: float = 3.0, overlap_gate_sigma_y: float = 4.0, tail_speed_range: tuple[float, float] | None = None, offsets_for_gaps: bool = False, dim_sigmas: Mapping[str, float] | None = None, dim_gate_sigma: float = 4.0, ambiguity_margin: float | None = None)

Gates and cost weights of one stitching pass (stitch_trajectories; one entry of stitching.stages).

The cost of a gap pair is sqrt(dx_pred^2 + (y_weight dy_pred)^2 + (len_weight dl)^2 + (speed_weight dv)^2) [m] plus the dimension terms of dim_sigmas. len_weight and speed_weight add two soft terms on top of the position-only error (both 0.0 by default): the vehicle-length difference between the two fragments (near-noise-free on some datasets, e.g. DLR Highway Traffic, and thus a strong identity discriminator beyond the hard gate max_len_error_m) and the difference between the tail's projected velocity and the head's own observed velocity (catches implausible speed jumps inside the kinematic envelope). dl and dv are normalised to a metre-equivalent scale (dl relative to max_len_error_m, dv relative to dv_norm_m_per_s, both then in units of base_x_error_m), so that weights of order 1 have an influence comparable to dx_pred.

Attributes:

Name Type Description
max_gap_sec float

Longest gap [s] between a fragment's end and the next fragment's start that may be bridged.

base_x_error_m float

Longitudinal tolerance [m] added to the reachability envelope.

max_accel_x float

Maximum longitudinal acceleration [m/s^2] of the envelope.

max_decel_x float

Maximum longitudinal deceleration [m/s^2] of the envelope (positive).

base_y_error_m float

Lateral tolerance [m].

max_vy_m_per_s float

Maximum lateral speed [m/s] over the gap.

absolute_max_lateral_m float

Hard limit of the lateral offset [m] between the two fragments.

max_len_error_m float

Maximum difference in vehicle length [m].

y_weight float

Weight of the lateral prediction error in the cost [-].

max_lateral_ratio float

Maximum lateral offset per metre of longitudinal distance [-].

len_weight float

Weight of the normalised length difference in the cost [-].

speed_weight float

Weight of the normalised speed difference in the cost [-] (the difference is first divided by dv_norm_m_per_s and expressed in units of base_x_error_m).

dv_norm_m_per_s float

Speed difference [m/s] that counts as one unit in the speed term.

max_search_distance_m float

Maximum longitudinal distance [m] between the two fragments (default: unlimited). The accel/decel envelope grows quadratically with the gap and can span hundreds of metres for fast vehicles with a long max_gap_sec, where it no longer discriminates between candidates in dense traffic.

state_window_sec float | None

Length [s] of the end/start window from which the fragment velocity is estimated (least-squares slope of pos_lon/pos_lat over time). None keeps the original estimate from the last/first 5 samples, which is noisy at fragment ends (p90 error 2.9 m/s against the provider speed on drone data at 10 Hz).

max_dv_m_per_s float

Hard gate on the speed difference [m/s] between the tail's and the head's velocity, plus max_dv_growth_m_per_s2 per second of gap. Without it a stage with a short max_gap_sec accepts a wrong neighbour when the true continuation lies beyond its gap window (greedy cascade). Default: unlimited.

max_dv_growth_m_per_s2 float

Growth of the speed gate per second of gap [m/s^2].

exit_zones Sequence[Mapping[str, float]] | None

Dicts with x_min/x_max/y_min/y_max [m] (missing keys unbounded); fragments ending there are not continued. None for none.

entry_zones Sequence[Mapping[str, float]] | None

Same for fragments starting there, which are not treated as continuations.

max_overlap_sec float

Also link heads that start up to this long [s] before the tail ends (time overlap, e.g. two cameras seeing the vehicle at the same time at a camera seam; I-24 MOTION merges). For such pairs the prediction residuals are the medians of the longitudinal and lateral differences at the tail's time stamps inside the overlap (head interpolated, at least 3 samples) instead of the constant-velocity prediction; gates overlap_max_dx_m / overlap_max_dy_m replace the envelope and lateral gates. A head that ends before the tail or starts before the tail starts is a duplicate, not a continuation. 0 keeps the original behaviour (only 0 < dt).

overlap_max_dx_m float

Longitudinal gate [m] on the median difference inside an overlap.

overlap_max_dy_m float

Lateral gate [m] on the median difference inside an overlap.

overlap_offsets Sequence[Mapping[str, float]] | None

Systematic camera disagreement at seams: dicts with x_min, x_max [m] (pos_lon of the head start) and dx, dy [m] (head minus tail); inside a zone the offset is subtracted from the overlap residuals before gating and costing. Estimated per site from unambiguous overlap pairs. A zone may also give tau [s]: a camera time offset, subtracted as tau * v_tail from dx (the I-24 seam offsets grow with speed). None for no correction.

overlap_sigma_x tuple[float, float] | None

(a, b): speed-dependent spread of the longitudinal overlap residual, sigma_x = a + b * |v| [m] (v = tail speed [m/s]). If set, the overlap pairs are gated at overlap_gate_sigma_x sigma_x and overlap_gate_sigma_y sigma_y and costed in sigma units, base_x_error_m * sqrt((dx/sigma_x)^2 + (dy/sigma_y)^2 + (dv/sigma_v)^2); the fixed overlap gates are then ignored. At I-24 seams sigma_x grows from about 1 m at 8 m/s to about 3.5 m at 30 m/s (camera time offsets). None: fixed gates, metre costs.

overlap_sigma_y float | None

Spread of the lateral overlap residual [m] for the sigma-unit mode; None uses 0.25 m.

overlap_sigma_v tuple[float, float] | None

(a, b): speed-dependent spread of the speed difference [m/s] for the sigma-unit mode; None uses (1.0, 0.0).

overlap_gate_sigma_x float

Longitudinal gate in sigma_x.

overlap_gate_sigma_y float

Lateral gate in sigma_y.

tail_speed_range tuple[float, float] | None

(v_min, v_max) [m/s]: only tails whose end speed lies in [v_min, v_max) are considered in this pass (stages per traffic state). None for all tails.

offsets_for_gaps bool

Also apply overlap_offsets to gap pairs whose head starts in a seam zone (the prediction is shifted by dx + tau * v_tail and dy): a camera time offset moves short-gap continuations at a seam by metres (I-24: tau * v about 3-5 m), beyond the gap envelope.

dim_sigmas Mapping[str, float] | None

Vehicle dimension columns and the spread [m] of their difference between two fragments of one vehicle, e.g. {"length": 0.2, "width": 0.07, "height": 0.11} (I-24: per-fragment detector dimensions are nearly constant for one vehicle). Pairs with a difference above dim_gate_sigma sigma in any dimension are excluded; base_x_error_m * d / sigma per dimension is added to the cost (gap pairs and sigma-mode overlap pairs). Per-fragment medians; missing values pass. None: only the length gate max_len_error_m.

dim_gate_sigma float

Gate of the dimension differences in sigma.

ambiguity_margin float | None

If set, an assigned pair is ambiguous when another admissible candidate of the same tail or head costs less than cost + ambiguity_margin (cost units: metres, see the cost formula); ambiguous pairs are not linked. None: no check.

StitchingResult dataclass

StitchingResult(tracks: TrackFrame, links: DataFrame)

Result of stitch_fragments.

Attributes:

Name Type Description
tracks TrackFrame

The stitched samples (merged IDs).

links DataFrame

One record per link of two fragments (stitch_trajectories), with the stage number in stage.

stitch_trajectories

stitch_trajectories(df: TrackFrame, stage: StitchingStage | None = None, *, id_col: str = C.ID, links_out: list[dict[str, Any]] | None = None) -> TrackFrame

Stitch fragments by kinematic forward projection and one-to-one matching.

Inspired by the fragment-association idea in Wang, Y., Gloudemans, D., Ji, J., Teoh, Z. N., Liu, L., Zachár, G., Barbour, W., & Work, D. (2023). Automatic vehicle trajectory data reconstruction at scale (arXiv:2212.07907), https://doi.org/10.48550/arXiv.2212.07907; implemented as one-to-one bipartite matching with constant-velocity prediction.

The pass runs four stages: the end state of every fragment (tail) and the start state of every fragment (head) outside the exit / entry zones; the gates and costs of every tail-head pair (constant-velocity prediction over a gap, median residuals over a time overlap); the one-to-one assignment with the ambiguity check; and the join of the linked fragments. Linked fragments form connected groups; each group gets the smallest of its IDs (compared as strings). The former flat keyword form (stitch_trajectories(df, max_gap_sec=2.0, ...)) is still accepted.

Parameters:

Name Type Description Default
df TrackFrame

Trajectory points with id_col, datum, pos_lon and pos_lat [m] (pos_lon increasing with travel), optionally speed [km/h], length [m] and class. Not modified.

required
stage StitchingStage | None

Gates and cost weights of the pass. None uses StitchingStage().

None
id_col str

Column of the vehicle ID.

ID
links_out list[dict[str, Any]] | None

If a list is passed, one dict per assigned pair is appended: tail, head, dt [s] (negative = overlap), dx, dy [m] (residuals), dv [m/s], cost, n_alternatives, confidence (exp(-cost^2 / 2) normalised over the admissible alternatives of tail and head, cost in units of base_x_error_m), ambiguous, linked.

None

Returns:

Type Description
TrackFrame

A copy of df sorted by [id_col, datum] in which the IDs of stitched fragments are replaced by one

TrackFrame

common ID per vehicle. The number of rows is unchanged.

Raises:

Type Description
RuntimeError

If the number of rows changed (an internal error; checked also under python -O). Raised by the helper _check_no_data_loss that this function calls at the end.

default_stages

default_stages() -> list[dict[str, float]]

Return the built-in 4-stage cascade of cascaded_stitching.

The longest bridged gap grows from stage to stage (2, 5, 8, 11 s) while the position tolerances widen, so short gaps are linked first under tight gates and only the remaining fragment ends reach the looser stages.

Returns:

Type Description
list[dict[str, float]]

Four parameter dicts (StitchingStage keyword arguments; fresh copies, safe to modify).

overlap_stages

overlap_stages(max_overlap_sec: float = 3.0, overlap_max_dx_m: float = 6.0, overlap_max_dy_m: float = 2.0, ambiguity_margin: float = 1.0) -> list[dict[str, float]]

Return the cascade for multi-camera data with overlapping fields of view (I-24 MOTION).

A first stage links only time-overlapping fragments (max_overlap_sec, residuals at common times, speed gate 4 m/s; its gap window is closed), then the four default_stages follow unchanged for all gaps. All stages report ambiguous pairs (ambiguity_margin, m) and do not link them. On the A39 ground truth (hardly any overlaps) a stage 0 that also took gaps up to 1 s with its wider gates cost precision.

Parameters:

Name Type Description Default
max_overlap_sec float

Longest time overlap [s] of the overlap stage.

3.0
overlap_max_dx_m float

Longitudinal gate [m] of the overlap stage.

6.0
overlap_max_dy_m float

Lateral gate [m] of the overlap stage.

2.0
ambiguity_margin float

Cost margin [m] below which an alternative makes a pair ambiguous (all stages).

1.0

Returns:

Type Description
list[dict[str, float]]

Five parameter dicts (StitchingStage keyword arguments).

cascaded_stitching

cascaded_stitching(df: TrackFrame, id_col: str = C.ID, exit_zones: Sequence[Mapping[str, float]] | None = None, entry_zones: Sequence[Mapping[str, float]] | None = None, stages: Sequence[StitchingStage | Mapping[str, Any]] | None = None, links_out: list[dict[str, Any]] | None = None, keep_fragment_id: bool = False) -> TrackFrame

Run the kinematic trajectory stitching in cascaded stages.

Parameters:

Name Type Description Default
df TrackFrame

Trajectory points to stitch, as expected by stitch_trajectories.

required
id_col str

Column of the vehicle ID.

ID
exit_zones Sequence[Mapping[str, float]] | None

StitchingStage.exit_zones of every stage (None keeps those of StitchingStage entries).

None
entry_zones Sequence[Mapping[str, float]] | None

StitchingStage.entry_zones of every stage (None keeps those of StitchingStage entries).

None
stages Sequence[StitchingStage | Mapping[str, Any]] | None

StitchingStage objects or their keyword dicts (without the zones), each applied as one stitch_trajectories pass, in order (progressively looser gates as the gap tolerance grows is the usual pattern, but any sequence is accepted). None uses default_stages().

None
links_out list[dict[str, Any]] | None

If a list is passed, the link records of all stages are appended (see stitch_trajectories) with the stage number in stage.

None
keep_fragment_id bool

Keep the original IDs in a column fragment_id (needed by bridge_joints).

False

Returns:

Type Description
TrackFrame

The stitched points (same rows, merged IDs), as returned by the last stitch_trajectories pass.

bridge_joints

bridge_joints(df: TrackFrame, id_col: str = C.ID, fragment_col: str = 'fragment_id', trim_sec: float = 0.5, fit_sec: float = 0.5, rate_hz: float | None = None, max_bridge_sec: float = 4.0) -> TrackFrame

Join the fragments of each stitched vehicle with cubic Hermite bridges.

Stitching only relabels; time-overlapping fragments of one vehicle (camera seams) then interleave two cameras' samples, and plain concatenation leaves steps at every joint. Per vehicle and joint (fragments in order of their first sample): the last trim_sec of the earlier and the first trim_sec of the later fragment are dropped (spline overshoot at fragment ends), and the joint is filled at rate_hz with a cubic Hermite curve matching position and velocity (linear fits over fit_sec) on both sides, in pos_lon, pos_lat and, if present, utm_x/utm_y (C1). Gaps longer than max_bridge_sec are kept.

Parameters:

Name Type Description Default
df TrackFrame

Stitched points with id_col, fragment_col (original IDs, cascaded_stitching(..., keep_fragment_id=True)), datum and the position columns. Not modified.

required
id_col str

Column of the vehicle ID.

ID
fragment_col str

Column of the original fragment ID.

'fragment_id'
trim_sec float

Time [s] dropped at both fragment ends of a joint.

0.5
fit_sec float

Window [s] of the end-state fits.

0.5
rate_hz float | None

Sampling rate [Hz] of the bridge; None takes the median sampling rate of the fragments (25 Hz if it cannot be determined).

None
max_bridge_sec float

Longest gap [s] that is bridged.

4.0

Returns:

Type Description
TrackFrame

Points sorted by [id_col, datum] with is_bridge (True on bridge samples) and stitch_joint

TrackFrame

(True on the first sample of each bridge). Rows change: trimmed samples are dropped, bridges added.

Raises:

Type Description
KeyError

If fragment_col is missing.

impute_trajectories

impute_trajectories(df_stitched: TrackFrame, id_col: str = C.ID, fps: int = 30, n_cores: int | None = None, max_gap_sec: float = 3.0) -> TrackFrame

Re-grid each track to a regular frame rate and fill short gaps.

Each vehicle gets a regular grid t0 + k / fps (t0 = the whole second before its first sample), built from integer nanoseconds so that it does not drift. On this grid:

  • Continuous columns (pos_lon, pos_lat, utm_x, utm_y, pos_lat_raw, y_correction, pos_lon_ref) are interpolated per vehicle (PCHIP for three or more samples, else linear).
  • All other columns (orientation, class, length, lane, ...) take the value of the nearest original sample.
  • The geometry is rebuilt per vehicle from utm_x/utm_y if both are present.
  • is_imputed is True for grid points without an original sample within half a frame.
  • Grid points inside a gap longer than max_gap_sec are left out, so the vehicle keeps a gap there.

Imputation only interpolates positions. Any speed/acceleration columns are dropped; kinematics come from Step 3 of the pipeline.

Parameters:

Name Type Description Default
df_stitched TrackFrame

Trajectory points with id_col and datum. Not modified.

required
id_col str

Column of the vehicle ID.

ID
fps int

Target frame rate [Hz].

30
n_cores int | None

Number of worker processes. None or 1 runs sequentially, which is faster for typical recordings (see detect_lane_changes). With n_cores > 1 on Windows the calling script needs an if __name__ == "__main__": guard.

None
max_gap_sec float

Longest gap [s] that is filled.

3.0

Returns:

Type Description
TrackFrame

The re-gridded points with is_imputed (GeoDataFrame for GeoDataFrame input), sorted by

TrackFrame

[id_col, datum].

stitch_fragments

stitch_fragments(tracks: TrackFrame, *, stages: Sequence[StitchingStage | Mapping[str, Any]] | Literal['overlap'] | None = PAPER_STAGES, bridge_joints: bool = False, bridge_trim_sec: float = 0.5) -> StitchingResult

Link the fragments of one vehicle into one track and optionally bridge the joints.

Entry function of page 04 of the pipeline steps 01-10 (docs/pipeline/04_stitching_imputation.md). Requires the columns id, datum, pos_lon and pos_lat [m] (project_to_reference_line); class, length and speed are used if present. Rewrites id (one ID per stitched vehicle) and adds fragment_id when the joints are bridged. Method: cascaded one-to-one matching of fragment ends with a constant-velocity prediction (after Wang et al. 2023), joints bridged with cubic Hermite curves.

Example

import trajlab from trajlab.processing.reference_line import project_to_reference_line from trajlab.processing.stitching import stitch_fragments raw = trajlab.examples.synthetic_motorway() ref_east, _ = trajlab.estimate_ref_lines(raw) tracks = project_to_reference_line(raw[raw["orientation"] > 0], ref_east) result = stitch_fragments(tracks) stitched, links = result.tracks, result.links

Parameters:

Name Type Description Default
tracks TrackFrame

Samples of one direction of travel. Not modified.

required
stages Sequence[StitchingStage | Mapping[str, Any]] | Literal['overlap'] | None

Cascade stages (StitchingStage objects or their keyword dicts), "overlap" for overlap_stages() (multi-camera data with overlapping views) or None for the 4 built-in stages (default_stages()). Defaults to PAPER_STAGES (preset drone_hgv_paper).

PAPER_STAGES
bridge_joints bool

Fill the joints of stitched vehicles with cubic Hermite curves (bridge_joints). Defaults to False.

False
bridge_trim_sec float

Time [s] trimmed at each side of a joint before it is bridged. Defaults to 0.5.

0.5

Returns:

Type Description
StitchingResult

The stitched samples and the link records.

Stitch fragmented tracks, bridge the joints and re-grid the tracks (page 04 of the pipeline steps 01-10).

stitch_trajectories links the end of one fragment to the start of another by one-to-one bipartite matching with a constant-velocity prediction (after the fragment association of Wang et al. 2023), with the gates and cost weights of one pass in a StitchingStage; cascaded_stitching runs it in stages with progressively looser gates. bridge_joints fills the joints of stitched vehicles with cubic Hermite curves, and impute_trajectories re-grids every track to a regular frame rate and fills short gaps. stitch_fragments is the entry function of the stitching (the cascade with the stages of the preset drone_hgv_paper, PAPER_STAGES, then the joint bridges); impute_trajectories is the entry function of the imputation.

pos_lon [m] runs along the travel direction, pos_lat [m] to the left.

StitchingStage dataclass

StitchingStage(max_gap_sec: float = 6.0, base_x_error_m: float = 2.0, max_accel_x: float = 2.0, max_decel_x: float = 6.0, base_y_error_m: float = 1.0, max_vy_m_per_s: float = 1.5, absolute_max_lateral_m: float = 5.0, max_len_error_m: float = 2.0, y_weight: float = 5.0, max_lateral_ratio: float = 0.2, len_weight: float = 0.0, speed_weight: float = 0.0, dv_norm_m_per_s: float = 5.0, max_search_distance_m: float = np.inf, state_window_sec: float | None = None, max_dv_m_per_s: float = np.inf, max_dv_growth_m_per_s2: float = 0.25, exit_zones: Sequence[Mapping[str, float]] | None = None, entry_zones: Sequence[Mapping[str, float]] | None = None, max_overlap_sec: float = 0.0, overlap_max_dx_m: float = 10.0, overlap_max_dy_m: float = 1.5, overlap_offsets: Sequence[Mapping[str, float]] | None = None, overlap_sigma_x: tuple[float, float] | None = None, overlap_sigma_y: float | None = None, overlap_sigma_v: tuple[float, float] | None = None, overlap_gate_sigma_x: float = 3.0, overlap_gate_sigma_y: float = 4.0, tail_speed_range: tuple[float, float] | None = None, offsets_for_gaps: bool = False, dim_sigmas: Mapping[str, float] | None = None, dim_gate_sigma: float = 4.0, ambiguity_margin: float | None = None)

Gates and cost weights of one stitching pass (stitch_trajectories; one entry of stitching.stages).

The cost of a gap pair is sqrt(dx_pred^2 + (y_weight dy_pred)^2 + (len_weight dl)^2 + (speed_weight dv)^2) [m] plus the dimension terms of dim_sigmas. len_weight and speed_weight add two soft terms on top of the position-only error (both 0.0 by default): the vehicle-length difference between the two fragments (near-noise-free on some datasets, e.g. DLR Highway Traffic, and thus a strong identity discriminator beyond the hard gate max_len_error_m) and the difference between the tail's projected velocity and the head's own observed velocity (catches implausible speed jumps inside the kinematic envelope). dl and dv are normalised to a metre-equivalent scale (dl relative to max_len_error_m, dv relative to dv_norm_m_per_s, both then in units of base_x_error_m), so that weights of order 1 have an influence comparable to dx_pred.

Attributes:

Name Type Description
max_gap_sec float

Longest gap [s] between a fragment's end and the next fragment's start that may be bridged.

base_x_error_m float

Longitudinal tolerance [m] added to the reachability envelope.

max_accel_x float

Maximum longitudinal acceleration [m/s^2] of the envelope.

max_decel_x float

Maximum longitudinal deceleration [m/s^2] of the envelope (positive).

base_y_error_m float

Lateral tolerance [m].

max_vy_m_per_s float

Maximum lateral speed [m/s] over the gap.

absolute_max_lateral_m float

Hard limit of the lateral offset [m] between the two fragments.

max_len_error_m float

Maximum difference in vehicle length [m].

y_weight float

Weight of the lateral prediction error in the cost [-].

max_lateral_ratio float

Maximum lateral offset per metre of longitudinal distance [-].

len_weight float

Weight of the normalised length difference in the cost [-].

speed_weight float

Weight of the normalised speed difference in the cost [-] (the difference is first divided by dv_norm_m_per_s and expressed in units of base_x_error_m).

dv_norm_m_per_s float

Speed difference [m/s] that counts as one unit in the speed term.

max_search_distance_m float

Maximum longitudinal distance [m] between the two fragments (default: unlimited). The accel/decel envelope grows quadratically with the gap and can span hundreds of metres for fast vehicles with a long max_gap_sec, where it no longer discriminates between candidates in dense traffic.

state_window_sec float | None

Length [s] of the end/start window from which the fragment velocity is estimated (least-squares slope of pos_lon/pos_lat over time). None keeps the original estimate from the last/first 5 samples, which is noisy at fragment ends (p90 error 2.9 m/s against the provider speed on drone data at 10 Hz).

max_dv_m_per_s float

Hard gate on the speed difference [m/s] between the tail's and the head's velocity, plus max_dv_growth_m_per_s2 per second of gap. Without it a stage with a short max_gap_sec accepts a wrong neighbour when the true continuation lies beyond its gap window (greedy cascade). Default: unlimited.

max_dv_growth_m_per_s2 float

Growth of the speed gate per second of gap [m/s^2].

exit_zones Sequence[Mapping[str, float]] | None

Dicts with x_min/x_max/y_min/y_max [m] (missing keys unbounded); fragments ending there are not continued. None for none.

entry_zones Sequence[Mapping[str, float]] | None

Same for fragments starting there, which are not treated as continuations.

max_overlap_sec float

Also link heads that start up to this long [s] before the tail ends (time overlap, e.g. two cameras seeing the vehicle at the same time at a camera seam; I-24 MOTION merges). For such pairs the prediction residuals are the medians of the longitudinal and lateral differences at the tail's time stamps inside the overlap (head interpolated, at least 3 samples) instead of the constant-velocity prediction; gates overlap_max_dx_m / overlap_max_dy_m replace the envelope and lateral gates. A head that ends before the tail or starts before the tail starts is a duplicate, not a continuation. 0 keeps the original behaviour (only 0 < dt).

overlap_max_dx_m float

Longitudinal gate [m] on the median difference inside an overlap.

overlap_max_dy_m float

Lateral gate [m] on the median difference inside an overlap.

overlap_offsets Sequence[Mapping[str, float]] | None

Systematic camera disagreement at seams: dicts with x_min, x_max [m] (pos_lon of the head start) and dx, dy [m] (head minus tail); inside a zone the offset is subtracted from the overlap residuals before gating and costing. Estimated per site from unambiguous overlap pairs. A zone may also give tau [s]: a camera time offset, subtracted as tau * v_tail from dx (the I-24 seam offsets grow with speed). None for no correction.

overlap_sigma_x tuple[float, float] | None

(a, b): speed-dependent spread of the longitudinal overlap residual, sigma_x = a + b * |v| [m] (v = tail speed [m/s]). If set, the overlap pairs are gated at overlap_gate_sigma_x sigma_x and overlap_gate_sigma_y sigma_y and costed in sigma units, base_x_error_m * sqrt((dx/sigma_x)^2 + (dy/sigma_y)^2 + (dv/sigma_v)^2); the fixed overlap gates are then ignored. At I-24 seams sigma_x grows from about 1 m at 8 m/s to about 3.5 m at 30 m/s (camera time offsets). None: fixed gates, metre costs.

overlap_sigma_y float | None

Spread of the lateral overlap residual [m] for the sigma-unit mode; None uses 0.25 m.

overlap_sigma_v tuple[float, float] | None

(a, b): speed-dependent spread of the speed difference [m/s] for the sigma-unit mode; None uses (1.0, 0.0).

overlap_gate_sigma_x float

Longitudinal gate in sigma_x.

overlap_gate_sigma_y float

Lateral gate in sigma_y.

tail_speed_range tuple[float, float] | None

(v_min, v_max) [m/s]: only tails whose end speed lies in [v_min, v_max) are considered in this pass (stages per traffic state). None for all tails.

offsets_for_gaps bool

Also apply overlap_offsets to gap pairs whose head starts in a seam zone (the prediction is shifted by dx + tau * v_tail and dy): a camera time offset moves short-gap continuations at a seam by metres (I-24: tau * v about 3-5 m), beyond the gap envelope.

dim_sigmas Mapping[str, float] | None

Vehicle dimension columns and the spread [m] of their difference between two fragments of one vehicle, e.g. {"length": 0.2, "width": 0.07, "height": 0.11} (I-24: per-fragment detector dimensions are nearly constant for one vehicle). Pairs with a difference above dim_gate_sigma sigma in any dimension are excluded; base_x_error_m * d / sigma per dimension is added to the cost (gap pairs and sigma-mode overlap pairs). Per-fragment medians; missing values pass. None: only the length gate max_len_error_m.

dim_gate_sigma float

Gate of the dimension differences in sigma.

ambiguity_margin float | None

If set, an assigned pair is ambiguous when another admissible candidate of the same tail or head costs less than cost + ambiguity_margin (cost units: metres, see the cost formula); ambiguous pairs are not linked. None: no check.

StitchingResult dataclass

StitchingResult(tracks: TrackFrame, links: DataFrame)

Result of stitch_fragments.

Attributes:

Name Type Description
tracks TrackFrame

The stitched samples (merged IDs).

links DataFrame

One record per link of two fragments (stitch_trajectories), with the stage number in stage.

stitch_trajectories

stitch_trajectories(df: TrackFrame, stage: StitchingStage | None = None, *, id_col: str = C.ID, links_out: list[dict[str, Any]] | None = None) -> TrackFrame

Stitch fragments by kinematic forward projection and one-to-one matching.

Inspired by the fragment-association idea in Wang, Y., Gloudemans, D., Ji, J., Teoh, Z. N., Liu, L., Zachár, G., Barbour, W., & Work, D. (2023). Automatic vehicle trajectory data reconstruction at scale (arXiv:2212.07907), https://doi.org/10.48550/arXiv.2212.07907; implemented as one-to-one bipartite matching with constant-velocity prediction.

The pass runs four stages: the end state of every fragment (tail) and the start state of every fragment (head) outside the exit / entry zones; the gates and costs of every tail-head pair (constant-velocity prediction over a gap, median residuals over a time overlap); the one-to-one assignment with the ambiguity check; and the join of the linked fragments. Linked fragments form connected groups; each group gets the smallest of its IDs (compared as strings). The former flat keyword form (stitch_trajectories(df, max_gap_sec=2.0, ...)) is still accepted.

Parameters:

Name Type Description Default
df TrackFrame

Trajectory points with id_col, datum, pos_lon and pos_lat [m] (pos_lon increasing with travel), optionally speed [km/h], length [m] and class. Not modified.

required
stage StitchingStage | None

Gates and cost weights of the pass. None uses StitchingStage().

None
id_col str

Column of the vehicle ID.

ID
links_out list[dict[str, Any]] | None

If a list is passed, one dict per assigned pair is appended: tail, head, dt [s] (negative = overlap), dx, dy [m] (residuals), dv [m/s], cost, n_alternatives, confidence (exp(-cost^2 / 2) normalised over the admissible alternatives of tail and head, cost in units of base_x_error_m), ambiguous, linked.

None

Returns:

Type Description
TrackFrame

A copy of df sorted by [id_col, datum] in which the IDs of stitched fragments are replaced by one

TrackFrame

common ID per vehicle. The number of rows is unchanged.

Raises:

Type Description
RuntimeError

If the number of rows changed (an internal error; checked also under python -O). Raised by the helper _check_no_data_loss that this function calls at the end.

default_stages

default_stages() -> list[dict[str, float]]

Return the built-in 4-stage cascade of cascaded_stitching.

The longest bridged gap grows from stage to stage (2, 5, 8, 11 s) while the position tolerances widen, so short gaps are linked first under tight gates and only the remaining fragment ends reach the looser stages.

Returns:

Type Description
list[dict[str, float]]

Four parameter dicts (StitchingStage keyword arguments; fresh copies, safe to modify).

overlap_stages

overlap_stages(max_overlap_sec: float = 3.0, overlap_max_dx_m: float = 6.0, overlap_max_dy_m: float = 2.0, ambiguity_margin: float = 1.0) -> list[dict[str, float]]

Return the cascade for multi-camera data with overlapping fields of view (I-24 MOTION).

A first stage links only time-overlapping fragments (max_overlap_sec, residuals at common times, speed gate 4 m/s; its gap window is closed), then the four default_stages follow unchanged for all gaps. All stages report ambiguous pairs (ambiguity_margin, m) and do not link them. On the A39 ground truth (hardly any overlaps) a stage 0 that also took gaps up to 1 s with its wider gates cost precision.

Parameters:

Name Type Description Default
max_overlap_sec float

Longest time overlap [s] of the overlap stage.

3.0
overlap_max_dx_m float

Longitudinal gate [m] of the overlap stage.

6.0
overlap_max_dy_m float

Lateral gate [m] of the overlap stage.

2.0
ambiguity_margin float

Cost margin [m] below which an alternative makes a pair ambiguous (all stages).

1.0

Returns:

Type Description
list[dict[str, float]]

Five parameter dicts (StitchingStage keyword arguments).

cascaded_stitching

cascaded_stitching(df: TrackFrame, id_col: str = C.ID, exit_zones: Sequence[Mapping[str, float]] | None = None, entry_zones: Sequence[Mapping[str, float]] | None = None, stages: Sequence[StitchingStage | Mapping[str, Any]] | None = None, links_out: list[dict[str, Any]] | None = None, keep_fragment_id: bool = False) -> TrackFrame

Run the kinematic trajectory stitching in cascaded stages.

Parameters:

Name Type Description Default
df TrackFrame

Trajectory points to stitch, as expected by stitch_trajectories.

required
id_col str

Column of the vehicle ID.

ID
exit_zones Sequence[Mapping[str, float]] | None

StitchingStage.exit_zones of every stage (None keeps those of StitchingStage entries).

None
entry_zones Sequence[Mapping[str, float]] | None

StitchingStage.entry_zones of every stage (None keeps those of StitchingStage entries).

None
stages Sequence[StitchingStage | Mapping[str, Any]] | None

StitchingStage objects or their keyword dicts (without the zones), each applied as one stitch_trajectories pass, in order (progressively looser gates as the gap tolerance grows is the usual pattern, but any sequence is accepted). None uses default_stages().

None
links_out list[dict[str, Any]] | None

If a list is passed, the link records of all stages are appended (see stitch_trajectories) with the stage number in stage.

None
keep_fragment_id bool

Keep the original IDs in a column fragment_id (needed by bridge_joints).

False

Returns:

Type Description
TrackFrame

The stitched points (same rows, merged IDs), as returned by the last stitch_trajectories pass.

bridge_joints

bridge_joints(df: TrackFrame, id_col: str = C.ID, fragment_col: str = 'fragment_id', trim_sec: float = 0.5, fit_sec: float = 0.5, rate_hz: float | None = None, max_bridge_sec: float = 4.0) -> TrackFrame

Join the fragments of each stitched vehicle with cubic Hermite bridges.

Stitching only relabels; time-overlapping fragments of one vehicle (camera seams) then interleave two cameras' samples, and plain concatenation leaves steps at every joint. Per vehicle and joint (fragments in order of their first sample): the last trim_sec of the earlier and the first trim_sec of the later fragment are dropped (spline overshoot at fragment ends), and the joint is filled at rate_hz with a cubic Hermite curve matching position and velocity (linear fits over fit_sec) on both sides, in pos_lon, pos_lat and, if present, utm_x/utm_y (C1). Gaps longer than max_bridge_sec are kept.

Parameters:

Name Type Description Default
df TrackFrame

Stitched points with id_col, fragment_col (original IDs, cascaded_stitching(..., keep_fragment_id=True)), datum and the position columns. Not modified.

required
id_col str

Column of the vehicle ID.

ID
fragment_col str

Column of the original fragment ID.

'fragment_id'
trim_sec float

Time [s] dropped at both fragment ends of a joint.

0.5
fit_sec float

Window [s] of the end-state fits.

0.5
rate_hz float | None

Sampling rate [Hz] of the bridge; None takes the median sampling rate of the fragments (25 Hz if it cannot be determined).

None
max_bridge_sec float

Longest gap [s] that is bridged.

4.0

Returns:

Type Description
TrackFrame

Points sorted by [id_col, datum] with is_bridge (True on bridge samples) and stitch_joint

TrackFrame

(True on the first sample of each bridge). Rows change: trimmed samples are dropped, bridges added.

Raises:

Type Description
KeyError

If fragment_col is missing.

impute_trajectories

impute_trajectories(df_stitched: TrackFrame, id_col: str = C.ID, fps: int = 30, n_cores: int | None = None, max_gap_sec: float = 3.0) -> TrackFrame

Re-grid each track to a regular frame rate and fill short gaps.

Each vehicle gets a regular grid t0 + k / fps (t0 = the whole second before its first sample), built from integer nanoseconds so that it does not drift. On this grid:

  • Continuous columns (pos_lon, pos_lat, utm_x, utm_y, pos_lat_raw, y_correction, pos_lon_ref) are interpolated per vehicle (PCHIP for three or more samples, else linear).
  • All other columns (orientation, class, length, lane, ...) take the value of the nearest original sample.
  • The geometry is rebuilt per vehicle from utm_x/utm_y if both are present.
  • is_imputed is True for grid points without an original sample within half a frame.
  • Grid points inside a gap longer than max_gap_sec are left out, so the vehicle keeps a gap there.

Imputation only interpolates positions. Any speed/acceleration columns are dropped; kinematics come from Step 3 of the pipeline.

Parameters:

Name Type Description Default
df_stitched TrackFrame

Trajectory points with id_col and datum. Not modified.

required
id_col str

Column of the vehicle ID.

ID
fps int

Target frame rate [Hz].

30
n_cores int | None

Number of worker processes. None or 1 runs sequentially, which is faster for typical recordings (see detect_lane_changes). With n_cores > 1 on Windows the calling script needs an if __name__ == "__main__": guard.

None
max_gap_sec float

Longest gap [s] that is filled.

3.0

Returns:

Type Description
TrackFrame

The re-gridded points with is_imputed (GeoDataFrame for GeoDataFrame input), sorted by

TrackFrame

[id_col, datum].

stitch_fragments

stitch_fragments(tracks: TrackFrame, *, stages: Sequence[StitchingStage | Mapping[str, Any]] | Literal['overlap'] | None = PAPER_STAGES, bridge_joints: bool = False, bridge_trim_sec: float = 0.5) -> StitchingResult

Link the fragments of one vehicle into one track and optionally bridge the joints.

Entry function of page 04 of the pipeline steps 01-10 (docs/pipeline/04_stitching_imputation.md). Requires the columns id, datum, pos_lon and pos_lat [m] (project_to_reference_line); class, length and speed are used if present. Rewrites id (one ID per stitched vehicle) and adds fragment_id when the joints are bridged. Method: cascaded one-to-one matching of fragment ends with a constant-velocity prediction (after Wang et al. 2023), joints bridged with cubic Hermite curves.

Example

import trajlab from trajlab.processing.reference_line import project_to_reference_line from trajlab.processing.stitching import stitch_fragments raw = trajlab.examples.synthetic_motorway() ref_east, _ = trajlab.estimate_ref_lines(raw) tracks = project_to_reference_line(raw[raw["orientation"] > 0], ref_east) result = stitch_fragments(tracks) stitched, links = result.tracks, result.links

Parameters:

Name Type Description Default
tracks TrackFrame

Samples of one direction of travel. Not modified.

required
stages Sequence[StitchingStage | Mapping[str, Any]] | Literal['overlap'] | None

Cascade stages (StitchingStage objects or their keyword dicts), "overlap" for overlap_stages() (multi-camera data with overlapping views) or None for the 4 built-in stages (default_stages()). Defaults to PAPER_STAGES (preset drone_hgv_paper).

PAPER_STAGES
bridge_joints bool

Fill the joints of stitched vehicles with cubic Hermite curves (bridge_joints). Defaults to False.

False
bridge_trim_sec float

Time [s] trimmed at each side of a joint before it is bridged. Defaults to 0.5.

0.5

Returns:

Type Description
StitchingResult

The stitched samples and the link records.

Step 10, output grid and surroundings (docs/pipeline/10_output_grid_surroundings.md).

Entry functions in run order: resample_tracks (the common output grid, module resampling; off in the preset drone_hgv_paper) and compute_surroundings (the six surrounding vehicles, defined in trajlab.analysis.interactions.surroundings). The platoon consistency of Montanino & Punzo runs after them (trajlab.processing.kinematics.platoon.enforce_platoon_consistency).

ResamplingResult dataclass

ResamplingResult(tracks: TrackFrame, rows_from_mp_grid: int | None = None)

Result of resample_tracks.

Attributes:

Name Type Description
tracks TrackFrame

The samples on the output grid.

rows_from_mp_grid int | None

Number of output rows that took the Montanino & Punzo grid values; None if they were not used (no reconstruction given, or another rate).

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.

resample_tracks

resample_tracks(tracks: TrackFrame, *, rate_hz: float = 10.0, interpolate_columns: Iterable[str] = (), nearest_columns: Iterable[str] = (), drop_columns: Iterable[str] = (), mp_tracks: Mapping[Hashable, TrackKinematics] | None = None, mp_rate_hz: float = 10.0) -> ResamplingResult

Put all trajectories on one common output grid; take the Montanino & Punzo grid values where they exist.

Entry function of the output grid of page 10 of the pipeline steps 01-10 (docs/pipeline/10_output_grid_surroundings.md). Requires the columns id and datum; numeric columns are interpolated, labels taken from the nearest sample (resample_to_output_grid). With mp_tracks (the KinematicsResult.mp_tracks of reconstruct_kinematics) at the same rate, pos_lon, speed, acceleration and mp_reconstructed come from the reconstruction grid instead of a round trip grid -> native -> grid. The preset drone_hgv_paper keeps the native rate (no resampling).

Example

import trajlab from trajlab.processing.surroundings import resample_tracks raw = trajlab.examples.synthetic_motorway() ref_east, _ = trajlab.estimate_ref_lines(raw) tracks = trajlab.run_pipeline(raw[raw["orientation"] > 0], ref_east) on_grid = resample_tracks(tracks, rate_hz=10.0).tracks

Parameters:

Name Type Description Default
tracks TrackFrame

Samples. Not modified.

required
rate_hz float

Output rate [Hz]. Defaults to 10.0.

10.0
interpolate_columns Iterable[str]

Columns forced to linear interpolation.

()
nearest_columns Iterable[str]

Columns forced to the nearest sample.

()
drop_columns Iterable[str]

Columns dropped.

()
mp_tracks Mapping[Hashable, TrackKinematics] | None

Vehicle ID -> its Montanino & Punzo reconstruction; None or empty for none.

None
mp_rate_hz float

Rate [Hz] of the reconstruction grid; its values are used only if it equals rate_hz. Defaults to 10.0.

10.0

Returns:

Type Description
ResamplingResult

The samples on the output grid and the number of rows taken from the reconstruction grid.

Resample trajectories from the native frame rate onto a common output time grid (Step 8).

ResamplingResult dataclass

ResamplingResult(tracks: TrackFrame, rows_from_mp_grid: int | None = None)

Result of resample_tracks.

Attributes:

Name Type Description
tracks TrackFrame

The samples on the output grid.

rows_from_mp_grid int | None

Number of output rows that took the Montanino & Punzo grid values; None if they were not used (no reconstruction given, or another rate).

resample_to_output_grid

resample_to_output_grid(df: TrackFrame, rate_hz: float | None = 10.0, id_col: str = C.ID, time_col: str = C.TIME, interpolate_columns: Iterable[str] | None = None, nearest_columns: Iterable[str] | None = None, drop_columns: Iterable[str] | None = None) -> TrackFrame

Resample all trajectories onto one common time grid.

The grid is t0 + k / rate_hz with the same t0 for every vehicle: the global minimum timestamp floored to a whole multiple of the grid step (counted from the Unix epoch, so grids of different recordings line up). Each vehicle keeps only the grid points inside its own observed time span; nothing is extrapolated.

  • Continuous columns (CONTINUOUS_COLUMNS: positions, speed, acceleration, UTM coordinates, alignment terms) are interpolated linearly in time.
  • The other columns the pipeline knows (lane IDs, flags, class, length, orientation, IDs of neighbours, ...) take the value of the nearest native sample.
  • Columns the pipeline does not know follow their dtype: floating-point columns are interpolated linearly in time (so e.g. a time_sec column stays consistent with datum); integer, boolean, string, categorical and datetime columns take the nearest native sample. The rule chosen for each unknown column is logged at INFO level.
  • interpolate_columns, nearest_columns and drop_columns override these rules for the named columns.
  • The geometry is rebuilt from utm_x/utm_y when both are present, otherwise it is taken from the nearest native sample (ties go to the earlier sample).
  • Duplicate (vehicle, time) rows are dropped (first kept) with a warning.

Parameters:

Name Type Description Default
df TrackFrame

Trajectory points at the native frame rate. Not modified.

required
rate_hz float | None

Output rate [Hz]; None returns an unchanged copy.

10.0
id_col str

Column of the vehicle ID.

ID
time_col str

Column of the time stamp (naive or tz-aware datetimes).

TIME
interpolate_columns Iterable[str] | None

Columns to interpolate linearly regardless of the rules above (must be numeric).

None
nearest_columns Iterable[str] | None

Columns to take from the nearest native sample.

None
drop_columns Iterable[str] | None

Columns to leave out of the result.

None

Returns:

Type Description
TrackFrame

A new DataFrame (GeoDataFrame if the input is one) with the same columns (minus the dropped ones), one row

TrackFrame

per vehicle and grid point, sorted by [id_col, time_col]. Vehicles whose span contains no grid point

TrackFrame

are dropped with a log message.

Raises:

Type Description
ValueError

If rate_hz is not positive or a column of interpolate_columns is not numeric.

resample_tracks

resample_tracks(tracks: TrackFrame, *, rate_hz: float = 10.0, interpolate_columns: Iterable[str] = (), nearest_columns: Iterable[str] = (), drop_columns: Iterable[str] = (), mp_tracks: Mapping[Hashable, TrackKinematics] | None = None, mp_rate_hz: float = 10.0) -> ResamplingResult

Put all trajectories on one common output grid; take the Montanino & Punzo grid values where they exist.

Entry function of the output grid of page 10 of the pipeline steps 01-10 (docs/pipeline/10_output_grid_surroundings.md). Requires the columns id and datum; numeric columns are interpolated, labels taken from the nearest sample (resample_to_output_grid). With mp_tracks (the KinematicsResult.mp_tracks of reconstruct_kinematics) at the same rate, pos_lon, speed, acceleration and mp_reconstructed come from the reconstruction grid instead of a round trip grid -> native -> grid. The preset drone_hgv_paper keeps the native rate (no resampling).

Example

import trajlab from trajlab.processing.surroundings import resample_tracks raw = trajlab.examples.synthetic_motorway() ref_east, _ = trajlab.estimate_ref_lines(raw) tracks = trajlab.run_pipeline(raw[raw["orientation"] > 0], ref_east) on_grid = resample_tracks(tracks, rate_hz=10.0).tracks

Parameters:

Name Type Description Default
tracks TrackFrame

Samples. Not modified.

required
rate_hz float

Output rate [Hz]. Defaults to 10.0.

10.0
interpolate_columns Iterable[str]

Columns forced to linear interpolation.

()
nearest_columns Iterable[str]

Columns forced to the nearest sample.

()
drop_columns Iterable[str]

Columns dropped.

()
mp_tracks Mapping[Hashable, TrackKinematics] | None

Vehicle ID -> its Montanino & Punzo reconstruction; None or empty for none.

None
mp_rate_hz float

Rate [Hz] of the reconstruction grid; its values are used only if it equals rate_hz. Defaults to 10.0.

10.0

Returns:

Type Description
ResamplingResult

The samples on the output grid and the number of rows taken from the reconstruction grid.