Skip to content

Package level

Generated by docs/scripts/make_api_pages.py.

Post-processing of drone-based vehicle trajectories.

The package turns raw trajectories (positions per vehicle and frame) into road-referenced, cleaned and lane-assigned trajectories: projection onto a reference line, perspective correction of tall vehicles, alignment, stitching, kinematic reconstruction, lane geometry and lane assignment, lane-change detection and surrounding vehicles. The orchestrator is :func:run_pipeline; the steps live in :mod:trajlab.processing. The run metadata of an output is read with :func:trajlab.metadata.run_metadata.

Example

import trajlab raw = trajlab.examples.synthetic_motorway() ref_east, ref_west = trajlab.estimate_ref_lines(raw) out = trajlab.run_pipeline(raw[raw["orientation"] > 0], ref_east, trajlab.load_preset("drone_hgv_paper"))

Attributes:

Name Type Description
__version__

Installed version of the package ("2.0.0" when run from a source tree).

Column names, lane IDs, sign conventions and units of the pipeline.

Conventions:

===================== ======================================================== Topic Convention ===================== ======================================================== Longitudinal sign pos_lon increases in the direction of travel. Step 1 guarantees this whatever direction the reference line was digitised in. Lateral sign pos_lat > 0 is left of the direction of travel. This holds because of the longitudinal normalisation. Lane IDs 0 = auxiliary lane (on/off-ramp, acceleration or deceleration lane). 1 = rightmost lane of the main carriageway. IDs increase to the left. -1 = unassigned. Neighbours *_left = lane + 1, *_right = lane - 1. Vehicles in lane 1 see lane-0 vehicles as their right neighbours (merge interactions). An adjacent-lane vehicle exactly side by side (within 1 mm) is a rear neighbour. Lane-change direction lc_direction = +1 / "left" means towards a higher lane ID (increasing pos_lat); -1 / "right" the opposite. A merge from lane 0 to lane 1 is a left lane change. Output rate The final output is on a common grid t0 + k / rate (10 Hz by default, same t0 for all vehicles). Steps 1-5 run at the native frame rate. Inputs No public function mutates its input. ===================== ========================================================

Units: speeds in km/h, accelerations in m/s^2, distances and positions in m, times in s.

neighbour_column

neighbour_column(metric: str, position: str) -> str

Return the column name of a neighbour metric, e.g. for ("clearance", "front_left").

Parameters:

Name Type Description Default
metric str

One of NEIGHBOUR_METRICS.

required
position str

One of NEIGHBOUR_POSITIONS.

required

Returns:

Type Description
str

The column name "<metric>_<position>".

Raises:

Type Description
ValueError

If metric or position is unknown.

Environment variables of the library, the applications and the tools (TRAJLAB_*).

All variables are named TRAJLAB_<NAME> (e.g. TRAJLAB_DATA_ROOT, TRAJLAB_EXID_DIR). Read every variable through :func:get (or :func:require), never through os.environ directly, so that the name is checked in one place.

name

name(var: str) -> str

Return the full name of a variable.

Parameters:

Name Type Description Default
var str

TRAJLAB_<NAME> or <NAME>.

required

Returns:

Type Description
str

TRAJLAB_<NAME>.

get

get(var: str, default: str | None = None, environ: Mapping[str, str] | None = None) -> str | None

Return the value of an environment variable.

Parameters:

Name Type Description Default
var str

TRAJLAB_<NAME> (<NAME> is accepted as well).

required
default str | None

Returned when the variable is not set.

None
environ Mapping[str, str] | None

Mapping to read from; default os.environ.

None

Returns:

Type Description
str | None

The value of TRAJLAB_<NAME> if set, else default.

require

require(var: str, environ: Mapping[str, str] | None = None) -> str

Return the value of an environment variable that must be set (see :func:get).

Parameters:

Name Type Description Default
var str

TRAJLAB_<NAME> (<NAME> is accepted as well).

required
environ Mapping[str, str] | None

Mapping to read from; default os.environ.

None

Returns:

Type Description
str

The value.

Raises:

Type Description
KeyError

