Skip to content

Method

trajlab turns raw vehicle trajectories from drone or roadside-camera recordings into road-relative, kinematically consistent trajectories with lane labels, lane-change events, and the surrounding vehicles of every vehicle. This page describes each processing step and why it is done the way it is. Column definitions are in output_format.md, known weaknesses in limitations.md, dataset readers in readers.md.

The design choices behind each step, with their evidence and sources, are in the step documents (docs/pipeline/, starting from the pipeline overview).

Overview

The pipeline runs once per travel direction. The steps run in this order (trajlab.PIPELINE_STEPS):

Order Step name Paper term Runs by default
1 projection reference-line projection (s, d) yes
– perspective perspective correction of tall vehicles no (perspective.correction = "none")
2 alignment road-edge alignment yes
– stitching trajectory stitching no
– imputation re-gridding of gaps no
3 kinematics kinematic reconstruction (Montanino & Punzo) yes
4 lanes lane geometry (point-wise mixture) yes
5 lane_correction lane-change detection and consistent lane assignment yes
– resampling common output grid yes (10 Hz)
6 surroundings leaders, followers, and neighbors yes
– platoon_consistency Montanino & Punzo platoon post-pass no
– lane_change_events event table with neighbor attributes yes

Steps 1–5 run at the native frame rate of each vehicle; the output is on one common time grid. A step whose output columns already exist is skipped unless cache="refresh", so a road-aligned dataset that already has pos_lon and pos_lat skips the projection.

Each section below names the source of a method. Thresholds and parameters without a source are choices made for this library; the "Design choices" section of the step document explains each of them, with the evidence. The perspective correction per camera view, the HMM lane assignment with its conflict resolution and the in-lane overtaking measure were developed for the paper of Baumann et al. (submitted to ANT 2027).

import trajlab

east, west = trajlab.estimate_ref_lines(raw)
config = trajlab.PipelineConfig.from_dict({"lanes": {"n_main_lanes": 3}})
result = trajlab.run_pipeline_detailed(raw[raw["orientation"] > 0], east, config)
out, events = result.tracks, result.events

Library defaults and the ANT 2027 paper preset

Since 1.0 the library defaults include the evaluated parts of the paper chain that do not need vehicle classes: HMM lane assignment with damped conflict resolution, the robust reading of the per-view offset (used only when the per-view correction is switched on) and the cut of uncorrectable track ends. The perspective correction itself, stitching and the paper's exclusions stay opt-in. The configuration used for the paper of Baumann et al. (submitted to ANT 2027) is shipped as a preset (trajlab.load_preset("drone_hgv_paper"), file trajlab/config/presets/drone_hgv_paper.yaml; the preset ant2027 is the same chain with every option set explicitly, so that it does not change with the library defaults). It holds no site settings; add the number of lanes and the auxiliary-lane zones of your site.

Setting Library default Paper preset
perspective.correction "none" "class_offset_empirical_view" (offset per camera view)
perspective.view_robust_reading True (since 1.0) True (no view_max_abs_delta_m limit)
stitching.enabled False True, with the five-stage cascade of the paper in stitching.stages
kinematics.method "montanino_punzo" "montanino_punzo"
kinematics.mp.lowpass_cutoff_hz 0.5 0.5
kinematics.mp.trim_track_ends_sec 2.0 (since 1.0) 2.0
lanes.gmm_model "restricted" "restricted"
lanes.assignment_method "hmm" (since 1.0) "hmm"
lanes.hmm.conflict_damping True (since 1.0) True (t_min 1 s, t_hold 2 s)
lanes.hmm.min_aux_zone_m 50 (since 1.0) 50
resampling.rate_hz 10 None (no resampling)

Notes on the preset:

  • The paper evaluation ran on 10 Hz input (every third frame of the 30 Hz recordings on one global grid).
  • The preset contains the re-parametrized stitching cascade of the paper (see Stitching); without stitching.stages the built-in cascade is used.
  • The lane labels behind the paper's Tables 2 and 3 come from an evaluation chain with Savitzky–Golay kinematics (the labels do not depend on the kinematics method); the preset is the chain of the processed data (Figure 2). See applications/ant2027/README.md.
  • Paper-specific exclusions (one distorted zone, vehicles on the hard shoulder; applications/ant2027/inputs/paper_exclusions.json) are applied in the evaluation, not in the pipeline.
import trajlab

site = {
    "lanes": {
        "n_main_lanes": 6,
        "auxiliary_lane_zones": [  # e.g. NGSIM I-80 (see readers.md)
            {"lon_start": 82.0, "lon_end": 203.0, "kind": "on_ramp"}
        ],
    }
}
config = trajlab.load_preset("drone_hgv_paper", site=site)

Reference line and projection (Step 1)

