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 ( |
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 |
required |
position
|
str
|
One of |
required |
Returns:
| Type | Description |
|---|---|
str
|
The column name |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
|
|
required |
Returns:
| Type | Description |
|---|---|
str
|
|
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
|
|
required |
default
|
str | None
|
Returned when the variable is not set. |
None
|
environ
|
Mapping[str, str] | None
|
Mapping to read from; default |
None
|
Returns:
| Type | Description |
|---|---|
str | None
|
The value of |
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
|
|
required |
environ
|
Mapping[str, str] | None
|
Mapping to read from; default |
None
|
Returns:
| Type | Description |
|---|---|
str
|
The value. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If |
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 whatperspective.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 |
GeoDataFrame
|
|
GeoDataFrame
|
[s] and point |
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 |
DataFrame
|
sample ( |
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 |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
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 |
required |
default
|
dict[str, Any] | None
|
Returned when the key is absent; None raises |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
The run-metadata dict (the object stored in |
Raises:
| Type | Description |
|---|---|
KeyError
|
If |
TypeError
|
If |
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 ( |
filter_padlen_sec |
float | None
|
Zero-phase filtering only: length of the odd extension at both track ends in seconds
( |
edge_method |
str
|
Zero-phase only: |
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 |
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, |
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 |
lon_end |
float
|
End of the zone in |
kind |
str
|
One of |
__post_init__
__post_init__() -> None
Check the zone limits and the kind.
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
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 |
lon_end |
float
|
End of the zone in |
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 |
taper_m |
float
|
Length (m) of the transition before |
__post_init__
__post_init__() -> None
Check the zone, convert n_lanes to int.
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
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 |
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 ( |
required |
zones
|
Sequence[LaneCountZone] | None
|
Lane-count zones; a later zone wins where zones overlap. None or empty: |
required |
Returns:
| Type | Description |
|---|---|
int | ndarray
|
An int for a scalar |