If TRAJLAB_<NAME> is not set.

Synthetic example data: a two-direction motorway with heavy goods vehicles and a camera hand-over.

The example mimics the structure of drone recordings that the pipeline was built for, without any real data: a gently curved six-lane motorway section (three lanes per direction, 3.75 m wide) in EPSG:25832, cars and heavy goods vehicles (HGVs), lane changes, short lateral excursions, position noise, and two camera views that meet at the middle of the section. Two effects of real recordings are reproduced on purpose:

  • Perspective offset of tall vehicles. Detections give the centre of the top of a bounding box, so HGV positions are displaced laterally; the displacement differs between camera views. Here it is a constant world offset per view (hgv_offsets_m), which is what perspective.correction = "class_offset_empirical_view" estimates.
  • Fragmentation at the camera hand-over. A share of the tracks is cut at the hand-over and continues under a new ID after a short gap, which is what the stitching step joins.

The generator is deterministic for a given seed.

Example::

import trajlab

raw = trajlab.examples.synthetic_motorway()
ref_east, ref_west = trajlab.estimate_ref_lines(raw)
out = trajlab.run_pipeline(raw[raw["orientation"] > 0], ref_east)

synthetic_motorway

synthetic_motorway(duration_s: float = 40.0, road_length_m: float = 1000.0, fps: float = 10.0, flow_veh_h_per_lane: float = 900.0, hgv_share: float = 0.3, hgv_offsets_m: Sequence[float] = (0.4, 1.5), fragment_share: float = 0.15, noise_std_m: float = 0.05, radius_m: float = 4000.0, seed: int = 0) -> gpd.GeoDataFrame

Generate the synthetic two-direction example.

:func:synthetic_motorway_with_truth returns the same data together with the true lane per sample.

Parameters:

Name Type Description Default
duration_s float

Recording duration [s].

40.0
road_length_m float

Length of the observed section [m].

1000.0
fps float

Sampling rate [Hz].

10.0
flow_veh_h_per_lane float

Mean flow per lane [veh/h] (exponential headways, at least 1.5 s).

900.0
hgv_share float

Share of HGVs among the vehicles entering lane 1 [-], 0 … 1 (lane 2 gets a quarter of that share, lane 3 none).

0.3
hgv_offsets_m Sequence[float]

Perspective offset of HGV positions per camera view [m], along the left normal of the eastbound direction (view 1 = first half of the section, view 2 = second half).

(0.4, 1.5)
fragment_share float

Share of the tracks that are cut at the camera hand-over [-], 0 … 1 (gap of about 1 s, new ID after it).

0.15
noise_std_m float

Standard deviation of the position noise [m].

0.05
radius_m float

Radius of the road's circular arc [m].

4000.0
seed int

Seed of the random generator.

0

Returns:

Type Description
GeoDataFrame

One row per vehicle and frame in EPSG:25832 with id, datum, class, length [m],

GeoDataFrame

orientation (+1 eastbound, -1 westbound), vel [km/h], utm_x, utm_y [m], time_sec

GeoDataFrame

[s] and point geometry; attrs["hand_over_s"] is the hand-over position [m].

synthetic_motorway_with_truth

synthetic_motorway_with_truth(duration_s: float = 40.0, road_length_m: float = 1000.0, fps: float = 10.0, flow_veh_h_per_lane: float = 900.0, hgv_share: float = 0.3, hgv_offsets_m: Sequence[float] = (0.4, 1.5), fragment_share: float = 0.15, noise_std_m: float = 0.05, radius_m: float = 4000.0, seed: int = 0) -> tuple[gpd.GeoDataFrame, pd.DataFrame]

Generate the synthetic two-direction example together with the true lane per sample.

Parameters:

Name Type Description Default
duration_s float

Recording duration [s].

40.0
road_length_m float

Length of the observed section [m].

1000.0
fps float

Sampling rate [Hz].

10.0
flow_veh_h_per_lane float

Mean flow per lane [veh/h] (exponential headways, at least 1.5 s).

900.0
hgv_share float

Share of HGVs among the vehicles entering lane 1 [-], 0 … 1 (lane 2 gets a quarter of that share, lane 3 none).