Purpose. Car-following and lane-change analyses need road-relative coordinates: the distance s along the road (pos_lon) and the signed lateral offset d from a reference line (pos_lat).

Reference line. The line is supplied by the user (for example from OpenStreetMap) or derived from the data with estimate_ref_lines, per travel direction:

  1. The road axis is the first principal component of the positions, oriented so that the vehicles move along it.
  2. The 30 trajectories with the largest extent along the axis form an ensemble. In 5 m bins the median lateral position is taken, which cancels individual lane changes and steering.
  3. A cubic smoothing B-spline goes through the bin medians with an RMS tolerance of 0.75 m (rms_tolerance_m). Smaller tolerances let the line follow the scatter of the medians and create kinks, and every projected trajectory jumps laterally at a kink; larger tolerances cut curves. The remaining slow deviation from the road is removed by the alignment.

Roads that curve by more than about 60–70° within the recording area are not monotonic along one axis; a warning is issued and a user-supplied line is needed.

Projection. For a point P and the reference line R:

$$s = \mathrm{line_locate_point}(R, P), \qquad d = \operatorname{sign}\big((\vec T_R \times \vec V_P)_z\big)\,\lVert P - R(s) \rVert,$$

with $\vec T_R$ the tangent of R at s and $\vec V_P$ the vector from the foot point to P.

Direction normalization. The net displacement of every moving vehicle along s decides its travel direction. If fewer than 90 % of the vehicles agree (projection.direction_consistency_min), the step stops and asks for the input to be split by direction. If the vehicles travel against the digitizing direction of the line, s ← L − s and d ← −d. As a result, s always increases in the direction of travel and d is always positive to the left. Steps 3–6 check this again.

End clamping. Points that project within 1 m of either end of the line are dropped; projections beyond the line ends would pile up at the end points.

Sources. The construction of the line, the 0.75 m tolerance, the 90 % direction share and the 1 m end clamp are chosen for this library; see 01.

Perspective correction of tall vehicles (optional)

Purpose. Drone and camera detections give the center of the top of a bounding box. For tall vehicles (heavy goods vehicles, buses) the roof is displaced away from the camera's ground point (relief displacement), so their lateral position is biased relative to cars, on the paper's data by up to several meters. Without a correction, heavy vehicles appear to overlap cars in the neighboring lane, are assigned to the wrong lane, and are "overtaken" inside their own lane. In the paper this was the largest single error source on data with many heavy vehicles: without the correction, in-lane overtakings rose from 0.19 to 3.7 per 100 vehicle-km for the temporally consistent assignment and from 0.26 to 5.3 for the point-wise mixture.

The correction runs right after the projection and before the alignment, so that displaced heavy vehicles do not pull the road-edge profile. It changes pos_lat of the heavy-vehicle rows in place and needs a vehicle class per row. Heavy vehicles are the class labels truck, heavy vehicle, bus, trailer, hgv and similar (case-insensitive); everything except motorcycles counts as a car for the comparison. The applied correction is stored in the run metadata (perspective).

All variants are estimated per recording and direction. The sign and size of the offset differ between camera set-ups and campaigns, so an estimate must not be transferred.

Offset per camera view ("class_offset_empirical_view", method of the ANT 2027 paper)

Drone recordings stitched from several camera views carry a different relief displacement in every view; on one of the paper's campaigns the heavy-vehicle offset steps by up to 3.5 m at the camera seams. One offset per direction cannot follow this. The per-view method:

  1. View boundaries along s (view_detection = "hgv_band", label-free): in 50 m bins, the car lane centers come from a restricted mixture of the cars (see Lane geometry), and the main peak of the heavy-vehicle positions is taken relative to the lane-1 center. The peak is unwrapped along s and split into constant pieces by binary segmentation (at least 150 m per view, at least 0.6 m step between views). Tracking evidence (track starts/ends, lateral jumps; view_detection = "seams") is an alternative but found only about half of the view boundaries on the paper's data.
  2. Direction-wide estimate (also the fallback): in a diagnostic pass (point-wise lanes, Savitzky-Golay kinematics), the residual r is the median over (lane, 50 m bin) of median d_heavy − median d_car. The shift is accumulated, δ ← δ + r, and re-estimated on the corrected data until |r| < 0.05 m or 4 passes. A single estimate is biased toward zero because shifted heavy vehicles are partly assigned to the neighboring lane; the iteration removes this bias.
  3. Per-view iteration: each view starts from its band offset and is iterated in the same way.
  4. Reading. The offset is only determined up to one lane width: heavy vehicles in lane j with offset δ fit a homogeneous road as well as heavy vehicles in lane j+1 with δ − Δμ. For each view the candidates δ and δ ± Δμ are compared by (a) the share of heavy-vehicle samples within 0.5 m of a car lane center and (b) the keep-right share (heavy vehicles in lane 1). Candidates that put fewer than half of the heavy vehicles in lane 1 are dropped while another one remains; among candidates within 5 percentage points of the best center share (view_ambiguous_pp), the one with the largest lane-1 share wins and the view is flagged ambiguous.
  5. Robust reading (view_robust_reading = True, default and paper preset): samples in auxiliary-lane zones do not count for the lane-1 share, and the keep-right check is skipped when the center criterion separates the best reading from the next by at least 10 percentage points (view_robust_margin_pp). For top-down drone data, view_max_abs_delta_m = 2 additionally drops readings with a larger offset; keep it unset for oblique set-ups and for data with large real offsets.
  6. Fallback and limits: a view with fewer than 300 heavy-vehicle or 1000 car samples uses the direction-wide estimate; so does a view whose offset exceeds 5 m (view_max_offset_m).
  7. Application: d ← d − δ_view for heavy-vehicle rows, blended linearly over ±25 m around each view boundary.

