Skip to content

Configuration

Generated by docs/scripts/make_api_pages.py.

Configuration of the pipeline: the nested PipelineConfig, its schema, presets, site and dataset files.

  • pipeline: PipelineConfig and the flat aliases; it re-exports the section dataclasses, which are defined one module per processing step in the private _sections package.
  • schema: schema and validation derived from the dataclasses.
  • loader: presets (presets/*.yaml), site files (sites/*.yaml) and dataset files (datasets/*.yaml), shipped as package data.

AlignmentConfig dataclass

AlignmentConfig(enabled: bool = True, 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: list[str] | None = None)

Step 2: road-edge alignment.

Attributes:

Name Type Description
enabled bool

Run the step. Defaults to True.

km_step float

Longitudinal bin width of the road-edge profile in meters. Defaults to 10.0 m.

smoothing_sigma_m float

Gaussian smoothing sigma of the profile in meters. Defaults to 30.0 m.

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 in meters the road-edge profile is moved to (center of lane 1). Defaults to 2.0 m.

edge_freeze_m float

Length in meters at each end of the profile frozen to the first interior value; 0 disables the freeze. Defaults to 0.0 m (no freeze; a 100 m freeze leaves the reference-line deviation at the ends uncorrected and raises the lane-change density there).

edge_freeze_bins int | None

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

profile_classes list[str] | None

Classes whose positions define the road-edge profile (e.g. ["Car"]: not displaced by perspective); the profile is applied to all rows. Defaults to None (all rows).

AuxLaneZone dataclass

AuxLaneZone(lon_start: float, lon_end: float, kind: str = 'acceleration')

A longitudinal section of the road with an auxiliary lane (lane 0).

Zones are entered by hand per site, e.g. from aerial images.

Attributes:

Name Type Description
lon_start float

Start of the zone in pos_lon meters (after Step 1, i.e. measured in the direction of travel).

lon_end float

End of the zone in pos_lon meters.

kind str

One of "on_ramp", "off_ramp", "acceleration", "deceleration", "weaving". Defaults to "acceleration".

__post_init__

__post_init__() -> None

Check the zone limits and the kind.

Raises:

Type Description
ValueError

If lon_end <= lon_start or kind is not in AUX_LANE_ZONE_KINDS.

contains

contains(pos_lon: float | ndarray | Series) -> bool | np.ndarray | pd.Series

Return whether pos_lon lies inside the zone (bounds included).

Parameters:

Name Type Description Default
pos_lon float | ndarray | Series

Longitudinal position(s) [m] (scalar, array or Series).

required

Returns:

Type Description
bool | ndarray | Series

A boolean (scalar, array or Series) of the same shape as pos_lon.

HmmConfig dataclass

HmmConfig(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)

Hidden-Markov-model lane assignment (lanes.assignment_method = "hmm").

Rates are per second and converted per sample with p = 1 - exp(-rate * dt), so results do not depend on the sampling rate.

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 (0.2 in the original specification).

epsilon float

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

emission_floor str

"relative" (floor relative to the best lane, default) or "uniform" (uniform over the lateral range, as originally specified); see processing.lanes.hmm.emission_logprob.

initial_geometry str

Where the lane centers of the first decoding come from: "labels" (default; medians of the Step 4 labels per em_bin_m bin outside detector intervals, smoothed with em_smooth_sigma_m) or "tracker" (the rolling GMM tracker centers of Step 4, interpolated along s).

zone_margin_m float

Lane 0 is valid up to this distance (m) beyond the ends of an auxiliary-lane zone. Defaults to 10.0.

merge_gap_s float

Detector intervals of one vehicle less than this far apart (s) form one manoeuvre for the A -> B -> A collapse (excursion split into "out" and "back"). Defaults to 1.0.

max_dwell_s float

A->B->A inside one joined manoeuvre window is collapsed to A only if the time in B is at most this (s; a longer stay in B counts as two real lane changes). Defaults to 2.0.

aux_lane_fallback bool

If zones are configured but Step 4 gave lane 0 no points, lane 0 still exists with center c_1 minus a lane width (e.g. a short deceleration lane at the end of the section). Defaults to True.

conflict_margin_m float

Feasibility: two vehicles in one lane conflict if their centers are closer than (L1 + L2) / 2 plus this margin (m). Defaults to 1.0.

conflict_penalty float

Log-penalty added to the emission of the less confident vehicle 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

Conflicts longer than this (s) between two confident vehicles less than duplicate_max_lateral_m apart are flagged as suspected duplicate tracks instead of re-assigned. Defaults to 1.0.

duplicate_min_confidence float

Duplicate flag: the lane confidence (0-1) of both vehicles must exceed this (see duplicate_min_overlap_sec). Defaults to 0.9.

duplicate_max_lateral_m float

Duplicate flag: the vehicles must be laterally closer than this [m] (see duplicate_min_overlap_sec). 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 (0.1 %).

em_bin_m float

Bin length of the center re-estimation (m). Defaults to 10.0.

em_smooth_sigma_m float

Gaussian smoothing of the center profile (m). Defaults to 30.0.

min_points_per_bin int

Minimum points of a lane in a bin (about one vehicle per 10 m bin at 30 Hz). Defaults to 10.

conflict_damping bool

Damped conflict resolution: only conflict episodes of a pair lasting at least conflict_min_duration_sec are resolved, the penalty window of the re-assigned vehicle covers at least conflict_hold_sec (not into its detected lane changes), and every conflict episode of a pair is resolved at most once. Defaults to True since 1.0 (False: every conflict frame is resolved, the behavior before 1.0).

conflict_min_duration_sec float

t_min of the damping (s). Defaults to 1.0.

conflict_hold_sec float

t_hold of the damping (s). Defaults to 2.0.

min_aux_zone_m float

The HMM ignores auxiliary-lane zones shorter than this (m): their lane center cannot be estimated from the 50 m bins, the auxiliary state then pulls lane-1 vehicles in and must release them at the zone edges. The zones stay in the site configuration (alignment, heuristic). Defaults to 50.0 since 1.0, the bin length of the auxiliary-lane center estimate (0.0: off).

ImputationConfig dataclass

ImputationConfig(enabled: bool = False, fps: int = 30, max_gap_sec: float = 3.0)

Optional step: imputation (re-gridding each track).

Attributes:

Name Type Description
enabled bool

Run the step. Defaults to False.

fps int

Frame rate of the imputation grid in Hz. Defaults to 30.

max_gap_sec float

Longest gap in seconds that is filled; longer gaps stay gaps. Defaults to 3.0 s.

KinematicsConfig dataclass

KinematicsConfig(enabled: bool = True, smooth_window_sec: float = 4.0, smooth_window_frames: int | None = None, poly_order: int = 2, max_reversal_m: float = 15.0, frame_rate: float = 30.0, method: str = 'montanino_punzo', lateral_smooth_window_sec: float | None = None, mp: MontaninoPunzoConfig = MontaninoPunzoConfig(), reconstruction: dict[str, Any] | None = None, spatial_correction: dict[str, Any] | None = None)

Step 3: kinematic reconstruction (Montanino & Punzo or Savitzky-Golay).

The smoothing window is defined in seconds (smooth_window_sec) and converted to an odd number of frames from each vehicle's own median sampling interval (121 frames at 30 Hz, 41 at 10 Hz). If smooth_window_frames is set, that fixed frame count wins for every vehicle.

method selects how the longitudinal kinematics are derived: "montanino_punzo" (default; the multistep reconstruction of Montanino & Punzo (2013, 2015), parameters in mp) or "savgol" (Savitzky-Golay, kept for comparison). The lateral position is always smoothed with Savitzky-Golay.

Attributes:

Name Type Description
enabled bool

Run the step. Defaults to True.

smooth_window_sec float

Savitzky-Golay window in seconds. Defaults to 4.0 s.

smooth_window_frames int | None

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

poly_order int

Polynomial order. Quadratic, because a cubic leaves visible ripples in the acceleration. Defaults to 2.

max_reversal_m float

Backward motion in meters above which a track is discarded as a tracking error. Defaults to 15.0 m.

frame_rate float

Nominal recording frame rate in Hz, used by get_smooth_window_frames when no rate is given. Defaults to 30.0 Hz.

method str

"montanino_punzo" or "savgol". Defaults to "montanino_punzo".

lateral_smooth_window_sec float | None

Savitzky-Golay window in seconds for pos_lat with the montanino_punzo method; None uses the same window as the longitudinal smoothing (smooth_window_sec / smooth_window_frames), i.e. exactly the lateral smoothing of the savgol method. Defaults to None.

mp MontaninoPunzoConfig

Parameters of the montanino_punzo method; a dict is converted. Defaults to MontaninoPunzoConfig().

reconstruction dict[str, Any] | None

Alternative longitudinal reconstruction used in place of the Montanino & Punzo steps of the montanino_punzo method (same 10 Hz grid, same write-back), e.g. {"method": "tv", "params": {"lam": 0.03, "order": 3}} or with "params_by_speed": [[20.0, {...}], [null, {...}]] (upper speed bound in m/s per entry, chosen by the vehicle's median speed); see processing.kinematics.filters.track_kinematics. Chosen per dataset by the synthetic recovery test. Mandatory keys: admissible_v_bands (speed bands that passed the counter-check) and edge_s (track-edge exclusion); the output gets the columns recon_admissible and recon_edge. Defaults to None (Montanino & Punzo).

spatial_correction dict[str, Any] | None

Removes a spatially fixed position error before the longitudinal reconstruction: {"profiles": "<parquet>"}, a table from processing.kinematics.spatial_correction.estimate_spatial_bias for this recording and direction (estimated from the raw positions and the lanes of a first run). Only lanes that passed the time-half cross-validation are corrected; the column spatial_corrected flags the corrected rows. Defaults to None (off).

__post_init__

__post_init__() -> None

Convert a dict mp to MontaninoPunzoConfig, check method and reconstruction.

Raises:

Type Description
ValueError

If method is not in KINEMATICS_METHODS (validate_reconstruction_spec raises for an invalid reconstruction).

get_smooth_window_frames

get_smooth_window_frames(fs: float | None = None) -> int

Return the Savitzky-Golay window in frames for a sampling rate fs.

Parameters:

Name Type Description Default
fs float | None

Sampling rate [Hz]. None or not positive: frame_rate.

None

Returns:

Type Description
int

smooth_window_frames if set, else smooth_window_sec * fs rounded to an odd number of at least 5

int

frames.

LaneChangeConfig dataclass

LaneChangeConfig(enabled: bool = True, lat_speed_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, sewma_alpha: float | None = None, min_displacement_m: float = 1.5, edge_buffer_m: float = 30.0)

Step 5: lane-change detection and lane correction.

Attributes:

Name Type Description
enabled bool

Run the step. Defaults to True.

lat_speed_threshold_mps float

Smoothed lateral speed in m/s above which a lane-change interval starts. Defaults to 0.1 m/s.

median_kernel_sec float

Median-filter width in seconds for the lateral velocity. Defaults to 0.167 s (5 samples at 30 Hz).

sewma_halfwidth_sec float

Half-width of the SEWMA kernel in seconds. Defaults to 0.5 s (15 samples at 30 Hz).

sewma_width_sec float

Width T of the symmetric exponential kernel (Thiemann et al. 2008) in seconds; per vehicle alpha = exp(-dt / T). Defaults to 0.3164 s (the former alpha = 0.9 at 30 Hz).

sewma_alpha float | None

Deprecated per-sample decay factor; if set, it is read at 30 Hz, converted to sewma_width_sec and a DeprecationWarning is emitted. Defaults to None.

min_displacement_m float

Minimum lateral displacement in meters of a lane change. Defaults to 1.5 m.

edge_buffer_m float

Events whose crossing lies within this distance (m) of either end of the road get near_road_end = True (artefacts of the section ends are concentrated there; excluded from behavioral statistics by default). Defaults to 30.0 m.

effective_sewma_width_sec

effective_sewma_width_sec() -> float

Return the SEWMA kernel width [s] to use.

Returns:

Type Description
float

sewma_width_sec, or, if the deprecated sewma_alpha is set, the width -(1/30) / ln(alpha) of

float

that per-sample factor read at 30 Hz (a DeprecationWarning is emitted).

LaneCountZone dataclass

LaneCountZone(lon_start: float, lon_end: float, n_lanes: int, side: str = 'left', taper_m: float = 0.0)

A longitudinal section with a different number of main lanes (lane gain or lane drop).

Outside all zones LanesConfig.n_main_lanes applies. Zones are entered per site, e.g. from aerial images. Lane numbers stay those of the widest cross-section (lane 1 = rightmost main lane present anywhere); a lane that ends or starts keeps its number.

Attributes:

Name Type Description
lon_start float

Start of the zone in pos_lon meters.

lon_end float

End of the zone in pos_lon meters.

n_lanes int

Number of main lanes inside the zone (>= 1); converted to int.

side str

Side on which lanes are added or missing compared with n_main_lanes: "left" (default; the right road edge is unchanged) or "right" (the right road edge moves; the alignment compensates so that lane numbers stay those of the widest cross-section).

taper_m float

Length (m) of the transition before lon_start and after lon_end over which the right-side compensation of the alignment ramps linearly (lane taper). Defaults to 0 (step at the zone limits; the zone must then start where the lane has physically ended).

__post_init__

__post_init__() -> None

Check the zone, convert n_lanes to int.

Raises:

Type Description
ValueError

If lon_end <= lon_start, n_lanes < 1 or side is not "left" / "right".

contains

contains(pos_lon: float | ndarray | Series) -> bool | np.ndarray | pd.Series

Return whether pos_lon lies inside the zone (bounds included).

Parameters:

Name Type Description Default
pos_lon float | ndarray | Series

Longitudinal position(s) [m] (scalar, array or Series).

required

Returns:

Type Description
bool | ndarray | Series

A boolean (scalar, array or Series) of the same shape as pos_lon.

LanesConfig dataclass

LanesConfig(enabled: bool = True, n_main_lanes: int = 3, auxiliary_lane_zones: list[AuxLaneZone] = list(), lon_step_m: float = 50.0, window_size_m: float = 200.0, max_drift_m: float = 2.0, assignment_method: str = 'hmm', hmm: HmmConfig = HmmConfig(), resolve_conflicts: bool = True, keep_unresolved_lane: bool = False, 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, lane_count_zones: list[LaneCountZone] = list())

Step 4: GMM lane tracking.

Attributes:

Name Type Description
enabled bool

Run the step. Defaults to True.

n_main_lanes int

Lanes of the main carriageway (without auxiliary lanes); upper bound for the GMM component count. Defaults to 3.

auxiliary_lane_zones list[AuxLaneZone]

Sections with an auxiliary lane (lane 0), in pos_lon meters. Also used by the alignment. Defaults to no zones.

lon_step_m float

Step between rolling GMM window centers in meters. Defaults to 50.0 m.

window_size_m float

Longitudinal width of each GMM window in meters. Defaults to 200.0 m.

max_drift_m float

Maximum lateral drift in meters when matching lane centers between windows. Defaults to 2.0 m.

assignment_method str

How Step 5 turns the Step 4 labels into lane_fixed: "heuristic" (crossovers of the detected lane changes, piecewise-constant segments, frame-wise conflict re-assignment) or "hmm" (hidden Markov model, processing.lanes.hmm). Defaults to "hmm" since 1.0.

hmm HmmConfig

Parameters of the "hmm" method; a dict is converted. Defaults to HmmConfig().

resolve_conflicts bool

Cross-vehicle conflict resolution of Step 5 (heuristic: frame-wise re-assignment of overlapping vehicles and edge snapping; HMM: feasibility re-decoding). Off only for evaluation (to measure the effect of the resolution). Defaults to True.

keep_unresolved_lane bool

Also output lane_fixed_unresolved, the Step 5 labels before the conflict resolution (evaluation). Defaults to False.

gmm_model str

Step 4 mixture per window: "restricted" (default; Chen & Krumm 2010: n_main_lanes equally spaced components with one shared variance, MAP-EM with priors; plus a free auxiliary-lane component in zones) or "free" (GMM with 1..n_main_lanes free components, BIC selection; the original behavior).

gmm_prior_eta_m float

"restricted": prior mean of the lane spacing (nominal lane width). Defaults to 3.75 m.

gmm_prior_kappa float

"restricted": prior strength of the spacing, dmu | sigma2 ~ N(eta, sigma2 / kappa). Defaults to 100.

gmm_prior_nu float

"restricted": shape parameter of the variance prior sigma2 ~ Inv-Gamma(nu / 2, varsigma2 / 2). Defaults to 3.

gmm_prior_varsigma2_m2 float

"restricted": scale of that prior (m^2; prior mean of sigma2 = varsigma2 / (nu - 2)). Defaults to 0.25 (Chen & Krumm: 4 m^2 for GPS; drone positions have centimetre noise).

lane_count_zones list[LaneCountZone]

Sections with a different number of main lanes (lane gain/drop); dicts are converted. Step 4 uses the local lane count per window (exact for "restricted", upper bound for "free"), lanes that end are removed from tracking at once and not extrapolated, and the HMM allows a lane only where Step 4 has a center for it. Defaults to none (n_main_lanes everywhere).

__post_init__

__post_init__() -> None

Convert dicts to HmmConfig / AuxLaneZone / LaneCountZone and check the options.

Raises:

Type Description
ValueError

If gmm_model or assignment_method is not an allowed value.

TypeError

If an auxiliary-lane zone is neither a dict nor an AuxLaneZone.

max_main_lanes

max_main_lanes() -> int

Return the largest number of main lanes anywhere on the section.

Returns:

Type Description
int

The maximum of n_main_lanes and the n_lanes of all lane-count zones.

MontaninoPunzoConfig dataclass

MontaninoPunzoConfig(rate_hz: float = 10.0, outlier_accel_max_mps2: float = 5.0, outlier_decel_min_mps2: float = -8.0, outlier_reference_points: int = 10, lowpass_cutoff_hz: float = 0.5, lowpass_order: int = 1, filter_zero_phase: bool = True, filter_padlen_sec: float | None = None, edge_method: str = 'pad', window_a_min_mps2: float = -3.0, window_a_max_mps2: float = 2.0, window_lookahead: int = 5, rec_a_min_mps2: float = -5.0, rec_a_max_mps2: float = 3.0, phi_mps2: float = 1.0, max_jerk_inversions: int = 1, jerk_window_sec: float = 1.0, max_window_sec: float = 10.0, h_min_m: float = 1.0, platoon_consistency: bool = False, max_platoon_iterations: int = 10, trim_track_ends_sec: float | None = 2.0, trim_track_ends_fixed_sec: float | None = None)

Parameters of the Montanino & Punzo reconstruction (kinematics.method = "montanino_punzo").

Multistep method of Montanino & Punzo (2013), Transportation Research Record 2390, 99-111; section and equation numbers refer to its extended version, Montanino & Punzo (2015), Transportation Research Part B, 80, 82-106. The negative thresholds are printed without their minus sign in text extractions of the PDF; they are read as -8, -3 and -5 m/s^2.

Attributes:

Name Type Description
rate_hz float

Rate in Hz at which the method runs. The paper's thresholds refer to 10 Hz (dt = 0.1 s); native samples are averaged in 0.1 s bins on the common grid and the result is interpolated back. Defaults to 10.0 Hz.

outlier_accel_max_mps2 float

Step 1 (Sec. 2.1) acceleration threshold in m/s^2. Defaults to 5.0.

outlier_decel_min_mps2 float

Step 1 deceleration threshold in m/s^2. Defaults to -8.0.

outlier_reference_points int

Step 1 spline reference points on each side (1 s at 10 Hz). Defaults to 10.

lowpass_cutoff_hz float

Steps 2/4 (Sec. 2.2/2.4) Butterworth cut-off in Hz. Defaults to 0.5 (paper: 1.0; at 1.0 Hz many 1 s windows of drone data keep more than one jerk sign inversion).

lowpass_order int

Butterworth order. Defaults to 1.

filter_zero_phase bool

Zero-phase filtering (sosfiltfilt; the magnitude response is applied twice) instead of causal filtering (not specified in the paper). Defaults to True.

filter_padlen_sec float | None

Zero-phase filtering only: length of the odd extension at both track ends in seconds (sosfiltfilt(padtype="odd")). None keeps the scipy default of 3 * (2 * n_sections + 1) samples (0.9 s at 10 Hz for order 1), whose start-up transient reaches about 1 m/s2 within the first and last 3-4 s; a longer padding does not reduce it. Defaults to None.

edge_method str

Zero-phase only: "pad" (odd extension, the behavior up to v1.0) or "gust" (Gustafsson's initial conditions; halves the track-end error without cutting data). Defaults to "pad".

window_a_min_mps2 float

Eq. 2 a_min in m/s^2 (also the Step 3 trigger). Defaults to -3.0.

window_a_max_mps2 float

Eq. 2 a_max in m/s^2. Defaults to 2.0.

window_lookahead int

Eq. 2 c, look-ahead samples. Defaults to 5.

rec_a_min_mps2 float

Eq. 3i a_Rec,min in m/s^2. Defaults to -5.0.

rec_a_max_mps2 float

Eq. 3i a_Rec,max in m/s^2. Defaults to 3.0.

phi_mps2 float

Eq. 3g/h relaxation of the acceleration continuity in m/s^2. Defaults to 1.0.

max_jerk_inversions int

Eq. 3j D, maximum jerk sign inversions per window. Defaults to 1.

jerk_window_sec float

Eq. 3j Z in seconds (the paper's "s = 1 s"). Defaults to 1.0 s.

max_window_sec float

Longest reconstruction window in seconds before an outlier is left as it is (not in the paper). Defaults to 10.0 s.

h_min_m float

Eq. 2e/3l minimum spacing to the leader in meters (platoon-consistency post-pass only). Defaults to 1.0 m.

platoon_consistency bool

Run the platoon-consistency post-pass (Eq. 2e/3l) after Step 6. Defaults to False.

max_platoon_iterations int

Iterations within circular leader-follower groups in the post-pass. Defaults to 10.

trim_track_ends_sec float | None

If set, cut each track end whose output acceleration lies outside the Step 1 outlier bounds within this many seconds of the end, up to the deepest such row (Step 1 never moves the end positions; not in the paper). Defaults to 2.0 since 1.0 (None: off).

trim_track_ends_fixed_sec float | None

If set, cut this many seconds from both ends of every track, unconditionally (removes the start-up transient of the filter; tracks shorter than twice the cut are dropped). Defaults to None (off).

__post_init__

__post_init__() -> None

Check edge_method.

Raises:

Type Description
ValueError

If edge_method is not "pad" or "gust".

reconstruction_params

reconstruction_params() -> dict[str, Any]

Return the reconstruction parameters as flat keyword arguments.

reconstruct_vehicle and reconstruct_track take the MontaninoPunzoConfig itself; the flat names are those of their signature before the parameter object (also used by the "mp" parameters of a reconstruction spec).

Returns:

Type Description
dict[str, Any]

Dict of the reconstruction parameters under their flat keyword names (thresholds in

dict[str, Any]

m/s^2, windows in s, h_min in m); rate_hz, platoon_consistency, max_platoon_iterations

dict[str, Any]

and the track-end trimming are not part of it.

PerspectiveConfig dataclass

PerspectiveConfig(correction: str = 'none', 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: list[float] | None = None, view_offsets_m: list[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)

Optional step after projection: lateral perspective correction of tall vehicles (docs/pipeline/02).

The box center of a tall vehicle is displaced laterally by kappa * (pos_lat - d_c) relative to a car (geometric model); the step subtracts this from pos_lat of the vehicles of the class groups in kappa.

Attributes:

Name Type Description
correction str

"none" (default), "lateral_class_offset" (geometric model) or "constant_class_offset" (one median lateral shift per class group, the simpler alternative of the ablation) or "class_offset_empirical" (the constant shift, re-estimated on the corrected data until the residual HGV-minus-car offset is below tol_m; the first estimate is biased towards zero because shifted HGVs are partly assigned to the neighboring lane) or "class_offset_empirical_view" (one iterated empirical offset per camera view, the method of the ANT 2027 paper; views from the HGV band profile or view_boundaries_m) or "joint_gmm" (experimental: joint estimation with the lane geometry; not recommended, it did worse than the empirical offsets on the evaluation data).

kappa dict[str, float] | None

Class group -> kappa [-], e.g. {"hgv": -0.095}. None: estimated by a first diagnostic pass of the pipeline (needs at least two lanes with HGVs). Defaults to None.

d_c_m float | None

Lateral position [m] of the camera's ground point in this direction's projected pos_lat frame. Defaults to None.

offset_m dict[str, float] | None

constant_class_offset: class group -> lateral shift [m] subtracted from pos_lat; None: median class-minus-car offset from a first diagnostic pass. Defaults to None.

min_points int

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

max_iter int

class_offset_empirical: maximum diagnostic passes. Defaults to 4.

tol_m float

class_offset_empirical: stop when the absolute residual offset is below this [m]. Defaults to 0.05.

max_offset_m float

class_offset_empirical: safety limit; an estimate above this [m] or one that has not converged after max_iter passes is not applied (warning). The estimate needs cars and HGVs in the same lane; without them it can diverge. Defaults to 2.5.

joint_offset_scope str

joint_gmm (experimental): the HGV offset is a parameter of the restricted lane mixture, estimated jointly with the lane geometry on a car-only aligned frame; "global" (one offset per direction), "lane" (one per lane, hierarchical prior) or "piecewise" (one per section, smoothness prior). Defaults to "global".

joint_tau_m float

joint_gmm: prior SD of the offset [m], delta ~ N(0, tau^2) (weak; about the largest offsets seen on the recordings of the ANT 2027 paper). Defaults to 1.5.

joint_lane_tau_m float

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

joint_lane_min_sep_m float | None

joint_gmm / "lane": minimum distance [m] of the displaced HGV centers of adjacent lanes (about an HGV width), i.e. delta_j - delta_{j+1} <= dmu - min_sep. Without it, converging lane offsets can describe one HGV lane as two (non-identifiable); None disables. Defaults to 2.5.

joint_section_m float

joint_gmm / "piecewise": section length [m]. Defaults to 300.

joint_smooth_tau_m float

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

joint_hgv_lane_alpha float

joint_gmm: strength of a weak Dirichlet prior on the HGV lane weights favoring the right lanes (alpha from 1 + strength for lane 1 to 1 for the leftmost lane; 0 = uniform). Breaks the delta / delta - dmu ambiguity. Defaults to 0.5.

joint_hgv_exclude_left_lane bool

joint_gmm: no HGVs in the leftmost lane where there are three or more lanes (StVO section 7(3c)); removes the ambiguity "lane j with delta_j" vs "lane j+1 with delta_j - dmu" for the middle lane. Defaults to True.

joint_mode_tie_nats float

joint_gmm: candidate offsets (local maxima of the profile, refined) whose log posterior is within this many nats per HGV point of the best count as equivalent; among them the one with the largest HGV share in the right lane is used. Defaults to 0.05.

joint_profile bool

joint_gmm: evaluate the profile log posterior of the global offset (identifiability diagnosis, stored in the run metadata); its local maxima are the candidate start values. Without it the candidates start from -2, -1, 0, 1 and 2 m. Defaults to True.

joint_profile_range_m float

joint_gmm: the profile log posterior of the global offset is evaluated on [-range, range] [m]. Defaults to 3.0.

joint_profile_step_m float

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

joint_max_outer int

joint_gmm: maximum outer iterations of the offset update. 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 (delta_global, delta_lane or delta_section as in the run metadata); skips the estimation, e.g. to reuse it for a second Step 5 method. With scope "lane" or "piecewise" and only delta_global given, the global stage is taken from it and only the lane / section offsets are estimated. Defaults to None (estimate).

view_detection str

class_offset_empirical_view: how the camera-view boundaries along s are found: "hgv_band" (steps of the label-free HGV band relative to the car lane centers) or "seams" (tracking evidence: track starts/ends and lateral jumps). Defaults to "hgv_band".

view_boundaries_m list[float] | None

fixed view boundaries along s [m] instead of the detection. Defaults to None.

view_offsets_m list[float] | None

with view_boundaries_m: fixed HGV offset per view [m] (estimate of an earlier run, e.g. for a second Step 5 method); skips the estimation. Defaults to None.

view_bin_m float

bin length of the HGV band profile [m]. Defaults to 50.

view_min_segment_m float

minimum view length [m]. Defaults to 150.

view_min_jump_m float

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

view_min_hgv int

minimum HGV samples per view; fewer: the direction-wide estimate is used there. Defaults to 300.

view_min_car int

minimum car samples per view. Defaults to 1000.

view_blend_m float

the offsets are blended linearly over +-view_blend_m around each boundary [m]. Defaults to 25.

view_max_offset_m float

per-view safety limit [m] (larger: the direction-wide estimate). Defaults to 5.0.

view_ambiguous_pp float

readings delta / delta +- dmu closer than this (percentage points of HGV samples within 0.5 m of a car lane center) are decided by the keep-right share and flagged ambiguous. Defaults to 5.

view_robust_reading bool

robust reading of the per-view offset: the lane-1 share ignores samples in the auxiliary-lane zones, and the keep-right check is skipped when the center criterion separates the best reading from the next by at least view_robust_margin_pp. Defaults to True since 1.0 (False: the earlier reading rule without these two changes).

view_robust_margin_pp float

see view_robust_reading [percentage points]. Defaults to 10.

view_max_abs_delta_m float | None

readings with |delta| above this [m] are not considered (e.g. 2 m for top-down drones; keep None for oblique set-ups). Only with view_robust_reading. Defaults to None.

enabled property

enabled: bool

Whether a correction is configured (correction != "none").

__post_init__

__post_init__() -> None

Check the string options against their allowed values.

Raises:

Type Description
ValueError

If joint_offset_scope, view_detection or correction is not an allowed value.

PipelineConfig dataclass

PipelineConfig(projection: ProjectionConfig | dict[str, Any] | None = None, perspective: PerspectiveConfig | dict[str, Any] | None = None, alignment: AlignmentConfig | dict[str, Any] | None = None, stitching: StitchingConfig | dict[str, Any] | None = None, imputation: ImputationConfig | dict[str, Any] | None = None, kinematics: KinematicsConfig | dict[str, Any] | None = None, lanes: LanesConfig | dict[str, Any] | None = None, lane_change: LaneChangeConfig | dict[str, Any] | None = None, resampling: ResamplingConfig | dict[str, Any] | None = None, surroundings: SurroundingsConfig | dict[str, Any] | None = None, round_decimals: int | None = 2, **flat: Any)

Configuration of the trajectory processing pipeline.

One section per step; all defaults are calibrated for 30 Hz drone or overhead-camera data on three-lane motorways. Old flat names are accepted as keywords and attributes (see the module docstring).

Example::

config = PipelineConfig(
    lanes=LanesConfig(n_main_lanes=3, auxiliary_lane_zones=[AuxLaneZone(420.0, 780.0)]),
    resampling=ResamplingConfig(rate_hz=10.0),
)
config.kinematics.poly_order = 2

Attributes:

Name Type Description
projection ProjectionConfig

Step 1. Defaults to ProjectionConfig().

perspective PerspectiveConfig

Optional perspective correction of tall vehicles (after Step 1). Defaults to PerspectiveConfig().

alignment AlignmentConfig

Step 2. Defaults to AlignmentConfig().

stitching StitchingConfig

Optional stitching. Defaults to StitchingConfig().

imputation ImputationConfig

Optional imputation. Defaults to ImputationConfig().

kinematics KinematicsConfig

Step 3. Defaults to KinematicsConfig().

lanes LanesConfig

Step 4. Defaults to LanesConfig().

lane_change LaneChangeConfig

Step 5. Defaults to LaneChangeConfig().

resampling ResamplingConfig

Common output grid. Defaults to ResamplingConfig().

surroundings SurroundingsConfig

Step 6. Defaults to SurroundingsConfig().

round_decimals int | None

Decimals all float64 output columns are rounded to at the end; None keeps full precision. Defaults to 2.

Parameters:

Name Type Description Default
projection ProjectionConfig | dict[str, Any] | None

Section object, dict of its fields, or None for the defaults.

None
perspective PerspectiveConfig | dict[str, Any] | None

Section object, dict of its fields, or None for the defaults.

None
alignment AlignmentConfig | dict[str, Any] | None

Section object, dict of its fields, or None for the defaults.

None
stitching StitchingConfig | dict[str, Any] | None

Section object, dict of its fields, or None for the defaults.

None
imputation ImputationConfig | dict[str, Any] | None

Section object, dict of its fields, or None for the defaults.

None
kinematics KinematicsConfig | dict[str, Any] | None

Section object, dict of its fields, or None for the defaults.

None
lanes LanesConfig | dict[str, Any] | None

Section object, dict of its fields, or None for the defaults.

None
lane_change LaneChangeConfig | dict[str, Any] | None

Section object, dict of its fields, or None for the defaults.

None
resampling ResamplingConfig | dict[str, Any] | None

Section object, dict of its fields, or None for the defaults.

None
surroundings SurroundingsConfig | dict[str, Any] | None

Section object, dict of its fields, or None for the defaults.

None
round_decimals int | None

Decimals of the float64 output columns; None keeps full precision.

2
**flat Any

Old flat names (keys of FLAT_ALIASES), applied after the sections; deprecated names warn.

{}

Raises:

Type Description
TypeError

If a section has the wrong type or a keyword is neither a section nor a flat alias.

__getattr__

__getattr__(name: str) -> Any

Read a flat alias from its section (only called when the normal lookup fails).

Parameters:

Name Type Description Default
name str

Attribute name.

required

Returns:

Type Description
Any

The value of the aliased section field (any type).

Raises:

Type Description
AttributeError

If name is not a flat alias.

__setattr__

__setattr__(name: str, value: Any) -> None

Set an attribute; a flat alias writes the aliased section field (zones are re-validated).

Parameters:

Name Type Description Default
name str

Attribute name (a section, round_decimals or a flat alias).

required
value Any

New value.

required

get_smooth_window_frames

get_smooth_window_frames(fs: float | None = None) -> int

Return the Savitzky-Golay window in frames (pass-through kept for existing callers; see kinematics).

Parameters:

Name Type Description Default
fs float | None

Sampling rate [Hz]. None: kinematics.frame_rate.

None

Returns:

Type Description
int

The window in frames, see KinematicsConfig.get_smooth_window_frames.

to_dict

to_dict() -> dict[str, Any]

Return the configuration as a nested dict of plain values (JSON-compatible).

Returns:

Type Description
dict[str, Any]

Dict {section: {field: value}} for every section of SECTIONS plus "round_decimals".

from_dict classmethod

from_dict(data: Mapping[str, Any]) -> PipelineConfig

Build a configuration from to_dict output.

Unknown top-level keys are ignored with a UserWarning, except comments (keys starting with _), site / notes and dataset (options of a dataset runner, e.g. trajlab.datasets.i24.run_i24motion, that act before the pipeline).

Parameters:

Name Type Description Default
data Mapping[str, Any]

Nested dict as returned by to_dict. Missing sections or fields take their defaults.

required

Returns:

Type Description
PipelineConfig

A new PipelineConfig.

to_json

to_json(path: Path | str | None = None, indent: int = 2) -> str

Serialise the configuration to JSON, optionally writing it to path.

Parameters:

Name Type Description Default
path Path | str | None

File to write (UTF-8, with a final newline). None only returns the string.

None
indent int

JSON indentation.

2

Returns:

Type Description
str

The JSON text (without the final newline).

from_json classmethod

from_json(source: Path | str) -> PipelineConfig

Read a configuration from a JSON file path or a JSON string.

Parameters:

Name Type Description Default
source Path | str

Path to a JSON file, or the JSON text itself (recognized by its leading {).

required

Returns:

Type Description
PipelineConfig

A new PipelineConfig.

ProjectionConfig dataclass

ProjectionConfig(enabled: bool = True, direction_consistency_min: float = 0.9)

Step 1: Frenet projection.

Attributes:

Name Type Description
enabled bool

Run the step. Defaults to True.

direction_consistency_min float

Minimum share (0-1) of moving vehicles that must travel in the same direction along the reference line (Step 1), and in the direction of increasing pos_lon (checked again in Steps 3-6). Defaults to 0.9.

ResamplingConfig dataclass

ResamplingConfig(rate_hz: float | None = 10.0, interpolate_columns: list[str] = list(), nearest_columns: list[str] = list(), drop_columns: list[str] = list())

Resampling onto the common output grid (before Step 6).

Columns the pipeline does not know are interpolated linearly if they are floating point and otherwise take the nearest native sample; the three lists override that per column.

Attributes:

Name Type Description
rate_hz float | None

Rate of the grid t0 + k / rate_hz in Hz; None keeps the native rate. Defaults to 10.0 Hz.

interpolate_columns list[str]

Columns always interpolated linearly in time (must be numeric). Defaults to [].

nearest_columns list[str]

Columns always taken from the nearest native sample. Defaults to [].

drop_columns list[str]

Columns left out of the output. Defaults to [].

StitchingConfig dataclass

StitchingConfig(enabled: bool = False, stages: list[dict[str, Any]] | str | None = None, bridge_joints: bool = False, bridge_trim_sec: float = 0.5)

Optional step: trajectory stitching.

Attributes:

Name Type Description
enabled bool

Run the step. Defaults to False.

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

Parameter dicts for cascaded_stitching (keyword arguments of stitch_trajectories). None uses the built-in 4-stage cascade; "overlap" uses overlap_stages() (multi-camera data with overlapping fields of view, I-24 MOTION). Defaults to None.

bridge_joints bool

Join the fragments of each stitched vehicle with cubic Hermite bridges (bridge_joints: 0.5 s trimmed at both fragment ends, C1 joint). Needed when fragments overlap in time. Defaults to False.

bridge_trim_sec float

Seconds trimmed at both fragment ends of a joint. Defaults to 0.5 s.

SurroundingsConfig dataclass

SurroundingsConfig(enabled: bool = True, default_vehicle_length_m: float = C.DEFAULT_VEHICLE_LENGTH_M, tie_tolerance_m: float = C.SIDE_BY_SIDE_TOLERANCE_M)

Step 6: surrounding vehicles.

Attributes:

Name Type Description
enabled bool

Run the step. Defaults to True.

default_vehicle_length_m float

Vehicle length in meters used when the input has no length column. Defaults to 4.5 m.

tie_tolerance_m float

Longitudinal distance in meters up to which an adjacent-lane vehicle counts as exactly side by side; such a vehicle is a rear neighbor (negative clearance), never a front one. Defaults to 1e-3 m.

list_datasets

list_datasets() -> list[str]

Return the names of the shipped dataset files.

Returns:

Type Description
list[str]

Sorted dataset names (config/datasets/*.yaml without the extension), usable with :func:load_dataset.

load_dataset

load_dataset(name: str) -> dict[str, Any]

Return the content of the dataset file config/datasets/<name>.yaml.

Parameters:

Name Type Description Default
name str

Dataset name (see :func:list_datasets).

required

Returns:

Type Description
dict[str, Any]

The parsed YAML: reader, environment variable(s), conventions, speed limit.

Raises:

Type Description
KeyError

If there is no dataset file name.

speed_limit_mps

speed_limit_mps(name: str) -> float | None

Return the speed limit of a dataset [m/s], converted from its native unit.

Parameters:

Name Type Description Default
name str

Dataset name (see :func:list_datasets).

required

Returns:

Type Description
float | None

The speed limit [m/s], or None if the dataset file has none. The conversion is written as in the paper code

float | None

(130 / 3.6, 65 * 0.44704) so that the values are bit-identical.

list_presets

list_presets() -> list[str]

Return the names of the shipped presets.

Returns:

Type Description
list[str]

Sorted preset names, usable with :func:load_preset.

list_sites

list_sites() -> list[str]

Return the names of the shipped site files.

Returns:

Type Description
list[str]

Sorted site names (config/sites/*.yaml without the extension), usable with :func:load_site.

load_preset

load_preset(name: str, site: Mapping[str, Any] | None = None, **overrides: Any) -> PipelineConfig

Build a configuration from a preset, optionally with site settings and overrides.

Parameters:

Name Type Description Default
name str

Preset name (see :func:list_presets).

required
site Mapping[str, Any] | None

Partial configuration with the site settings, e.g. {"lanes": {"n_main_lanes": 3, "auxiliary_lane_zones": [...]}}; its dict-valued keys not starting with _ are merged into the preset (other keys, e.g. name, are ignored).

None
**overrides Any

Further sections as dicts, merged last (e.g. resampling={"rate_hz": 10.0}).

{}

Returns:

Type Description
PipelineConfig

The configuration.

Raises:

Type Description
KeyError

If there is no preset name; raised by :func:preset_dict.

TypeError

If a section of the preset, site or overrides has an unknown option; raised by the section constructors called in PipelineConfig.from_dict (unknown sections only warn).

ValueError

If an option has a value outside its allowed choices; raised by the __post_init__ checks of the sections.

Examples:

>>> import trajlab
>>> config = trajlab.load_preset("drone_hgv_paper", site={"lanes": {"n_main_lanes": 3}})
>>> config.lanes.assignment_method
'hmm'

load_site

load_site(name: str) -> dict[str, Any]

Return the content of the site file config/sites/<name>.yaml.

Parameters:

Name Type Description Default
name str

Site name (see :func:list_sites).

required

Returns:

Type Description
dict[str, Any]

The parsed YAML (name, dataset, description, lane_source, optionally pipeline and

dict[str, Any]

dataset-specific keys).

Raises:

Type Description
KeyError

If there is no site name.

preset_dict

preset_dict(name: str) -> dict[str, Any]

Return a preset as a partial configuration dict (comments removed).

Parameters:

Name Type Description Default
name str

Preset name (see :func:list_presets).

required

Returns:

Type Description
dict[str, Any]

Partial configuration for PipelineConfig.from_dict: the top-level keys of the preset file without those

dict[str, Any]

starting with _.

Raises:

Type Description
KeyError

If there is no preset name.

site_config_from_attrs

site_config_from_attrs(gdf: DataFrame) -> dict[str, dict[str, Any]]

Return the site settings provided by a reader in gdf.attrs.

Readers of datasets with a known lane layout store n_lanes and, where present, auxiliary_lane_zones in attrs.

Parameters:

Name Type Description Default
gdf DataFrame

Output of a reader.

required

Returns:

Type Description
dict[str, dict[str, Any]]

{"lanes": {"n_main_lanes": int, "auxiliary_lane_zones": [zone dicts]}} with the settings found (empty

dict[str, dict[str, Any]]

dict if the reader provides none).

site_pipeline_config

site_pipeline_config(name: str) -> dict[str, Any]

Return the partial pipeline configuration of a site.

Parameters:

Name Type Description Default
name str

Site name (see :func:list_sites).

required

Returns:

Type Description
dict[str, Any]

A deep copy of the pipeline key of the site file (empty dict if it has none), for

dict[str, Any]

load_preset(..., site=).

lanes_at

lanes_at(pos_lon: float | ndarray, default: int, zones: Sequence[LaneCountZone] | None) -> int | np.ndarray

Return the number of main lanes at pos_lon.

Parameters:

Name Type Description Default
pos_lon float | ndarray

Longitudinal position(s) [m], scalar or array.

required
default int

Number of main lanes outside all zones (LanesConfig.n_main_lanes).

required
zones Sequence[LaneCountZone] | None

Lane-count zones; a later zone wins where zones overlap. None or empty: default everywhere.

required

Returns:

Type Description
int | ndarray

An int for a scalar pos_lon, else an int array of the same shape.

Presets and site files shipped with the package (config/presets/*.yaml, config/sites/*.yaml).

Presets:

  • default: the library defaults.
  • drone_hgv_paper: the exact processing chain of the ANT 2027 paper (drone data with heavy goods vehicles; perspective correction per camera view).
  • drone_topdown: near-nadir drone data (highD, exiD): no perspective correction.
  • roadside_camera: oblique roadside cameras (NGSIM): no perspective correction, auxiliary-lane zones required.
  • ngsim: roadside_camera adapted to NGSIM I-80 and US-101 (no road-edge alignment, no conflict resolution, detector threshold above the lateral-speed noise); with the site files ngsim_i80 and ngsim_us101.
  • i24_motion: I-24 MOTION (oblique pole cameras, provider fragments): no perspective correction, stitching off (stitching.enabled = True runs the overlap cascade), 25 Hz; lanes and zones from the corridor site files.

Site settings (number of main lanes, auxiliary-lane zones) are added per site, e.g. with :func:site_config_from_attrs for readers that provide them, or from a site file.

Site files (YAML) have name, dataset, description, lane_source (pipeline, provider, map, lane_drop), optionally pipeline (a partial configuration merged into a preset, e.g. lanes, zones, the stitching cascade of a site) and dataset-specific keys (lane chains of a map, provider lane roles, ...). Load one with load_site(name); site_pipeline_config(name) returns its partial configuration for load_preset(..., site=).

Dataset files (config/datasets/*.yaml) describe a dataset: reader, environment variable(s), conventions and speed limit (load_dataset, speed_limit_mps).

list_presets

list_presets() -> list[str]

Return the names of the shipped presets.

Returns:

Type Description
list[str]

Sorted preset names, usable with :func:load_preset.

preset_dict

preset_dict(name: str) -> dict[str, Any]

Return a preset as a partial configuration dict (comments removed).

Parameters:

Name Type Description Default
name str

Preset name (see :func:list_presets).

required

Returns:

Type Description
dict[str, Any]

Partial configuration for PipelineConfig.from_dict: the top-level keys of the preset file without those

dict[str, Any]

starting with _.

Raises:

Type Description
KeyError

If there is no preset name.

load_preset

load_preset(name: str, site: Mapping[str, Any] | None = None, **overrides: Any) -> PipelineConfig

Build a configuration from a preset, optionally with site settings and overrides.

Parameters:

Name Type Description Default
name str

Preset name (see :func:list_presets).

required
site Mapping[str, Any] | None

Partial configuration with the site settings, e.g. {"lanes": {"n_main_lanes": 3, "auxiliary_lane_zones": [...]}}; its dict-valued keys not starting with _ are merged into the preset (other keys, e.g. name, are ignored).

None
**overrides Any

Further sections as dicts, merged last (e.g. resampling={"rate_hz": 10.0}).

{}

Returns:

Type Description
PipelineConfig

The configuration.

Raises:

Type Description
KeyError

If there is no preset name; raised by :func:preset_dict.

TypeError

If a section of the preset, site or overrides has an unknown option; raised by the section constructors called in PipelineConfig.from_dict (unknown sections only warn).

ValueError

If an option has a value outside its allowed choices; raised by the __post_init__ checks of the sections.

Examples:

>>> import trajlab
>>> config = trajlab.load_preset("drone_hgv_paper", site={"lanes": {"n_main_lanes": 3}})
>>> config.lanes.assignment_method
'hmm'

site_config_from_attrs

site_config_from_attrs(gdf: DataFrame) -> dict[str, dict[str, Any]]

Return the site settings provided by a reader in gdf.attrs.

Readers of datasets with a known lane layout store n_lanes and, where present, auxiliary_lane_zones in attrs.

Parameters:

Name Type Description Default
gdf DataFrame

Output of a reader.

required

Returns:

Type Description
dict[str, dict[str, Any]]

{"lanes": {"n_main_lanes": int, "auxiliary_lane_zones": [zone dicts]}} with the settings found (empty

dict[str, dict[str, Any]]

dict if the reader provides none).

list_sites

list_sites() -> list[str]

Return the names of the shipped site files.

Returns:

Type Description
list[str]

Sorted site names (config/sites/*.yaml without the extension), usable with :func:load_site.

load_site

load_site(name: str) -> dict[str, Any]

Return the content of the site file config/sites/<name>.yaml.

Parameters:

Name Type Description Default
name str

Site name (see :func:list_sites).

required

Returns:

Type Description
dict[str, Any]

The parsed YAML (name, dataset, description, lane_source, optionally pipeline and

dict[str, Any]

dataset-specific keys).

Raises:

Type Description
KeyError

If there is no site name.

site_pipeline_config

site_pipeline_config(name: str) -> dict[str, Any]

Return the partial pipeline configuration of a site.

Parameters:

Name Type Description Default
name str

Site name (see :func:list_sites).

required

Returns:

Type Description
dict[str, Any]

A deep copy of the pipeline key of the site file (empty dict if it has none), for

dict[str, Any]

load_preset(..., site=).

list_datasets

list_datasets() -> list[str]

Return the names of the shipped dataset files.

Returns:

Type Description
list[str]

Sorted dataset names (config/datasets/*.yaml without the extension), usable with :func:load_dataset.

load_dataset

load_dataset(name: str) -> dict[str, Any]

Return the content of the dataset file config/datasets/<name>.yaml.

Parameters:

Name Type Description Default
name str

Dataset name (see :func:list_datasets).

required

Returns:

Type Description
dict[str, Any]

The parsed YAML: reader, environment variable(s), conventions, speed limit.

Raises:

Type Description
KeyError

If there is no dataset file name.

speed_limit_mps

speed_limit_mps(name: str) -> float | None

Return the speed limit of a dataset [m/s], converted from its native unit.

Parameters:

Name Type Description Default
name str

Dataset name (see :func:list_datasets).

required

Returns:

Type Description
float | None

The speed limit [m/s], or None if the dataset file has none. The conversion is written as in the paper code

float | None

(130 / 3.6, 65 * 0.44704) so that the values are bit-identical.

Pipeline configuration: one small settings group per step.

PipelineConfig bundles one settings object ("section") per pipeline step, e.g. config.kinematics.poly_order or config.lanes.n_main_lanes. Grouping the settings by step makes it visible which parameter belongs to which step and keeps each group short. The section classes are defined one module per step in trajlab.config._sections and re-exported here.

The older flat names (enable_lanes, poly_order, gmm_lon_step, ...) still work, both as constructor keywords (PipelineConfig(poly_order=3)) and as attributes (config.poly_order); they read and write the nested field. Flat names that are used by other projects (EXTERNALLY_USED_FLAT_NAMES) are silent aliases; the others emit a DeprecationWarning. to_dict/from_dict and to_json/from_json save and restore a configuration.

Conventions of the settings: road-related coordinates, pos_lon [m] along the direction of travel and pos_lat [m] to the left of it; lane 0 = auxiliary or ramp lane, 1 = rightmost main lane, -1 = not assigned. The Attributes sections of the section classes are the source of the generated configuration reference (trajlab.config.schema), so every field is documented there with unit and default.

PipelineConfig dataclass

PipelineConfig(projection: ProjectionConfig | dict[str, Any] | None = None, perspective: PerspectiveConfig | dict[str, Any] | None = None, alignment: AlignmentConfig | dict[str, Any] | None = None, stitching: StitchingConfig | dict[str, Any] | None = None, imputation: ImputationConfig | dict[str, Any] | None = None, kinematics: KinematicsConfig | dict[str, Any] | None = None, lanes: LanesConfig | dict[str, Any] | None = None, lane_change: LaneChangeConfig | dict[str, Any] | None = None, resampling: ResamplingConfig | dict[str, Any] | None = None, surroundings: SurroundingsConfig | dict[str, Any] | None = None, round_decimals: int | None = 2, **flat: Any)

Configuration of the trajectory processing pipeline.

One section per step; all defaults are calibrated for 30 Hz drone or overhead-camera data on three-lane motorways. Old flat names are accepted as keywords and attributes (see the module docstring).

Example::

config = PipelineConfig(
    lanes=LanesConfig(n_main_lanes=3, auxiliary_lane_zones=[AuxLaneZone(420.0, 780.0)]),
    resampling=ResamplingConfig(rate_hz=10.0),
)
config.kinematics.poly_order = 2

Attributes:

Name Type Description
projection ProjectionConfig

Step 1. Defaults to ProjectionConfig().

perspective PerspectiveConfig

Optional perspective correction of tall vehicles (after Step 1). Defaults to PerspectiveConfig().

alignment AlignmentConfig

Step 2. Defaults to AlignmentConfig().

stitching StitchingConfig

Optional stitching. Defaults to StitchingConfig().

imputation ImputationConfig

Optional imputation. Defaults to ImputationConfig().

kinematics KinematicsConfig

Step 3. Defaults to KinematicsConfig().

lanes LanesConfig

Step 4. Defaults to LanesConfig().

lane_change LaneChangeConfig

Step 5. Defaults to LaneChangeConfig().

resampling ResamplingConfig

Common output grid. Defaults to ResamplingConfig().

surroundings SurroundingsConfig

Step 6. Defaults to SurroundingsConfig().

round_decimals int | None

Decimals all float64 output columns are rounded to at the end; None keeps full precision. Defaults to 2.

Parameters:

Name Type Description Default
projection ProjectionConfig | dict[str, Any] | None

Section object, dict of its fields, or None for the defaults.

None
perspective PerspectiveConfig | dict[str, Any] | None

Section object, dict of its fields, or None for the defaults.

None
alignment AlignmentConfig | dict[str, Any] | None

Section object, dict of its fields, or None for the defaults.

None
stitching StitchingConfig | dict[str, Any] | None

Section object, dict of its fields, or None for the defaults.

None
imputation ImputationConfig | dict[str, Any] | None

Section object, dict of its fields, or None for the defaults.

None
kinematics KinematicsConfig | dict[str, Any] | None

Section object, dict of its fields, or None for the defaults.

None
lanes LanesConfig | dict[str, Any] | None

Section object, dict of its fields, or None for the defaults.

None
lane_change LaneChangeConfig | dict[str, Any] | None

Section object, dict of its fields, or None for the defaults.

None
resampling ResamplingConfig | dict[str, Any] | None

Section object, dict of its fields, or None for the defaults.

None
surroundings SurroundingsConfig | dict[str, Any] | None

Section object, dict of its fields, or None for the defaults.

None
round_decimals int | None

Decimals of the float64 output columns; None keeps full precision.

2
**flat Any

Old flat names (keys of FLAT_ALIASES), applied after the sections; deprecated names warn.

{}

Raises:

Type Description
TypeError

If a section has the wrong type or a keyword is neither a section nor a flat alias.

__getattr__

__getattr__(name: str) -> Any

Read a flat alias from its section (only called when the normal lookup fails).

Parameters:

Name Type Description Default
name str

Attribute name.

required

Returns:

Type Description
Any

The value of the aliased section field (any type).

Raises:

Type Description
AttributeError

If name is not a flat alias.

__setattr__

__setattr__(name: str, value: Any) -> None

Set an attribute; a flat alias writes the aliased section field (zones are re-validated).

Parameters:

Name Type Description Default
name str

Attribute name (a section, round_decimals or a flat alias).

required
value Any

New value.

required

get_smooth_window_frames

get_smooth_window_frames(fs: float | None = None) -> int

Return the Savitzky-Golay window in frames (pass-through kept for existing callers; see kinematics).

Parameters:

Name Type Description Default
fs float | None

Sampling rate [Hz]. None: kinematics.frame_rate.

None

Returns:

Type Description
int

The window in frames, see KinematicsConfig.get_smooth_window_frames.

to_dict

to_dict() -> dict[str, Any]

Return the configuration as a nested dict of plain values (JSON-compatible).

Returns:

Type Description
dict[str, Any]

Dict {section: {field: value}} for every section of SECTIONS plus "round_decimals".

from_dict classmethod

from_dict(data: Mapping[str, Any]) -> PipelineConfig

Build a configuration from to_dict output.

Unknown top-level keys are ignored with a UserWarning, except comments (keys starting with _), site / notes and dataset (options of a dataset runner, e.g. trajlab.datasets.i24.run_i24motion, that act before the pipeline).

Parameters:

Name Type Description Default
data Mapping[str, Any]

Nested dict as returned by to_dict. Missing sections or fields take their defaults.

required

Returns:

Type Description
PipelineConfig

A new PipelineConfig.

to_json

to_json(path: Path | str | None = None, indent: int = 2) -> str

Serialise the configuration to JSON, optionally writing it to path.

Parameters:

Name Type Description Default
path Path | str | None

File to write (UTF-8, with a final newline). None only returns the string.

None
indent int

JSON indentation.

2

Returns:

Type Description
str

The JSON text (without the final newline).

from_json classmethod

from_json(source: Path | str) -> PipelineConfig

Read a configuration from a JSON file path or a JSON string.

Parameters:

Name Type Description Default
source Path | str

Path to a JSON file, or the JSON text itself (recognized by its leading {).

required

Returns:

Type Description
PipelineConfig

A new PipelineConfig.

Configuration schema: every option with its type, default, allowed values, status and description.

The schema is derived from the configuration dataclasses in :mod:trajlab.config (field, type and default) and the Attributes sections of their docstrings (description), so it cannot drift from the code. :func:validate_config checks a (partial) configuration dict against it before PipelineConfig.from_dict builds the objects; docs/configuration.md is generated from it (python docs/scripts/make_config_docs.py).

Main functions: :func:config_schema and :func:validate_config.

CHOICES module-attribute

CHOICES: dict[tuple[str, str], tuple[str, ...]] = {('perspective', 'correction'): cfg.PERSPECTIVE_CORRECTIONS, ('perspective', 'view_detection'): cfg.VIEW_DETECTIONS, ('perspective', 'joint_offset_scope'): cfg.JOINT_OFFSET_SCOPES, ('kinematics', 'method'): cfg.KINEMATICS_METHODS, ('lanes', 'gmm_model'): cfg.GMM_MODELS, ('lanes', 'assignment_method'): cfg.LANE_ASSIGNMENT_METHODS}

Allowed values of the options that take one of a fixed set of strings.

EXPERIMENTAL module-attribute

EXPERIMENTAL: dict[tuple[str, str], str] = {('perspective', 'joint_offset_scope'): "only used by the experimental 'joint_gmm' correction", ('kinematics.mp', 'platoon_consistency'): 'Montanino & Punzo platoon post-pass, not extended'}

Options that belong to documented, not adopted experiments.

EXPERIMENTAL_VALUES module-attribute

EXPERIMENTAL_VALUES: dict[tuple[str, str], dict[str, str]] = {('perspective', 'correction'): {'lateral_class_offset': 'geometric model of the offset, not used for the papers', 'joint_gmm': 'joint estimation of offset and lanes, not adopted'}, ('perspective', 'view_detection'): {'seams': 'camera views from the seam detector, experimental'}}

Experimental values of otherwise supported options.

OBSOLETE module-attribute

OBSOLETE: dict[tuple[str, str], str] = {('alignment', 'edge_freeze_bins'): 'legacy setting in bins; use alignment.edge_freeze_m', ('lane_change', 'sewma_alpha'): 'deprecated (read at 30 Hz, warns); use lane_change.sewma_width_sec'}

Options kept for backward compatibility only.

config_schema

config_schema() -> dict[str, dict[str, Any]]

Return the configuration schema.

Returns:

Type Description
dict[str, dict[str, Any]]

``{section: {"class", "summary", "options": {name: {"type", "default", "description", "status",

dict[str, dict[str, Any]]

["choices"], ["experimental_values"], ["note"]}}}}`` for every section of

dict[str, dict[str, Any]]

class:~trajlab.config.PipelineConfig; nested sections appear as "kinematics.mp" and

dict[str, dict[str, Any]]

"lanes.hmm", the top-level option round_decimals under "pipeline". status is

dict[str, dict[str, Any]]

"supported", "experimental" or "obsolete".

validate_config

validate_config(data: Mapping[str, Any]) -> list[str]

Check a (partial) configuration dict against the schema.

Unknown sections and options, values outside the allowed choices and the use of experimental or obsolete options are reported. Keys starting with _ (comments) and the top-level keys site, notes and dataset, which are not pipeline sections, are ignored, as in PipelineConfig.from_dict.

Parameters:

Name Type Description Default
data Mapping[str, Any]

Configuration as accepted by PipelineConfig.from_dict (e.g. a preset).

required

Returns:

Type Description
list[str]

Problems as strings; "error: ..." entries make PipelineConfig.from_dict fail or change the meaning,

list[str]

"warning: ..." entries flag experimental or obsolete options. Empty if the dict is valid.