0.3
hgv_offsets_m Sequence[float]

Perspective offset of HGV positions per camera view [m], along the left normal of the eastbound direction (view 1 = first half of the section, view 2 = second half).

(0.4, 1.5)
fragment_share float

Share of the tracks that are cut at the camera hand-over [-], 0 … 1 (gap of about 1 s, new ID after it).

0.15
noise_std_m float

Standard deviation of the position noise [m].

0.05
radius_m float

Radius of the road's circular arc [m].

4000.0
seed int

Seed of the random generator.

0

Returns:

Type Description
GeoDataFrame

A tuple (gdf, truth): gdf as returned by :func:synthetic_motorway, truth the true lane per

DataFrame

sample (id, datum, lane, s [m]).

Access to the run metadata that :func:trajlab.run_pipeline attaches to its output.

The pipeline stores its run metadata (configuration, library version and git commit, dependency versions, rows and vehicles per step, perspective and lane-geometry results; see :func:trajlab.processing.pipeline.build_run_metadata) in out.attrs["trajlab"]. Read it with :func:run_metadata instead of indexing attrs directly.

Example

import pandas as pd from trajlab.metadata import run_metadata out = pd.DataFrame() out.attrs["trajlab"] = {"config": {}} run_metadata(out) {'config': {}}

has_run_metadata

has_run_metadata(obj: Any) -> bool

Return whether obj carries run metadata.

Parameters:

Name Type Description Default
obj Any

A pipeline output (anything with an attrs mapping) or the attrs mapping itself.

required

Returns:

Type Description
bool

True if attrs["trajlab"] is present.

Raises:

Type Description
TypeError

If obj has no attrs mapping and is not a mapping; raised by the helper _attrs.

run_metadata

run_metadata(obj: Any, default: dict[str, Any] | None = None) -> dict[str, Any]

Return the run metadata of a pipeline output.

Parameters:

Name Type Description Default
obj Any

A pipeline output (anything with an attrs mapping) or the attrs mapping itself.

required
default dict[str, Any] | None

Returned when the key is absent; None raises KeyError instead.

None

Returns:

Type Description
dict[str, Any]

The run-metadata dict (the object stored in attrs, not a copy).

Raises:

Type Description
KeyError

If attrs["trajlab"] is absent and no default is given.

TypeError

If obj has no attrs mapping and is not a mapping; raised by the helper _attrs.

Parameters of the Montanino & Punzo reconstruction, shared by the kinematics step and the configuration.

trajlab.config re-exports MontaninoPunzoConfig (section kinematics.mp); the processing step trajlab.processing.kinematics takes it directly. This module imports neither the configuration nor the processing steps.

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.

Road layout of a site: auxiliary-lane zones, lane-count zones and the number of main lanes.

The zones are entered per site in pos_lon [m] along the direction of travel; lane 0 = auxiliary or ramp lane, 1 = rightmost main lane. The processing steps take a LaneLayout; the configuration (trajlab.config, section lanes) re-exports the same classes. This module imports neither the configuration nor the processing steps.

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.

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.

LaneLayout dataclass

LaneLayout(n_main_lanes: int = 3, auxiliary_lane_zones: Sequence[AuxLaneZone] = list(), lane_count_zones: Sequence[LaneCountZone] = list())

Number of main lanes and the zones of one direction of a site, as the processing steps take them.

Attributes:

Name Type Description
n_main_lanes int

Number of main lanes outside all lane-count zones. Defaults to 3.

auxiliary_lane_zones Sequence[AuxLaneZone]

Sections with an auxiliary lane (lane 0); dicts are converted. Defaults to none.

lane_count_zones Sequence[LaneCountZone]

Sections with a different number of main lanes; dicts are converted. Defaults to none.

__post_init__

__post_init__() -> None

Convert zone dicts to AuxLaneZone / LaneCountZone (lists of zones).

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.

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.

Type aliases used across the package.

The aliases name the recurring table layouts; the column schemas are described here once and referred to from the function docstrings. Column names and units follow trajlab.conventions.