On the paper's data the per-view offset raised the share of heavy-vehicle positions near a car lane center on the campaign with many heavy vehicles from 39 % (constant offset) to 69 % (cars: 82 %). All 65 views of the 44 directions converged to |r| < 0.05 m within the pass limit.

The view boundaries and offsets of an earlier run can be reused with view_boundaries_m and view_offsets_m (no estimation).

The method and its thresholds (50 m bins, 150 m and 0.6 m for the views, 300 and 1000 samples, 5 m, ±25 m, 5 and 10 percentage points) are chosen for this library and the ANT 2027 paper; see 02.

Other variants

perspective.correction Method Status
"none" no correction library default
"constant_class_offset" one median shift per class group from a single diagnostic pass, or fixed via offset_m ablation baseline
"class_offset_empirical" the iterated constant shift per direction (step 2 above); not applied if |δ| > 2.5 m (max_offset_m) or not converged comparison (constant offset) in the paper
"lateral_class_offset" geometric relief-displacement model $\Delta d = \kappa\,(d - d_c)$ with $\kappa$ = effective height / flight height, estimated by weighted least squares from per-lane class offsets (needs at least two lanes with heavy vehicles); inverse correction $d = d_{obs} - \frac{\kappa}{1+\kappa}(d_{obs} - d_c)$; longitudinal component not corrected not used in the paper
"joint_gmm" heavy-vehicle offset as a parameter of the restricted lane mixture (global, per lane, or per section) experimental; not recommended (more in-lane overtakings than the empirical estimate)

Sources on the position errors of drone detections, on which the relief-displacement model builds: Sánchez Morales et al. (2020), Páncsics et al. (2024), Fonod et al. (2025).

Road-edge alignment (Step 2)

Purpose. A data-derived reference line follows the road only up to its tolerance, and roads curve. After projection a vehicle driving straight in its lane still shows a slowly varying d. The alignment subtracts the right road edge, estimated from the data, so that each lane has an approximately constant lateral position along s.

Method.

  1. Per 10 m bin along s, the 5 % quantile of d defines the right road edge: robust to single points beyond the edge, yet close to it.
  2. Inside auxiliary-lane zones the lowest band is the auxiliary lane, not the edge of the main carriageway. Bins that overlap a zone, widened by one bin on each side, are replaced by linear interpolation (without the extra bin, auxiliary-lane points that spill into the bin before the zone tilt the frame across the zone).
  3. Where lanes are added or missing on the right (LaneCountZone(side="right")), the profile is referred back to the cross-section of n_main_lanes, $y(s) \leftarrow y(s) - w(s)\,(n_{main} - n_{zone}) \cdot 3.75$ m, with w ramping over taper_m; otherwise every lane would be renumbered there.
  4. Optional edge freeze (edge_freeze_m, default 0 m; a frozen profile keeps the deviation of the reference line at the road ends and creates end-of-road lane changes).
  5. Gaussian smoothing with σ = 30 m.
  6. d ← d − y(s) + 2.0 m, i.e. the edge profile is moved to the center of lane 1.

alignment.profile_classes (for example ["Car"]) builds the profile from selected classes only; it is then applied to all rows. The alignment removes any lateral shift common to all vehicles, including the shift of all vehicles at a camera seam.

Sources. The alignment and its parameters (5 % quantile, 10 m bins, σ = 30 m, 2.0 m) are chosen for this library; see 03.

Stitching (optional)

Purpose. Camera-based tracking fragments trajectories: a vehicle disappears behind a bridge or a truck, or at a camera hand-over, and reappears under a new ID. Stitching links the fragments of one vehicle. It runs on projected, perspective-corrected, and aligned positions. All rows are kept; only the IDs of linked fragments are replaced by one common ID.

One pass (stitch_trajectories), inspired by the fragment association of Wang et al. (2024): a one-to-one bipartite matching of fragment tails to fragment heads.

  1. State of a tail or head: time, s, d, class, length, and the velocities $v_s, v_d$ (slope over the last/first 5 samples, or a least-squares slope over a time window, state_window_sec).
  2. Prediction at gap $\Delta t$: $\hat s = s_{tail} + v_s\,\Delta t$, $\hat d = d_{tail} + v_d\,\Delta t$.
  3. Gates (a pair failing one is forbidden):
  4. $0 < \Delta t \le \Delta t_{max}$;
  5. kinematic envelope $\hat s - \tfrac12 a_{dec}\Delta t^2 - e_x \le s_{head} \le \hat s + \tfrac12 a_{acc}\Delta t^2 + e_x$;
  6. forward motion $s_{head} \ge s_{tail} - e_x$;
  7. lateral: $|\hat d - d_{head}| < e_y + v_{y,max}\Delta t$, $|d_{head} - d_{tail}| < e_y + 0.2\,|s_{head} - s_{tail}|$ and $< d_{abs,max}$;
  8. same class, $|L_{head} - L_{tail}| < e_L$;
  9. optional speed gate $|v_{head} - v_{tail}| \le \Delta v_{max} + g\,\Delta t$.
  10. Cost $C = \sqrt{\Delta s_{pred}^2 + (w_y \Delta d_{pred})^2 + (w_L \Delta L_n)^2 + (w_v \Delta v_n)^2}$.
  11. Assignment with the Hungarian algorithm; accepted pairs are edges of a graph whose connected components (chains A→B→C) get one ID.

Cascade (cascaded_stitching). Passes run with growing maximum gap. The cascade is greedy by gap length: a stage only sees candidates within its own window and, without a speed gate and with a wide envelope, links a wrong neighbor when the true continuation lies just beyond it. The built-in cascade has four stages (maximum gap 2, 5, 8, 11 s). The paper cascade keeps stages 1–2, tightens the envelope and adds a speed gate (3 m/s + 0.25 m/s² × gap, 1 s velocity window) in stages 3–4, and adds a hand-over stage with a maximum gap of 16 s:

Stage Δt_max [s] e_x [m] a_acc / a_dec [m/s²] e_y [m] v_y,max [m/s] d_abs,max [m] w_y speed gate
1 2 1.0 2.0 / 6.0 0.5 0.2 5.0 10 no
2 5 2.0 2.0 / 3.5 1.0 0.5 5.0 6 no
3 8 3.0 0.75 / 1.0 (built-in 2.0 / 2.5) 1.5 1.2 5.0 4 yes
4 11 3.0 0.75 / 1.0 (built-in 1.0 / 1.5) 1.5 1.2 2.5 4 yes
5 (hand-over) 16 3.0 0.5 / 1.0 0.75 0.2 1.5 4 (+ w_v = 1) yes

Stages 1–2 keep no speed gate: in congestion the speed at fragment ends varies by more than 3 m/s, and at short gaps the envelope is tight enough.

Evaluation without ground truth. In each hand-over zone, 30 % of the tracks crossing the zone are cut at real fragment end/start positions; the cut tracks stay in the data with all real fragments as competitors. Parameters were selected on seeds 1–3 (rule fixed beforehand: precision ≥ 0.95 in every zone, then the highest recall) and reported on independent seeds 11–15: precision 0.995, recall 0.949 (built-in cascade 0.983 / 0.945).

Imputation (imputation.enabled, optional) re-grids each vehicle on its own grid (default 30 Hz), interpolates positions with PCHIP, fills gaps up to max_gap_sec (3 s), and marks filled rows is_imputed. It drops speed and acceleration; Step 3 recomputes them.

Sources. The gates, the cost and the stage parameters are chosen for this library; the paper cascade was selected on artificial gaps as described above. The imputation (PCHIP, 3 s) is chosen for this library. See 04.

Kinematic reconstruction (Step 3)

Purpose. Positions from image-based tracking contain noise; differentiating them amplifies it (noise in speed grows with the frame rate, in acceleration with its square). Step 3 reconstructs smooth, internally consistent longitudinal kinematics (pos_lon, speed, acceleration) and smooths pos_lat.

Before reconstruction, a track that moves backward by more than 15 m (max_reversal_m; an identity swap of the tracker; chosen for this library) is discarded.

Montanino & Punzo (default, kinematics.method = "montanino_punzo")

The multistep method of Montanino & Punzo (2013), with Step 3 in the extended form of Montanino & Punzo (2015, Sec. 2):

  • Rate. The method's thresholds refer to 10 Hz. Native positions are put on a 0.1 s grid anchored at whole multiples of 0.1 s (identical to the output grid). With more than one native sample per grid step they are averaged per bin; with at most one sample per step (native rate ≤ 10 Hz) they are interpolated linearly onto the grid points (binning a slightly drifting 9.99 Hz clock had dropped up to 60 s at track ends, which were then extrapolated).
  • Step 1 (outliers). Where $a > +5$ or $a < -8$ m/s², positions are replaced by a natural cubic spline through 10 points on each side.
  • Step 2 (noise). First-order Butterworth low-pass on the speed, zero-phase, cut-off 0.5 Hz (the original method uses 1 Hz; 0.5 Hz more than halves the share of 1 s windows with more than one jerk sign inversion without changing the internal consistency, in the sense of Punzo et al. 2011). The traveled distance is restored afterwards.
  • Step 3 (constrained local reconstruction). In windows where $a \notin [-3, 2]$ m/s², with the window end from the compatibility cone (look-ahead 5 samples), the speed is replaced by a fifth-degree polynomial that minimizes $\max|a|$ subject to: $v \ge 0$, continuity at both ends (φ = 1 m/s²), $a \in [-5, 3]$ m/s², at most one jerk sign inversion per 1 s, preserved distance, and optionally the spacing to the leader. Infeasible windows are enlarged up to 10 s; a window that stays infeasible is left as it is. Infeasible windows are recognized by a necessary condition on the end accelerations and a linear-programming feasibility check before the nonlinear solver runs (results unchanged, run time linear in samples and windows).
  • Step 4. Step 2's filter again.
  • Output. At a 10 Hz output grid, pos_lon, speed, and acceleration come directly from the 10 Hz reconstruction; values at the native rate (for Steps 4–5) are interpolated with PCHIP. mp_reconstructed marks samples changed by Steps 1 or 3.
  • Track ends (mp.trim_track_ends_sec, default and paper preset 2 s). Step 1 never moves the first or last position (the spline needs reference points on both sides), so outliers can remain at track ends. With this option, each track end is cut up to the deepest row within the given depth whose acceleration lies outside [−8, 5] m/s². The cut happens before lanes and neighbors are computed; the counts are in the run metadata (mp_counters.trim_track_ends).
  • Tracks too short for the method fall back to Savitzky-Golay.

Savitzky-Golay (kinematics.method = "savgol")

A generic smoothing choice, not part of Montanino & Punzo: a local polynomial of order 2 over 4 s, with constant-velocity padding at both ends (order, window and padding chosen for this library; see 05). Position, speed, and acceleration are the 0th, 1st, and 2nd analytical derivatives. It is faster and is used in the diagnostic passes of the perspective correction.

The lateral position pos_lat is always smoothed with Savitzky-Golay (order 2, 4 s window unless lateral_smooth_window_sec is set).

Platoon consistency (optional post-pass)

Leaders are known only after Step 6, so the spacing constraint of Montanino & Punzo runs as a post-pass on the output grid (kinematics.mp.platoon_consistency): the leader–follower tree is built from id_front, and layer by layer vehicles whose clearance falls below h_min_m get Step 3 again with the spacing constraint. Step 6 is then recomputed. As in the original method, windows are triggered by unphysical accelerations only, so a spacing violation without one is reported but not fixed.

Lane geometry (Step 4)

Purpose. Lane centers are estimated from the data instead of being drawn by hand. In rolling windows along the road a Gaussian mixture is fitted to the lateral positions of cars, and the window centers are tracked along the road. Every point gets the nearest lane; this is the point-wise assignment.

Windows. 200 m windows every 50 m. The fit uses the cars (all vehicles if a window has fewer than 30 car points). Inside auxiliary-lane zones, points right of lane 1 (its center minus half the local lane width) are left out of the fit and labeled 0.

Restricted mixture (default, lanes.gmm_model = "restricted"; Chen & Krumm 2010). Exactly k components, k = number of main lanes from the site configuration and lane-count zones (no model selection), with equally spaced means and one shared variance:

$$p(d) = \sum_{j=1}^{k} w_j\,\phi!\left(d \mid \mu + (j-1)\Delta\mu,\ \sigma^2\right).$$

MAP estimation by EM as in Chen & Krumm's Appendix A, with priors $w_j$, $\mu$ uniform, $\sigma^2 \sim \text{Inv-Gamma}(\nu/2, \varsigma^2/2)$ and $\Delta\mu \mid \sigma^2 \sim N(\eta, \sigma^2/\kappa)$: η = 3.75 m (nominal lane width), κ = 100, ν = 3 as in the paper, and ς² = 0.25 m² instead of their 4 m² (their prior reflects GPS noise; drone positions have centimeter noise). EM is started both from the previous window and from a grid search over μ with Δμ = η; the solution with the higher log posterior is kept (a warm start alone locked into a wrong spacing after a short lateral shift at a camera hand-over).

Compared with a free mixture whose component count is chosen by BIC (gmm_model = "free"), the restricted model cannot lose a sparsely used lane: on the paper's data the share of windows with a lost lane fell from 3.1 % to 0.06 %. It presupposes the perspective correction on data with many heavy vehicles.

Auxiliary-lane zones (addition, not in Chen & Krumm). In windows touching an AuxLaneZone(lon_start, lon_end, kind), one extra component right of lane 1 with its own mean and variance, outside the spacing constraint (auxiliary lanes are often narrower). Auxiliary-lane zones are part of the site configuration; they are not detected.

Lane gain and drop (LaneCountZone(lon_start, lon_end, n_lanes, side, taper_m)). Each window uses the main-lane count at its center. Lanes that end are removed from tracking at once and not extrapolated. Lane numbers stay those of the widest cross-section.

Tracking and labeling. Window centers are matched to the tracked lanes with the Hungarian algorithm (maximum drift 2 m), updated as $y \leftarrow 0.7\,y + 0.3\,m$; unmatched lanes follow the mean shift of the matched ones and are dropped after 10 missed windows. Every point gets the nearest active center of its 50 m bin; lanes are renumbered by lateral order (1 = rightmost main lane).

Sources. The mixture follows Chen & Krumm (2010). The windows (200 m every 50 m), the 30 car points, the tracking (2 m drift, weights 0.7 / 0.3, 10 missed windows) and ς² = 0.25 m² are chosen for this library; see 06.

Lane-change detection (Step 5)

Purpose. Lateral maneuvers are detected from the lateral velocity of each vehicle. The detector intervals feed both lane-assignment methods, which decide whether an interval is a lane change (the vehicle ends in another lane) or a lateral excursion (it returns, or moves within its lane).

  1. Lateral velocity $\dot d$ by numerical differentiation, median-filtered over 0.167 s.
  2. Smoothing with a symmetric exponential kernel (SEWMA; Thiemann, Treiber & Kesting 2008): $$\mathrm{SEWMA}i = \frac{\sum{j=-w}^{w} \alpha^{|j|}\,\dot d_{i+j}}{\sum_{j=-w}^{w} \alpha^{|j|}},\qquad \alpha = e^{-\Delta t / T},$$ with width $T$ = 0.3164 s and half-width 0.5 s, both in seconds, so the smoothing is the same at 10, 25, and 30 Hz.
  3. An interval is where $|\mathrm{SEWMA}| > 0.1$ m/s with a total lateral displacement above 1.5 m; start and end at the threshold crossings (scheme of Hofinger & Fellendorf 2023). Increasing d is a movement to the left.

Slow drifts below the threshold are not detected; the HMM can still switch lanes there.

Sources. The kernel is that of Thiemann, Treiber & Kesting (2008), the interval scheme that of Hofinger & Fellendorf (2023). The values 0.167 s, 0.5 s, 0.1 m/s and 1.5 m are chosen for this library; see 07.

Consistent lane assignment (Step 5)

The point-wise labels of Step 4 flicker near lane boundaries and can place two vehicles in one lane at one time. Step 5 turns them into one consistent lane sequence per vehicle (lane_fixed).

Heuristic (lanes.assignment_method = "heuristic")

  1. A detector interval is a lane change if the lateral position crosses the boundary between the start-lane center and the next center in the direction of movement and the lane before the interval differs from the one after it; otherwise it is a lateral excursion, which does not change the lane.
  2. The crossover time is when the vehicle crosses the midpoint between the source and target lane centers.
  3. Between crossovers, the lane is the one whose center is nearest to the segment's mean d.
  4. Conflict resolution: two vehicles overlap in one lane if $|s_a - s_b| < (L_a + L_b)/2 + 1$ m at the same time; they are reassigned to adjacent distinct lanes minimizing the combined offset to the lane centers (lane 0 only inside auxiliary-lane zones). Changed rows are flagged lane_conflict_resolved.

Each segment is decided on its own; there is no probabilistic smoothing across segments. The heuristic and its 1 m conflict margin are chosen for this library; see 08.

Hidden Markov model (library default and paper method, lanes.assignment_method = "hmm")

The HMM treats the lane as a hidden state and decodes the whole track at once. This is the temporally consistent assignment of Baumann et al. (submitted to ANT 2027). Viterbi decoding and the forward–backward algorithm are the standard HMM algorithms (Rabiner 1989); the model, its rates, floors and add-on rules are chosen for this library (see 09).

  • States: lanes 1…n, plus lane 0 within auxiliary-lane zones ± 10 m (zone_margin_m). With lane-count zones a lane is a valid state only within its observed range.
  • Emission: $p(d \mid k) = (1-\varepsilon)\,N(d; c_k(s), \sigma_k^2) + \varepsilon\,\max_j N(d; c_j(s), \sigma_j^2)$, ε = 10⁻³, $\sigma_k = \max(0.4\ \text{m},\ 1.4826\,\mathrm{MAD})$ of the residuals of lane k outside detector intervals. The relative floor (instead of a uniform one) keeps "the closest lane wins" between two lane centers, where both Gaussians are tiny.
  • Transitions (rates per second, so independent of the sampling rate): $p_{k \to k\pm1} = 1 - e^{-\lambda\Delta t}$ with λ = 2 /s toward the detected side inside a detector interval and λ = 10⁻³ /s otherwise; no jumps over more than one lane. The results are insensitive to these rates over a wide range.
  • Decoding: Viterbi for the lane sequence; forward–backward for the posterior, giving lane_confidence (posterior of the decoded lane) and lane_posterior_margin (lead over the second most probable lane).
  • Geometry: initial lane centers $c_k(s)$ are medians of the Step 4 labels per 10 m bin outside detector intervals, smoothed with σ = 30 m (more robust than the tracked window centers, which collapse locally in sparse traffic); then up to 3 EM rounds alternate decoding and re-estimating centers and spreads.
  • Events: every change of the decoded lane is a lane change. Within one maneuver (detector intervals less than 1 s apart), a return A→B→A with at most 2 s in B is collapsed to A.
  • Feasibility across vehicles: a conflict is the same lane at the same time with $|s_1 - s_2| < (L_1 + L_2)/2 + 1$ m. The vehicle with the lower mean confidence on the conflict frames gets a penalty (log 10⁻⁴) on the occupied lane there and is re-decoded (up to 10 rounds). Long, confident overlaps of laterally coincident tracks are flagged suspected_duplicate_track; remaining conflicts lane_conflict_unresolved.

Damped conflict resolution (default and paper preset). Undamped re-decoding oscillates in dense traffic with overlapping positions: vehicles are re-assigned back and forth. With lanes.hmm.conflict_damping = True:

  • only conflict episodes of a pair lasting at least t_min = 1 s are resolved;
  • the penalty window of the re-assigned vehicle covers at least t_hold = 2 s, but never extends into its own detected lane changes;
  • every conflict episode of a pair is resolved at most once;
  • shorter conflicts stay and are flagged lane_conflict_unresolved.

The values of t_min and t_hold were set beforehand, not tuned on ground truth. In addition, lanes.hmm.min_aux_zone_m = 50 makes the HMM ignore auxiliary-lane zones shorter than 50 m: the auxiliary-lane center is estimated in 50 m bins and cannot be estimated in a shorter zone, so the auxiliary state would pull lane-1 vehicles in and release them at the zone edges. Such zones stay in the site configuration for the alignment and the heuristic.

Against lane ground truth without perspective correction, the HMM with damped conflict resolution reached a sample accuracy of 99.24 % (exiD, Moers et al. 2022, 13 directions; point-wise 99.35 %) and 99.18 % (highD, Krajewski et al. 2018, 20 recordings; point-wise 99.23 %), with lane-change F1 0.974 and 0.961 (point-wise 0.973 and 0.944) and almost no flicker. On the paper's recordings with the per-view correction it produced 0.19 in-lane overtakings per 100 vehicle-km (point-wise 0.26) and 0.075 unexplained leader changes per vehicle-km (point-wise 0.089).

Output grid and surroundings (Step 6)

Output grid. Before neighbors are computed, all vehicles are resampled to one grid $t_0 + k/\text{rate}$ (default 10 Hz), with $t_0$ the global minimum time floored to a whole grid step counted from the Unix epoch. Each vehicle keeps only grid points within its observed time span; nothing is extrapolated. Continuous columns are interpolated linearly in time, labels and flags take the nearest native sample; with Montanino & Punzo at the same rate, pos_lon, speed, and acceleration come directly from the reconstruction. resampling.rate_hz = None keeps the native rate.

Surroundings. For each vehicle and grid time, the leader and follower in its own lane and in the lanes to the left (lane + 1) and right (lane − 1) are found at the identical timestamp. "Front" means larger pos_lon. For each of the six positions:

  • headway: center-to-center distance along the direction of travel;
  • clearance: headway − (L_subject + L_neighbor) / 2;
  • relative speed: v_neighbor − v_subject.

Unassigned points (lane −1) have no neighbors and are nobody's neighbor. An adjacent-lane vehicle exactly side by side (within 1 mm) is a rear neighbor with a negative clearance, never a front one. A missing vehicle length is filled with 4.5 m.

Pairwise measures need common timestamps: if the input is thinned (for example 30 → 10 Hz), take every n-th frame of the recording, not every n-th sample of each track.

Sources. The grid, the six neighbor positions, the 1 mm tie rule and the 4.5 m default length are chosen for this library; see 10.

Lane-change events

The last step builds the event table: one row per detector interval classified as a lane change or lateral excursion, with timing, lanes before and after, kinematics, and the neighbors from the output grid at the nearest grid time: at the start the leader and follower in the target lane, at the crossing and at the end those in the vehicle's own lane. Events whose crossing (lane changes) or peak (excursions) lies within 30 m of either end of the section (lane_change.edge_buffer_m) are flagged near_road_end (30 m chosen for this library; see 03 and 07); artifacts of the section ends concentrate there, so exclude them from behavioral statistics.

The lane-change duration is the length of the detector interval (start and end where the smoothed lateral speed crosses 0.1 m/s). This definition gives longer durations than values reported in the literature for NGSIM; see limitations.md.

References

  • Baumann, M. V., Grau, J., & Vortisch, P. (2027). Automated lane assignment for drone-based vehicle trajectories under perspective distortion. Procedia Computer Science. Submitted to ANT 2027.
  • Chen, Y., & Krumm, J. (2010). Probabilistic modeling of traffic lanes from GPS traces. Proc. 18th ACM SIGSPATIAL International Conference on Advances in Geographic Information Systems, 81–88. https://doi.org/10.1145/1869790.1869805
  • Coifman, B., & Li, L. (2017). A critical evaluation of the Next Generation Simulation (NGSIM) vehicle trajectory dataset. Transportation Research Part B, 105, 362–377. https://doi.org/10.1016/j.trb.2017.09.018
  • Coifman, B., & Li, L. (2024). Partial trajectory method to align and validate successive video cameras for vehicle tracking. Transportation Research Part C, 158, 104416. https://doi.org/10.1016/j.trc.2023.104416
  • Fonod, R., Cho, H., Yeo, H., & Geroliminis, N. (2025). Advanced computer vision for extracting georeferenced vehicle trajectories from drone imagery. Transportation Research Part C, 178, 105205. https://doi.org/10.1016/j.trc.2025.105205
  • Hofinger, F., & Fellendorf, M. (2023). Lane change behavior on motorways based on naturalistic trajectory data. 11th Symposium of the European Association for Research in Transportation (hEART 2023), Zürich. https://transp-or.epfl.ch/heart/2023/abstracts/hEART_2023_paper_2329.pdf
  • Krajewski, R., Bock, J., Kloeker, L., & Eckstein, L. (2018). The highD dataset: A drone dataset of naturalistic vehicle trajectories on German highways for validation of highly automated driving systems. Proc. 21st IEEE International Conference on Intelligent Transportation Systems (ITSC), 2118–2125. https://doi.org/10.1109/ITSC.2018.8569552
  • Moers, T., Vater, L., Krajewski, R., Bock, J., Zlocki, A., & Eckstein, L. (2022). The exiD dataset: A real-world trajectory dataset of highly interactive highway scenarios in Germany. 2022 IEEE Intelligent Vehicles Symposium (IV), 958–964. https://doi.org/10.1109/IV51971.2022.9827305
  • 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
  • Montanino, M., & Punzo, V. (2015). Trajectory data reconstruction and simulation-based validation against macroscopic traffic patterns. Transportation Research Part B, 80, 82–106. https://doi.org/10.1016/j.trb.2015.06.010
  • Páncsics, Z., Nyisztor, N., Tóth, T., Juhász, I., Treplán, G., & Hajder, L. (2024). Error analysis of aerial image-based relative object position estimation. Proc. 19th International Joint Conference on Computer Vision, Imaging and Computer Graphics Theory and Applications (VISAPP), Vol. 3, 656–663. https://doi.org/10.5220/0012433300003660
  • Punzo, V., Borzacchiello, M. T., & Ciuffo, B. (2011). On the assessment of vehicle trajectory data accuracy and application to the Next Generation SIMulation (NGSIM) program data. Transportation Research Part C, 19(6), 1243–1262. https://doi.org/10.1016/j.trc.2010.12.007
  • Rabiner, L. R. (1989). A tutorial on hidden Markov models and selected applications in speech recognition. Proceedings of the IEEE, 77(2), 257–286. https://doi.org/10.1109/5.18626
  • Sánchez Morales, E., Kruber, F., Botsch, M., Huber, B., & García Higuera, A. (2020). Accuracy characterization of the vehicle state estimation from aerial imagery. 2020 IEEE Intelligent Vehicles Symposium (IV), 2081–2088. https://doi.org/10.1109/IV47402.2020.9304705 (preprint arXiv:2005.06314)
  • Thiemann, C., Treiber, M., & Kesting, A. (2008). Estimating acceleration and lane-changing dynamics from Next Generation Simulation trajectory data. Transportation Research Record, 2088, 90–101. https://doi.org/10.3141/2088-10
  • Wang, Y., Gloudemans, D., Ji, J., Teoh, Z. N., Liu, L., Zachár, G., Barbour, W., & Work, D. (2024). Automatic vehicle trajectory data reconstruction at scale. Transportation Research Part C, 160, 104520. https://doi.org/10.1016/j.trc.2024.104520 (preprint arXiv:2212.07907)

The step documents use the same list (references).