Skip to content

Input and output

Generated by docs/scripts/make_api_pages.py.

Input and output: readers of the public trajectory datasets, synthetic scenarios, OpenDRIVE.

  • readers: one reader per public trajectory dataset onto the internal format (read_dataset dispatches by name).
  • synthetic: straight-road scenarios with known ground truth.
  • opendrive: minimal OpenDRIVE reader (reference lines and lane boundaries).

Conventions: 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.

Minimal OpenDRIVE (.xodr) reader: road reference lines and lane boundaries.

Supported (ASAM OpenDRIVE 1.4-1.6):

  • plan view geometries line, arc, spiral (clothoid, linear curvature), poly3 and paramPoly3 (pRange arcLength or normalized); every geometry is sampled on an arc-length grid (polynomial geometries are re-parametrised numerically by arc length);
  • laneOffset (cubic in s), lane sections with left / right lanes, lane width records (cubic in the distance from the section start plus sOffset) and lane type.

Not supported: elevation, superelevation, lane border records (lanes defined by borders instead of widths are skipped with a warning), junction connection semantics (each road is read on its own).

read_opendrive(path) returns one Road per <road>; Road.sample(ds) gives the reference line (s, x, y, hdg) and Road.lane_boundaries(ds) a long table of lane boundary points in map coordinates with the lane id, side and type, which RoadReference.lane_layout projects into any reference frame. Map coordinates are metres; s is the arc length along the road reference line [m], t the lateral offset from it [m] (positive to the left), headings hdg are in radians.

Reference: ASAM OpenDRIVE 1.6, sections 7 (plan view) and 9 (lanes).

Geometry dataclass

Geometry(s: float, x: float, y: float, hdg: float, length: float, kind: str, params: dict[str, Any] = dict())

One plan-view geometry record of a road reference line.

Attributes:

Name Type Description
s float

Start arc length along the road [m].

x float

Start x in map coordinates [m].

y float

Start y in map coordinates [m].

hdg float

Start heading [rad].

length float

Arc length of the geometry [m].

kind str

"line", "arc", "spiral", "poly3" or "paramPoly3".

params dict[str, Any]

Parameters of the kind: curvature [1/m] (arc), curvStart / curvEnd [1/m] (spiral), a ... d (poly3), aU ... dV and pRange (paramPoly3). Defaults to an empty dict.

sample

sample(ds: float = 0.5) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]

Sample the geometry on an arc-length grid.

Parameters:

Name Type Description Default
ds float

Maximum step of the grid [m]; the geometry is split into ceil(length / ds) equal steps.

0.5

Returns:

Type Description
ndarray

Tuple (s, x, y, hdg) of float arrays at arc lengths self.s + [0, ..., length]: arc length [m], map

ndarray

coordinates [m] and heading [rad].

Raises:

Type Description
ValueError

If kind is not supported.

Lane dataclass

Lane(id: int, type: str, widths: list[tuple[float, ...]])

One lane of a lane section.

Attributes:

Name Type Description
id int

OpenDRIVE lane id (positive left, negative right of the reference line).

type str

OpenDRIVE lane type, e.g. "driving", "shoulder"; "none" if missing.

widths list[tuple[float, ...]]

Width records (sOffset, a, b, c, d), sorted by sOffset; the width at distance ds [m] from the section start is a + b u + c u^2 + d u^3 with u = ds - sOffset [m].

width

width(ds: ndarray) -> np.ndarray

Return the lane width [m] at distances ds [m] from the section start (0 without width records).

Each distance uses the last width record starting at or before it (the first record before the first sOffset); negative widths are clipped to 0.

Parameters:

Name Type Description Default
ds ndarray

Distances from the start of the lane section [m].

required

Returns:

Type Description
ndarray

The lane width at each distance [m], same shape as ds.

LaneSection dataclass

LaneSection(s: float, left: list[Lane], right: list[Lane])

A lane section of a road.

Attributes:

Name Type Description
s float

Start arc length of the section along the road [m].

left list[Lane]

Lanes left of the reference line (positive ids).

right list[Lane]

Lanes right of the reference line (negative ids).

Road dataclass

Road(id: str, name: str, length: float, junction: str, geometries: list[Geometry], offsets: list[tuple[float, ...]], sections: list[LaneSection], predecessor: RoadLink | None = None, successor: RoadLink | None = None)

One OpenDRIVE road: plan view, lane offset and lane sections.

Attributes:

Name Type Description
id str

Road id.

name str

Road name (empty if missing).

length float

Road length [m].

junction str

Junction id ("-1" outside junctions).

geometries list[Geometry]

Plan-view geometries, sorted by s.

offsets list[tuple[float, ...]]

Lane offset records (s, a, b, c, d) (cubic in s - s0 [m]), sorted.

sections list[LaneSection]

Lane sections, sorted by s.

predecessor RoadLink | None

Link to the predecessor (elementType, elementId, contactPoint). Defaults to None.

successor RoadLink | None

Link to the successor, as predecessor. Defaults to None.

sample

sample(ds: float = 0.5) -> pd.DataFrame

Sample the reference line of the whole road.

Parameters:

Name Type Description Default
ds float

Maximum step of the arc-length grid [m] per geometry.

0.5

Returns:

Type Description
DataFrame

DataFrame with s [m], x, y [m] and hdg [rad]; duplicate arc lengths at the joints of two

DataFrame

geometries are dropped.

lane_offset

lane_offset(s: ndarray) -> np.ndarray

Return the lane offset [m] (shift of the lane reference from the road reference line) at arc lengths s.

Parameters:

Name Type Description Default
s ndarray

Arc lengths along the road [m].

required

Returns:

Type Description
ndarray

Float array like s; 0 without laneOffset records.

lane_boundaries

lane_boundaries(ds: float = 0.5, types: Iterable[str] | None = None) -> pd.DataFrame

Return the lane boundary points of the road as a long table.

Parameters:

Name Type Description Default
ds float

Maximum step of the arc-length grid [m].

0.5
types Iterable[str] | None

Lane types to include (e.g. ("driving", "entry")); None: all lanes. Lanes of other types still count for the offsets of the lanes outside them.

None

Returns:

Type Description
DataFrame

DataFrame with road, section, lane, side (+1 left, -1 right), type, s [m],

DataFrame

t_inner, t_outer [m] (lateral offsets from the reference line, positive left), width [m] and

DataFrame

the map coordinates x_inner, y_inner, x_outer, y_outer, x_centre, y_centre [m];

DataFrame

empty if no lane matches.

read_opendrive

read_opendrive(path: Path | str) -> dict[str, Road]

Read the roads of an OpenDRIVE file.

An XML namespace is dropped; unsupported plan-view geometries are skipped with a warning, as are (with a warning) lanes defined by border records instead of widths, which get no width.

Parameters:

Name Type Description Default
path Path | str

The .xodr file.

required

Returns:

Type Description
dict[str, Road]

Dict road id -> Road.

lane_boundaries

lane_boundaries(roads: Mapping[str, Road], ds: float = 0.5, types: Iterable[str] | None = None) -> pd.DataFrame

Return Road.lane_boundaries of all roads in one table.

Parameters:

Name Type Description Default
roads Mapping[str, Road]

Roads as returned by read_opendrive.

required
ds float

Maximum step of the arc-length grid [m].

0.5
types Iterable[str] | None

Lane types to include; None: all lanes.

None

Returns:

Type Description
DataFrame

The concatenated tables (see Road.lane_boundaries); empty if no road has a matching lane.

Readers for public trajectory datasets: one adapter per dataset onto the internal format.

Every reader returns a GeoDataFrame with the raw positions of one recording (never the dataset's own speeds or accelerations, so the pipeline processes the data like any other recording) and these columns:

  • id (int), datum (datetime64), class (canonical: Car, Van, Truck, Bus, Motorcycle, Other; Truck/Bus count as heavy vehicles in the pipeline), class_provider (the dataset's label), length and width (m, where available);
  • road-aligned datasets (highD, RWTH A43, NGSIM, UTE, I-24 MOTION): pos_lon (m, along the direction of travel, starting at 0) and pos_lat (m, positive to the left of the direction of travel, ≄ 0), geometry = Point(pos_lon, pos_lat) without CRS, attrs["coordinates"] = "road". Pass the frame of one driving direction to run_pipeline(gdf, None, config); the projection step is skipped.
  • planar datasets (exiD, INTERACTION, MONA, DLR HT, Automatum): UTM or local x/y in metres as geometry, orientation (+1 / āˆ’1: sign of the track displacement along the principal axis of all positions), attrs["coordinates"] = "planar". Use reference_line(gdf, direction) (or a user-supplied line, e.g. from OSM for curved sites) and pass the frame of that direction with the line to the pipeline.
  • lane ground truth where the dataset has lane IDs: lane_gt in the pipeline's convention (1 = rightmost main lane, increasing to the left, 0 = auxiliary lane, āˆ’1 = not evaluated) and lane_provider (the raw ID).

read_dataset(name, ...) dispatches by name (DATASETS). The readers only read; no file is written (except the optional parquet cache of read_automatum when a cache_dir is given) and nothing is extracted from zip archives (highD and DLR HT are read from the zip directly). Licences: the datasets may not be redistributed; keep derived data local.

Documented limitations: NGSIM provider lanes contain known errors (Coifman & Li 2017); INTERACTION/MONA lanes exist only in their maps (no lane_gt); UTE has no classes (heavy vehicles from the length) and its lane order is an assumption (see the dataset documentation).

LaneMapping dataclass

LaneMapping(chain_lane: dict[int, int], lanelet_lane: dict[int, int], n_main_lanes: int, zones: list[dict[str, Any]], ambiguous_share: float, excluded: bool, reason: str = '', profile: DataFrame = pd.DataFrame())

Result of the lanelet-to-lane conversion of one recording and direction.

Attributes:

Name Type Description
chain_lane dict[int, int]

Chain id -> lane label (-1 = not evaluated); map_exid_lanes uses the lanelets as chains, so this equals lanelet_lane.

lanelet_lane dict[int, int]

Lanelet id -> lane label.

n_main_lanes int

Number of main lanes.

zones list[dict[str, Any]]

Auxiliary-lane zones as dicts (lon_start, lon_end [m] in pos_lon, kind).

ambiguous_share float

Share (0-1) of bins with a lateral overlap of two lanelets with different labels.

excluded bool

True if the mapping is ambiguous (share above the limit) or has fewer than two main lanes.

reason str

Why the recording was excluded (empty otherwise). Defaults to "".

profile DataFrame

Per bin and lanelet: bin, chain, median, p10, p90 [m] of pos_lat, n and group (for the validation plot). Defaults to an empty DataFrame.

dlrht_files

dlrht_files(source: Path | str) -> list[str]

List the trajectory CSV files (5 min each) of the DLR HT dataset.

Parameters:

Name Type Description Default
source Path | str

The dataset zip or the extracted folder.

required

Returns:

Type Description
list[str]

Sorted names: member names inside the zip (.../trajectories/...csv), or paths of the

list[str]

trajectories_*.csv files below the folder.

read_dlrht

read_dlrht(source: Path | str, files: str | Sequence[str], bbox: tuple[float, float, float, float] | None = None) -> gpd.GeoDataFrame

Read the DLR Highway Traffic dataset (A39, 59 roadside poles with 118 cameras; 20 Hz), planar UTM 32N.

Parameters:

Name Type Description Default
source Path | str

The dataset zip (read in place) or the extracted folder.

required
files str | Sequence[str]

One or more trajectory CSV names (dlrht_files), concatenated in time.

required
bbox tuple[float, float, float, float] | None

Optional (min_easting, min_northing, max_easting, max_northing) crop [m]: the corridor is several kilometres long and curved, so a reference line usually needs a section of it.

None

Returns:

Name Type Description
GeoDataFrame

Planar RawFrame (trajlab.typing.RawFrame; columns as in "Common output" of docs/readers.md) in

EPSG GeoDataFrame

32632, datum timezone-naive UTC, class the class with the highest probability of the

GeoDataFrame

classifications_* columns (mapped by DLRHT_CLASSES), length / width from the dimensions;

GeoDataFrame

further columns utm_x / utm_y [m]. Duplicate (id, datum) rows are dropped; the dataset's

GeoDataFrame

velocities and accelerations are not used. attrs["frame_rate"] = 20.0.

exid_dir

exid_dir(base_dir: Path | str | None = None) -> Path | None

Return the exiD root folder.

Parameters:

Name Type Description Default
base_dir Path | str | None

exiD root; None: the environment variable TRAJLAB_EXID_DIR.

None

Returns:

Type Description
Path | None

The root as a Path, or None if neither is set or the folder has no data/ subfolder.

exid_recordings

exid_recordings(base_dir: Path | str | None = None) -> pd.DataFrame

Return the recording metadata (recordingMeta) of all exiD recordings with a tracks file.

Parameters:

Name Type Description Default
base_dir Path | str | None

exiD root; None: TRAJLAB_EXID_DIR.

None

Returns:

Type Description
DataFrame

One row per recording with the columns of exiD's *_recordingMeta.csv; empty if exiD is not found.

read_exid

read_exid(recording_id: int, base_dir: Path | str | None = None, base_timestamp: Timestamp = EXID_BASE_TIMESTAMP) -> gpd.GeoDataFrame

Read the raw positions of one exiD recording (no dataset kinematics).

Samples without a lanelet are dropped (a few in recordings 46, 55, 56).

Parameters:

Name Type Description Default
recording_id int

exiD recording number.

required
base_dir Path | str | None

exiD root; defaults to TRAJLAB_EXID_DIR.

None
base_timestamp Timestamp

Timestamp of frame 0 (exiD gives no absolute time).

EXID_BASE_TIMESTAMP

Returns:

Type Description
GeoDataFrame

GeoDataFrame in EPSG:25832 with id, datum, utm_x, utm_y [m], geometry (bounding-box

GeoDataFrame

centre), length / width [m], class (exiD label), orientation (+1 / -1: sign of the track

GeoDataFrame

displacement along the principal axis of all positions), lanelet_id and lanelet_lane_change (exiD

GeoDataFrame

laneChange); attrs recording_id, location_id and frame_rate.

Raises:

Type Description
FileNotFoundError

If the exiD root is not found.

lanelet_chains

lanelet_chains(df: DataFrame) -> dict[int, int]

Map every lanelet to a chain id: lanelets joined by lanelet changes without lane change (union-find).

Parameters:

Name Type Description Default
df DataFrame

read_exid rows with id, datum, lanelet_id and lanelet_lane_change.

required

Returns:

Type Description
dict[int, int]

Dict lanelet id -> chain id (the smallest lanelet id of the chain).

map_exid_lanes

map_exid_lanes(projected: DataFrame, bin_m: float = 10.0, min_points: int = 20, main_quantile: float = 0.1, max_ambiguous_share: float = 0.05, aux_max_offset_lanes: float = 1.5, same_lane_gap_m: float = 1.5, max_lane_gap_m: float = 6.0) -> LaneMapping

Derive lane labels from exiD lanelets for one direction (see the module docstring).

Per bin, the lanelets present (at least min_points samples) are ordered by their median lateral position. The number of main lanes is a low quantile (main_quantile) of the lane count of the carriageway per bin, i.e. the lanes present along (almost) the whole section. In every bin the n_main leftmost lanes are the main lanes n_main ... 1; a lanelet right of lane 1 is the auxiliary lane 0 if its median lies less than aux_max_offset_lanes lane widths right of lane 1, else it is not evaluated (-1, a ramp leaving the carriageway). Each lanelet finally gets the label it has in most of its bins.

Parameters:

Name Type Description Default
projected DataFrame

Rows of one direction with pos_lon, pos_lat [m] (projected, aligned or not) and lanelet_id.

required
bin_m float

Bin length along pos_lon [m].

10.0
min_points int

Minimum samples of a lanelet in a bin.

20
main_quantile float

Quantile (0-1) of the carriageway lane count per bin taken as the number of main lanes.

0.1
max_ambiguous_share float

Maximum share (0-1) of bins with a lateral overlap of two lanelets with different labels.

0.05
aux_max_offset_lanes float

Maximum distance of an auxiliary lanelet right of lane 1, in lane widths (the median spacing of the main lanes, 3.75 m with a single main lane).

1.5
same_lane_gap_m float

Lanelets of one bin whose medians are closer than this [m] are pieces of the same lane (predecessor and successor meeting inside the bin).

1.5
max_lane_gap_m float

Lanes farther apart than this [m] belong to different roads; only the leftmost block of adjacent lanes is the carriageway, lanes beyond the gap are not evaluated.

6.0

Returns:

Type Description
LaneMapping

A LaneMapping (chain_lane holds the lanelet labels too). The first and last bin are left out

LaneMapping

(points beyond the ends of the reference line are projected onto them). Without enough samples: an

LaneMapping

excluded mapping with n_main_lanes = 0 and ambiguous_share = NaN.

exid_ground_truth

exid_ground_truth(out: DataFrame, mapping: LaneMapping) -> pd.DataFrame

Return the lane ground truth for the rows of a pipeline output (needs lanelet_id carried through).

Rows whose lanelet is not evaluated, or that lie in an auxiliary lanelet outside every zone (only checked if out has pos_lon), get -1.

Parameters:

Name Type Description Default
out DataFrame

Rows with id, datum, lanelet_id and optionally pos_lon [m].

required
mapping LaneMapping

Result of map_exid_lanes for the same recording and direction.

required

Returns:

Type Description
DataFrame

DataFrame with id, datum and lane_gt, one row per row of out.

exid_evaluation_case

exid_evaluation_case(recording_id: int, direction: int, base_dir: Path | str | None = None, ref_smoothing: float = 1.0, min_evaluated_share: float = 0.5, min_samples: int = 50) -> dict[str, Any]

Assemble everything needed to evaluate the pipeline on one exiD recording and direction.

The reference line comes from estimate_ref_lines(..., rms_tolerance_m=sqrt(ref_smoothing)) (default 1, i.e. an RMS deviation of about 1 m from the binned median trajectory; looser settings are too loose for the short, curved exiD sections). The input is cropped to the carriageway, as a user of a single-carriageway pipeline would crop the recording: only samples on an evaluated lane (main lanes, auxiliary lane inside its zone) are kept, of vehicles with at least min_evaluated_share of their samples there and at least min_samples samples left. Samples on ramps beyond the gore or on a parallel road would otherwise pull the road-edge alignment of Step 2. If the first mapping is not excluded, the reference line, the mapping and the crop are computed a second time from the carriageway samples only.

Parameters:

Name Type Description Default
recording_id int

exiD recording.

required
direction int

+1 or -1 (orientation of read_exid).

required
base_dir Path | str | None

exiD root; defaults to TRAJLAB_EXID_DIR.

None
ref_smoothing float

Square of the RMS tolerance [m^2] of the reference line (see above).

1.0
min_evaluated_share float

Minimum share (0-1) of evaluated samples per vehicle.

0.5
min_samples int

Minimum evaluated samples per vehicle.

50

Returns:

Type Description
dict[str, Any]

Dict with gdf (cropped raw input), ref_line, mapping (LaneMapping), config (nested

dict[str, Any]

site-config dict: n_main_lanes and auxiliary-lane zones from the mapping), vehicles_dropped and

dict[str, Any]

recording / location / direction ("pos" or "neg").

read_i24motion

read_i24motion(source: Path | str | DataFrame, direction: int | None = None, x_origin_ft: float | None = None) -> gpd.GeoDataFrame

Read one driving direction of an I-24 MOTION sample (Gloudemans et al. 2023), road-aligned, 25 Hz.

source is a sample cut from the I-24 MOTION trajectory documents (parquet or DataFrame: one row per point with id (provider ObjectId), t (Unix s), x, y (ft) and the document attributes direction, length_ft, width_ft, height_ft, coarse_class, flags, n_fragments; optionally in_window and attrs["mm"], the mile-marker range of the sample).

Coordinates: I-24 roadway coordinates are already road-aligned (x along the median spline, MM 60 = 316 800 ft; y perpendicular, negative EB, positive WB; data documentation v1.x). x_position is the back centre of the vehicle; the reader moves it to the vehicle centre (+ direction * length / 2), the reference of the other readers. pos_lon = direction * (x_centre - x_origin_ft) * 0.3048, increasing with travel. pos_lat = (direction * y + I24_Y_OFFSET_FT) * 0.3048: fixed offsets, not the data minimum, so that outliers do not shift the frame and seams stay at fixed positions. The source columns are kept as x_ft, y_ft and mm (vehicle centre).

id is an integer per provider document (id_provider keeps the ObjectId); datum is local time (America/Chicago, timezone-naive). Provider lanes are not delivered (the documentation only gives lateral ranges); lane_gt is not set.

Parameters:

Name Type Description Default
source Path | str | DataFrame

Parquet file of the sample, or the sample as a DataFrame (not modified).

required
direction int | None

+1 (EB) or -1 (WB); None: the only direction of the sample.

None
x_origin_ft float | None

x [ft] of pos_lon = 0. None: the start of the sample's MM range in the direction of travel (attrs["mm"], miles x 5280), else the extreme x of the data.

None

Returns:

Type Description
GeoDataFrame

Road-aligned RawFrame (trajlab.typing.RawFrame; columns as in "Common output" of

GeoDataFrame

docs/readers.md, geometry (pos_lon, pos_lat) without CRS). Further columns: id_provider,

GeoDataFrame

height [m], the provider positions x_ft / y_ft [ft], the mile marker mm [mi],

GeoDataFrame

flags_provider, n_fragments_provider and, if present in the sample, in_window; attrs

GeoDataFrame

coordinates = "road", source, direction, frame_rate = 25.0, x_origin_ft [ft],

GeoDataFrame

y_offset_ft [ft] and n_lanes = 4.

Raises:

Type Description
ValueError

If direction is None and the sample holds both directions.

read_interaction

read_interaction(path: Path | str, base_timestamp: Timestamp = INTERACTION_BASE_TIMESTAMP) -> gpd.GeoDataFrame

Read one INTERACTION track file (vehicle_tracks_*.csv; Zhan et al. 2019), planar local metres, 10 Hz.

Lanes exist only in the lanelet2/OSM map of the scenario; no lane_gt.

Parameters:

Name Type Description Default
path Path | str

The track CSV.

required
base_timestamp Timestamp

Timestamp of timestamp_ms = 0.

INTERACTION_BASE_TIMESTAMP

Returns:

Type Description
GeoDataFrame

Planar RawFrame (trajlab.typing.RawFrame; columns as in "Common output" of docs/readers.md) in

GeoDataFrame

local coordinates without CRS; attrs["frame_rate"] = 10.0.

read_mona

read_mona(path: Path | str, base_timestamp: Timestamp = MONA_BASE_TIMESTAMP, time_window_s: tuple[float, float] | None = None) -> gpd.GeoDataFrame

Read one MONA file (trajectories.parquet), planar local metres, 25 Hz; INTERACTION-like columns.

Rows whose position is not finite or lies more than MONA_MAX_OFFSET_M from the median position are dropped (corrupt positions would break the principal axis the frame is oriented by).

Parameters:

Name Type Description Default
path Path | str

The parquet file.

required
base_timestamp Timestamp

Timestamp of timestamp_ms = 0.

MONA_BASE_TIMESTAMP
time_window_s tuple[float, float] | None

Optional (t0, t1) in seconds of timestamp_ms [s] to read a part only (t0 <= t < t1).

None

Returns:

Type Description
GeoDataFrame

Planar RawFrame (trajlab.typing.RawFrame; columns as in "Common output" of docs/readers.md) in

GeoDataFrame

local coordinates without CRS; attrs["frame_rate"] = 25.0.

read_ngsim

read_ngsim(path: Path | str, site: str | None = None) -> gpd.GeoDataFrame

Read one NGSIM vehicle-trajectory file (I-80 or US-101), road-aligned, feet -> metres.

Reads the original whitespace-separated trajectories-*.txt or a CSV export with the NGSIM column names. CSV exports with exactly 1 048 575 data rows were truncated by a spreadsheet program; the reader then switches to the .txt file next to it if present (and warns otherwise). Duplicate (Vehicle_ID, Global_Time) rows are dropped.

Local_Y is along the road, Local_X the distance from the left edge (lane 1 = leftmost). lane_gt: provider lanes renumbered from the right (I-80: lanes 1-6 main, 7 on-ramp -> 0; US-101: lanes 1-5 main, 6 auxiliary -> 0, 7/8 ramps -> -1). The provider lanes contain known errors (Coifman & Li 2017). attrs["auxiliary_lane_zones"]: the extent of the auxiliary lane (1-99 % quantiles of its pos_lon, only with at least 100 samples), ready for lanes.auxiliary_lane_zones (without it the auxiliary lane is counted as lane 1 and all lanes shift by one in that section).

Parameters:

Name Type Description Default
path Path | str

.txt (original) or .csv of one 15-minute period.

required
site str | None

"i-80" or "us-101"; None: the first site name contained in the path, else "i-80".

None

Returns:

Type Description
GeoDataFrame

Road-aligned RawFrame (trajlab.typing.RawFrame; columns as in "Common output" of

GeoDataFrame

docs/readers.md, datum from Global_Time [ms]) with lane_gt and lane_provider; attrs

GeoDataFrame

frame_rate = 10.0, n_lanes, site and auxiliary_lane_zones.

read_ngsim_relabelled

read_ngsim_relabelled(path: Path | str, columns: Mapping[str, str] | None = None, time_unit: Literal['D', 's', 'ms', 'us', 'ns'] | None = 'ms', length_unit_m: float = FT, lane_from_left: bool = True, n_main_lanes: int = 6, sep: str | None = None) -> gpd.GeoDataFrame

Read a lane-level re-extraction of NGSIM (e.g. Coifman & Li 2024).

The data are not publicly distributed; available from the authors.

Parameters:

Name Type Description Default
path Path | str

Table with one row per vehicle and time step.

required
columns Mapping[str, str] | None

Mapping of the roles id, time, lon, lat, lane (required) and length, width, class (optional) to the file's column names; defaults to the NGSIM names (NGSIM_RELABELLED_COLUMNS). lat may be missing (lane labels only): pos_lat is then NaN.

None
time_unit Literal['D', 's', 'ms', 'us', 'ns'] | None

Unit of the time column as a pd.to_datetime unit code: "ms" [ms] (NGSIM Global_Time, milliseconds since the Unix epoch), "s" [s], "us" [µs], "ns" [ns] or "D" [d]; None for parseable timestamps.

'ms'
length_unit_m float

Metres per unit of positions and dimensions [m] (feet by default).

FT
lane_from_left bool

Lane numbers count from the left (NGSIM); they are renumbered from the right (lanes above n_main_lanes: n_main_lanes + 1 -> 0, others -1). False: lanes up to n_main_lanes are kept, others -1.

True
n_main_lanes int

Main lanes (I-80: 6).

6
sep str | None

Column separator passed to pd.read_csv (None: separator detected by pandas' sniffer; r"\s+" for whitespace).

None

Returns:

Type Description
GeoDataFrame

Road-aligned RawFrame (trajlab.typing.RawFrame; columns as in "Common output" of

GeoDataFrame

docs/readers.md; class is "Other" without a class column, length NaN without a length column)

GeoDataFrame

with lane_gt (renumbered) and lane_provider; duplicate (id, datum) rows dropped. Without a

GeoDataFrame

lat column a GeoDataFrame without geometry, pos_lon shifted to start at 0 and

GeoDataFrame

attrs["coordinates"] = "labels only". The width role is not read.

Raises:

Type Description
KeyError

If a required column (id, time, lon, lane) is missing.

read_ngsim_reconstructed

read_ngsim_reconstructed(path: Path | str, base_timestamp: Timestamp = NGSIM_RECONSTRUCTED_BASE_TIMESTAMP) -> pd.DataFrame

Read the Montanino-Punzo reconstruction of NGSIM I-80 (RECONSTRUCTED trajectories-*.csv).

Longitudinal only: no lateral position, hence no geometry. For kinematic comparisons only.

Parameters:

Name Type Description Default
path Path | str

The reconstructed CSV.

required
base_timestamp Timestamp

Timestamp of frame 0 (10 Hz frames).

NGSIM_RECONSTRUCTED_BASE_TIMESTAMP

Returns:

Type Description
DataFrame

Plain DataFrame with id, datum, pos_lon [m], speed [km/h] and acceleration [m/s^2] (the

DataFrame

reconstruction's own), length [m], class (canonical), lane_provider and id_front (leader id,

DataFrame

NaN without leader).

read_ute

read_ute(path: Path | str, lanes: Sequence[int] | None = None, lane_gt: Mapping[int, int] | None = None, base_timestamp: Timestamp = UTE_BASE_TIMESTAMP, lane_offsets: Literal['profile', 'constant'] = 'profile', lower_edge: Literal['auto', 'low', 'up'] = 'auto') -> gpd.GeoDataFrame

Read one UTE recording, road-aligned, 30 Hz: a Frenet workbook (frenet-up.xlsx) or a frenet.csv.

The workbook has one sheet per lane. pos_lon from longitudinalDistance along the direction of travel (the sign is taken from the median displacement of the vehicles). pos_lat:

  • workbook: lane k's lower line lies at the sum of the median widths (distanceToUpperLaneLine + distanceToLowerLaneLine per lane) of the lanes below it, plus the vehicle's distance to its lower line;
  • CSV: lateralDistance is the distance to the centre line of the vehicle's lane, so it jumps by a lane width at every lane change; each lane's centre line is placed from those jumps (_ute_lane_offsets).

A file may hold both directions of a road, each with its own laneID range: lanes keeps one of them. lane_gt maps the provider's laneID to the internal lane numbers (1 = rightmost main lane, 0 = auxiliary lane, -1 = neither, e.g. the outer lane of a two-lane ramp); ids it does not name become -1, and pos_lat is then oriented to grow with it (to the left). Without it lane_gt = laneID, assuming lane 1 is the rightmost lane (VERIFY per site). UTE has no classes: vehicles of at least 8 m length are Truck, the others Car (class_provider = "length rule"). Rows without a position or lane are dropped, as are duplicate (vehicleID, time) rows.

Parameters:

Name Type Description Default
path Path | str

The workbook or the CSV.

required
lanes Sequence[int] | None

Provider lane ids to keep (one direction of travel); all when None.

None
lane_gt Mapping[int, int] | None

Provider lane id -> internal lane number.

None
base_timestamp Timestamp

Time origin.

UTE_BASE_TIMESTAMP
lane_offsets Literal['profile', 'constant']

"profile" (default; per 25-m section, interpolated, _ute_lane_profile; removes the steps at lane changes where lane widths vary along the road) or "constant" (one width / offset per lane, as above; the default up to v1.0).

'profile'
lower_edge Literal['auto', 'low', 'up']

Workbook only: the column measured from the lane line on the side of the lower lane ids, "low" (distanceToLowerLaneLine; the default up to v1.0), "up" (on SQM-N-4 the "lower" line lies on the side of the higher lane ids; with "low" the position jumps by two lane widths at every lane change) or "auto" (default: the one with the smaller median step at the lane switches, _ute_switch_step; a warning is logged when the smaller step exceeds UTE_EDGE_AMBIGUOUS = half of the larger one or there are no lane switches, and attrs["lower_edge_auto"] records both steps).

'auto'

Returns:

Type Description
GeoDataFrame

Road-aligned RawFrame (trajlab.typing.RawFrame; columns as in "Common output" of

GeoDataFrame

docs/readers.md) with lane_gt and lane_provider; attrs frame_rate = 30.0, n_lanes

GeoDataFrame

(lanes >= 1 of lane_gt, else the number of provider lanes), lane_widths_m (lane width or centre-line

GeoDataFrame

step per provider lane [m]) and, with lower_edge="auto" on a workbook, lower_edge_auto.

read_dataset

read_dataset(name: str, *args: Any, **kwargs: Any) -> pd.DataFrame

Read one recording of a dataset, dispatching by name.

The name is matched case-insensitively without spaces and hyphens; aliases: rwtha43 -> a43, ngsimreconstructed -> ngsim_reconstructed, ngsimrelabelled / coifmanli -> ngsim_relabelled, dlr -> dlrht, ubiquitoustrafficeyes -> ute, i24 -> i24motion.

Parameters:

Name Type Description Default
name str

Dataset name, a key of DATASETS or an alias.

required
*args Any

Positional arguments of the reader.

()
**kwargs Any

Keyword arguments of the reader.

{}

Returns:

Type Description
DataFrame

The reader's output: a GeoDataFrame, except for ngsim_reconstructed (a plain DataFrame).

Raises:

Type Description
KeyError

If the name is not a known dataset.

RWTH A43 reader (drone, Muenster): road-aligned, 10 Hz, no lane information.

Main function: read_a43.

read_a43

read_a43(path: Path | str, base_timestamp: Timestamp | None = None, time_window_s: tuple[float, float] | None = None) -> gpd.GeoDataFrame

Read one direction file of the RWTH A43 Münster drone data (DroneData*CSV_*.csv), road-aligned.

The files give x along the road in the direction of travel and y across it (positive to the left: heavy vehicles have the smallest y), 10 Hz. No lane information. The time of each row is the first ttimestamp minus its tseconds plus the row's tseconds (rounded to ms).

Parameters:

Name Type Description Default
path Path | str

The CSV file of one direction.

required
base_timestamp Timestamp | None

Not used (ttimestamp gives the absolute time); kept for the common reader signature.

None
time_window_s tuple[float, float] | None

Optional (t0, t1) in tseconds [s] to read a part only (t0 <= t < t1).

None

Returns:

Type Description
GeoDataFrame

Road-aligned RawFrame (trajlab.typing.RawFrame; columns as in "Common output" of

GeoDataFrame

docs/readers.md, pos_lon / pos_lat shifted to start at 0) with class_provider and width

GeoDataFrame

[m]; no lane ground truth. attrs["frame_rate"] = 10.0.

AUTOMATUM reader (planar UTM; lane ground truth from the provider lanes and the OpenDRIVE lane types).

Main functions: read_automatum and automatum_lane_types.

automatum_lane_types

automatum_lane_types(xodr: Path | str) -> dict[tuple[int, int], int]

Map the lanes of an OpenDRIVE file to lane labels in the pipeline convention.

driving lanes are main lanes, numbered per road and side from the right of their direction of travel (the largest |id| of the road and side is 1); ramp lanes (AUTOMATUM_AUX) are 0, all others -1. The centre lane (id 0) is left out.

Parameters:

Name Type Description Default
xodr Path | str

OpenDRIVE file (staticWorld.xodr).

required

Returns:

Type Description
dict[tuple[int, int], int]

Dict (road_id, lane_id) -> lane label.

read_automatum

read_automatum(site_dir: Path | str, time_window_s: tuple[float, float] | None = None, base_timestamp: Timestamp = AUTOMATUM_BASE_TIMESTAMP, cache_dir: Path | str | None = None) -> gpd.GeoDataFrame

Read one Automatum recording (dynamicWorld.json + staticWorld.xodr in site_dir), planar UTM.

The JSON (1.5-3.6 GB) is loaded completely (about 10 s and 10-30 GB of memory). Positions x_vec/y_vec are relative to the UTM-ReferencePoint; the dataset's kinematics are not used. lane_gt from the provider's lane_id_vec / road_id_vec and the lane types of the OpenDRIVE map (automatum_lane_types; -1 where the map is missing or the provider gives no lane).

Parameters:

Name Type Description Default
site_dir Path | str

Folder of one recording.

required
time_window_s tuple[float, float] | None

Optional (t0, t1) [s] of the recording time (t0 <= t < t1).

None
base_timestamp Timestamp

Timestamp of recording time 0.

AUTOMATUM_BASE_TIMESTAMP
cache_dir Path | str | None

If given, the parsed recording (whole, without time_window_s) is kept as <cache_dir>/<folder>_raw.parquet and read from there the next time (the JSON costs 10-30 GB of memory). Defaults to None.

None

Returns:

Name Type Description
GeoDataFrame

Planar RawFrame (trajlab.typing.RawFrame; columns as in "Common output" of docs/readers.md) in

EPSG GeoDataFrame

326xx of the UTM zone of the reference point (default zone 32); id is the object index. Further

columns GeoDataFrame

uuid, utm_x / utm_y [m] and road_provider. attrs["frame_rate"] = 29.97.

Shared reader conventions: canonical vehicle classes, road-aligned and planar frames, reference lines.

Every reader returns SI units, a road-related frame (pos_lon along travel, pos_lat to the left), lane IDs 0 = auxiliary / ramp lane, 1 = rightmost main lane, -1 = not assigned, and canonical classes (CANONICAL) which conventions groups into HGV and motorcycles.

All readers follow one pattern: read the dataset's files, rename the columns to the trajlab.conventions names and convert the units (the dataset-specific part, in the reader module), then build the output frame with its attrs (shared, here).

Main functions: canonical_class and reference_line; the frame builders _road_frame, _road_frame_unshifted and _planar_frame (with _orientation) are shared by the readers.

canonical_class

canonical_class(label: object) -> str

Map a dataset class label to a canonical class.

Parameters:

Name Type Description Default
label object

Provider label (any object; compared as stripped, lower-case string).

required

Returns:

Type Description
str

One of CANONICAL; unknown labels give "Other".

reference_line

reference_line(gdf: GeoDataFrame, direction: int, rms_tolerance_m: float = 0.75) -> LineString | None

Return the reference line of one driving direction of a planar dataset.

The line comes from processing.reference_line.reference_line.estimate_ref_lines (binned median of the longest tracks, smoothing spline); it is computed for both directions and the one of direction is returned.

Parameters:

Name Type Description Default
gdf GeoDataFrame

Planar reader output with geometry, orientation and id.

required
direction int

orientation of the wanted direction: > 0 for +1, otherwise -1.

required
rms_tolerance_m float

Allowed RMS deviation of the spline from the bin medians [m].

0.75

Returns:

Type Description
LineString | None

The reference line in the coordinates of gdf, oriented in the direction of travel, or None if the

LineString | None

direction has no data.

DLR Highway Traffic reader (A39; planar UTM 32N, 20 Hz).

Main functions: dlrht_files and read_dlrht.

dlrht_files

dlrht_files(source: Path | str) -> list[str]

List the trajectory CSV files (5 min each) of the DLR HT dataset.

Parameters:

Name Type Description Default
source Path | str

The dataset zip or the extracted folder.

required

Returns:

Type Description
list[str]

Sorted names: member names inside the zip (.../trajectories/...csv), or paths of the

list[str]

trajectories_*.csv files below the folder.

read_dlrht

read_dlrht(source: Path | str, files: str | Sequence[str], bbox: tuple[float, float, float, float] | None = None) -> gpd.GeoDataFrame

Read the DLR Highway Traffic dataset (A39, 59 roadside poles with 118 cameras; 20 Hz), planar UTM 32N.

Parameters:

Name Type Description Default
source Path | str

The dataset zip (read in place) or the extracted folder.

required
files str | Sequence[str]

One or more trajectory CSV names (dlrht_files), concatenated in time.

required
bbox tuple[float, float, float, float] | None

Optional (min_easting, min_northing, max_easting, max_northing) crop [m]: the corridor is several kilometres long and curved, so a reference line usually needs a section of it.

None

Returns:

Name Type Description
GeoDataFrame

Planar RawFrame (trajlab.typing.RawFrame; columns as in "Common output" of docs/readers.md) in

EPSG GeoDataFrame

32632, datum timezone-naive UTC, class the class with the highest probability of the

GeoDataFrame

classifications_* columns (mapped by DLRHT_CLASSES), length / width from the dimensions;

GeoDataFrame

further columns utm_x / utm_y [m]. Duplicate (id, datum) rows are dropped; the dataset's

GeoDataFrame

velocities and accelerations are not used. attrs["frame_rate"] = 20.0.

exiD reader and lanelet-to-lane ground truth.

The readers return raw positions only (UTM coordinates, time, id, length, width, class) and never the dataset's own speeds or accelerations, so the pipeline processes them like any other recording. Next to the positions they keep the dataset's lane information, from which exid_ground_truth derives a lane label in the pipeline's convention (0 = auxiliary lane, 1 = rightmost main lane, increasing to the left, -1 = not evaluated).

Main functions: read_exid, map_exid_lanes, exid_ground_truth and exid_evaluation_case.

Data locations come from environment variables (never hard-coded): TRAJLAB_EXID_DIR is the root of exiD v2.x (contains data/).

exiD ground truth

exiD gives every sample the lanelet it is on (laneletId; a lanelet is a short piece of one lane from the HD map) and flags lanelet changes that are lane changes (laneChange = 1). The conversion:

  1. Lateral order: along the road, in 10 m bins of pos_lon, every lanelet has a median lateral position. The projected pos_lat is used; the road-edge alignment of Step 2 only shifts each bin as a whole, so the order within a bin is the same as with aligned positions.
  2. Main lanes: per bin, lanelets closer than 1.5 m are one lane, and only the leftmost block of lanes without a gap of more than 6 m is the carriageway (lanes beyond such a gap belong to another road, e.g. a parallel connector, and are not evaluated). The number of main lanes is the lane count of the carriageway found in (almost) every bin (10 % quantile). In each bin the leftmost lanes are the main lanes, numbered from the right (1 = rightmost). A lanelet right of lane 1 within 1.5 lane widths is the auxiliary lane 0; the bins where it exists form the auxiliary-lane zones of the site configuration. Lanelets farther right (ramps that leave the carriageway) are not evaluated (-1). Every lanelet keeps the label it has in most of its bins.
  3. Ambiguity: if two lanelets with different labels overlap laterally (their 10-90 % ranges of pos_lat intersect) in more than 5 % of the bins, the mapping is ambiguous and the recording (direction) is excluded. Directions with fewer than two main lanes (ramps or connectors seen without their carriageway) are excluded as well.

(exiD's laneChange flag would allow chaining lanelets into lanes, but at merges and splits exiD links lanelets of different lanes without a lane change, which merged on-ramps into lane 1; the per-bin order avoids that.)

LaneMapping dataclass

LaneMapping(chain_lane: dict[int, int], lanelet_lane: dict[int, int], n_main_lanes: int, zones: list[dict[str, Any]], ambiguous_share: float, excluded: bool, reason: str = '', profile: DataFrame = pd.DataFrame())

Result of the lanelet-to-lane conversion of one recording and direction.

Attributes:

Name Type Description
chain_lane dict[int, int]

Chain id -> lane label (-1 = not evaluated); map_exid_lanes uses the lanelets as chains, so this equals lanelet_lane.

lanelet_lane dict[int, int]

Lanelet id -> lane label.

n_main_lanes int

Number of main lanes.

zones list[dict[str, Any]]

Auxiliary-lane zones as dicts (lon_start, lon_end [m] in pos_lon, kind).

ambiguous_share float

Share (0-1) of bins with a lateral overlap of two lanelets with different labels.

excluded bool

True if the mapping is ambiguous (share above the limit) or has fewer than two main lanes.

reason str

Why the recording was excluded (empty otherwise). Defaults to "".

profile DataFrame

Per bin and lanelet: bin, chain, median, p10, p90 [m] of pos_lat, n and group (for the validation plot). Defaults to an empty DataFrame.

exid_dir

exid_dir(base_dir: Path | str | None = None) -> Path | None

Return the exiD root folder.

Parameters:

Name Type Description Default
base_dir Path | str | None

exiD root; None: the environment variable TRAJLAB_EXID_DIR.

None

Returns:

Type Description
Path | None

The root as a Path, or None if neither is set or the folder has no data/ subfolder.

exid_recordings

exid_recordings(base_dir: Path | str | None = None) -> pd.DataFrame

Return the recording metadata (recordingMeta) of all exiD recordings with a tracks file.

Parameters:

Name Type Description Default
base_dir Path | str | None

exiD root; None: TRAJLAB_EXID_DIR.

None

Returns:

Type Description
DataFrame

One row per recording with the columns of exiD's *_recordingMeta.csv; empty if exiD is not found.

read_exid

read_exid(recording_id: int, base_dir: Path | str | None = None, base_timestamp: Timestamp = EXID_BASE_TIMESTAMP) -> gpd.GeoDataFrame

Read the raw positions of one exiD recording (no dataset kinematics).

Samples without a lanelet are dropped (a few in recordings 46, 55, 56).

Parameters:

Name Type Description Default
recording_id int

exiD recording number.

required
base_dir Path | str | None

exiD root; defaults to TRAJLAB_EXID_DIR.

None
base_timestamp Timestamp

Timestamp of frame 0 (exiD gives no absolute time).

EXID_BASE_TIMESTAMP

Returns:

Type Description
GeoDataFrame

GeoDataFrame in EPSG:25832 with id, datum, utm_x, utm_y [m], geometry (bounding-box

GeoDataFrame

centre), length / width [m], class (exiD label), orientation (+1 / -1: sign of the track

GeoDataFrame

displacement along the principal axis of all positions), lanelet_id and lanelet_lane_change (exiD

GeoDataFrame

laneChange); attrs recording_id, location_id and frame_rate.

Raises:

Type Description
FileNotFoundError

If the exiD root is not found.

lanelet_chains

lanelet_chains(df: DataFrame) -> dict[int, int]

Map every lanelet to a chain id: lanelets joined by lanelet changes without lane change (union-find).

Parameters:

Name Type Description Default
df DataFrame

read_exid rows with id, datum, lanelet_id and lanelet_lane_change.

required

Returns:

Type Description
dict[int, int]

Dict lanelet id -> chain id (the smallest lanelet id of the chain).

map_exid_lanes

map_exid_lanes(projected: DataFrame, bin_m: float = 10.0, min_points: int = 20, main_quantile: float = 0.1, max_ambiguous_share: float = 0.05, aux_max_offset_lanes: float = 1.5, same_lane_gap_m: float = 1.5, max_lane_gap_m: float = 6.0) -> LaneMapping

Derive lane labels from exiD lanelets for one direction (see the module docstring).

Per bin, the lanelets present (at least min_points samples) are ordered by their median lateral position. The number of main lanes is a low quantile (main_quantile) of the lane count of the carriageway per bin, i.e. the lanes present along (almost) the whole section. In every bin the n_main leftmost lanes are the main lanes n_main ... 1; a lanelet right of lane 1 is the auxiliary lane 0 if its median lies less than aux_max_offset_lanes lane widths right of lane 1, else it is not evaluated (-1, a ramp leaving the carriageway). Each lanelet finally gets the label it has in most of its bins.

Parameters:

Name Type Description Default
projected DataFrame

Rows of one direction with pos_lon, pos_lat [m] (projected, aligned or not) and lanelet_id.

required
bin_m float

Bin length along pos_lon [m].

10.0
min_points int

Minimum samples of a lanelet in a bin.

20
main_quantile float

Quantile (0-1) of the carriageway lane count per bin taken as the number of main lanes.

0.1
max_ambiguous_share float

Maximum share (0-1) of bins with a lateral overlap of two lanelets with different labels.

0.05
aux_max_offset_lanes float

Maximum distance of an auxiliary lanelet right of lane 1, in lane widths (the median spacing of the main lanes, 3.75 m with a single main lane).

1.5
same_lane_gap_m float

Lanelets of one bin whose medians are closer than this [m] are pieces of the same lane (predecessor and successor meeting inside the bin).

1.5
max_lane_gap_m float

Lanes farther apart than this [m] belong to different roads; only the leftmost block of adjacent lanes is the carriageway, lanes beyond the gap are not evaluated.

6.0

Returns:

Type Description
LaneMapping

A LaneMapping (chain_lane holds the lanelet labels too). The first and last bin are left out

LaneMapping

(points beyond the ends of the reference line are projected onto them). Without enough samples: an

LaneMapping

excluded mapping with n_main_lanes = 0 and ambiguous_share = NaN.

exid_ground_truth

exid_ground_truth(out: DataFrame, mapping: LaneMapping) -> pd.DataFrame

Return the lane ground truth for the rows of a pipeline output (needs lanelet_id carried through).

Rows whose lanelet is not evaluated, or that lie in an auxiliary lanelet outside every zone (only checked if out has pos_lon), get -1.

Parameters:

Name Type Description Default
out DataFrame

Rows with id, datum, lanelet_id and optionally pos_lon [m].

required
mapping LaneMapping

Result of map_exid_lanes for the same recording and direction.

required

Returns:

Type Description
DataFrame

DataFrame with id, datum and lane_gt, one row per row of out.

exid_evaluation_case

exid_evaluation_case(recording_id: int, direction: int, base_dir: Path | str | None = None, ref_smoothing: float = 1.0, min_evaluated_share: float = 0.5, min_samples: int = 50) -> dict[str, Any]

Assemble everything needed to evaluate the pipeline on one exiD recording and direction.

The reference line comes from estimate_ref_lines(..., rms_tolerance_m=sqrt(ref_smoothing)) (default 1, i.e. an RMS deviation of about 1 m from the binned median trajectory; looser settings are too loose for the short, curved exiD sections). The input is cropped to the carriageway, as a user of a single-carriageway pipeline would crop the recording: only samples on an evaluated lane (main lanes, auxiliary lane inside its zone) are kept, of vehicles with at least min_evaluated_share of their samples there and at least min_samples samples left. Samples on ramps beyond the gore or on a parallel road would otherwise pull the road-edge alignment of Step 2. If the first mapping is not excluded, the reference line, the mapping and the crop are computed a second time from the carriageway samples only.

Parameters:

Name Type Description Default
recording_id int

exiD recording.

required
direction int

+1 or -1 (orientation of read_exid).

required
base_dir Path | str | None

exiD root; defaults to TRAJLAB_EXID_DIR.

None
ref_smoothing float

Square of the RMS tolerance [m^2] of the reference line (see above).

1.0
min_evaluated_share float

Minimum share (0-1) of evaluated samples per vehicle.

0.5
min_samples int

Minimum evaluated samples per vehicle.

50

Returns:

Type Description
dict[str, Any]

Dict with gdf (cropped raw input), ref_line, mapping (LaneMapping), config (nested

dict[str, Any]

site-config dict: n_main_lanes and auxiliary-lane zones from the mapping), vehicles_dropped and

dict[str, Any]

recording / location / direction ("pos" or "neg").

highD reader (ika, drone, Germany): one driving direction, road-aligned, with lane ground truth.

Main function: read_highd.

read_highd

read_highd(recording: int, source: Path | str, direction: int, base_timestamp: Timestamp = HIGHD_BASE_TIMESTAMP) -> gpd.GeoDataFrame

Read one driving direction of a highD recording (Krajewski et al. 2018), road-aligned.

Positions are the bounding-box centres; pos_lon grows in the direction of travel and pos_lat to its left (direction 2: pos_lon = x, pos_lat = -y; direction 1: pos_lon = -x, pos_lat = y; both then shifted to start at 0). The time of frame k is base_timestamp + recording days + k / frameRate, so recordings do not overlap in time.

Parameters:

Name Type Description Default
recording int

Recording number (1-60).

required
source Path | str

The highD zip (read in place) or the folder containing data/.

required
direction int

highD drivingDirection (1: upper half, moving to -x; 2: lower half, moving to +x).

required
base_timestamp Timestamp

Timestamp of frame 0 of recording 0 (highD gives none).

HIGHD_BASE_TIMESTAMP

Returns:

Type Description
GeoDataFrame

Road-aligned RawFrame (trajlab.typing.RawFrame; columns as in "Common output" of

GeoDataFrame

docs/readers.md) with lane_gt from highD's laneId and lane_provider; attrs

GeoDataFrame

recording, direction, frame_rate and n_lanes (from the lane markings).

I-24 MOTION reader (road-aligned, 25 Hz; feet to metres, back point to centre).

Main function: read_i24motion.

read_i24motion

read_i24motion(source: Path | str | DataFrame, direction: int | None = None, x_origin_ft: float | None = None) -> gpd.GeoDataFrame

Read one driving direction of an I-24 MOTION sample (Gloudemans et al. 2023), road-aligned, 25 Hz.

source is a sample cut from the I-24 MOTION trajectory documents (parquet or DataFrame: one row per point with id (provider ObjectId), t (Unix s), x, y (ft) and the document attributes direction, length_ft, width_ft, height_ft, coarse_class, flags, n_fragments; optionally in_window and attrs["mm"], the mile-marker range of the sample).

Coordinates: I-24 roadway coordinates are already road-aligned (x along the median spline, MM 60 = 316 800 ft; y perpendicular, negative EB, positive WB; data documentation v1.x). x_position is the back centre of the vehicle; the reader moves it to the vehicle centre (+ direction * length / 2), the reference of the other readers. pos_lon = direction * (x_centre - x_origin_ft) * 0.3048, increasing with travel. pos_lat = (direction * y + I24_Y_OFFSET_FT) * 0.3048: fixed offsets, not the data minimum, so that outliers do not shift the frame and seams stay at fixed positions. The source columns are kept as x_ft, y_ft and mm (vehicle centre).

id is an integer per provider document (id_provider keeps the ObjectId); datum is local time (America/Chicago, timezone-naive). Provider lanes are not delivered (the documentation only gives lateral ranges); lane_gt is not set.

Parameters:

Name Type Description Default
source Path | str | DataFrame

Parquet file of the sample, or the sample as a DataFrame (not modified).

required
direction int | None

+1 (EB) or -1 (WB); None: the only direction of the sample.

None
x_origin_ft float | None

x [ft] of pos_lon = 0. None: the start of the sample's MM range in the direction of travel (attrs["mm"], miles x 5280), else the extreme x of the data.

None

Returns:

Type Description
GeoDataFrame

Road-aligned RawFrame (trajlab.typing.RawFrame; columns as in "Common output" of

GeoDataFrame

docs/readers.md, geometry (pos_lon, pos_lat) without CRS). Further columns: id_provider,

GeoDataFrame

height [m], the provider positions x_ft / y_ft [ft], the mile marker mm [mi],

GeoDataFrame

flags_provider, n_fragments_provider and, if present in the sample, in_window; attrs

GeoDataFrame

coordinates = "road", source, direction, frame_rate = 25.0, x_origin_ft [ft],

GeoDataFrame

y_offset_ft [ft] and n_lanes = 4.

Raises:

Type Description
ValueError

If direction is None and the sample holds both directions.

I-24 MOTION day files and corridor: a time window of a day file, a fixed origin and the corridor's zones.

Main functions: read_i24motion_day (one time window of a provider day file into time-bucketed parquet files) and read_i24motion_corridor (a window or sample through read_i24motion, with a fixed origin and the auxiliary-lane zones of the corridor site files).

Coordinates (I-24 MOTION data documentation v1.x, section "Roadway coordinates"): x runs along a spline of the median in feet, increasing eastbound, offset so that MM 60 is exactly 5280 x 60 = 316 800 ft; other mile markers are approximately x / 5280. y is perpendicular to it, negative on EB and positive on WB. x_position and y_position are the back centre of the vehicle.

read_i24motion_day

read_i24motion_day(day_file: Path | str, start: str | Timestamp, end: str | Timestamp, *, out_dir: Path | str, direction: int | None = None, margin_s: float = 30.0, bucket_s: float = 60.0, order_lag_s: float | None = I24_ORDER_LAG_S) -> Path

Read one time window of an I-24 MOTION day file into time-bucketed parquet files (Gloudemans et al. 2023).

The day file of INCEPTION v1.0 (e.g. 11-22-2022.zip, about 6 GB) holds a zip with one JSON array of about 18 GB, one document per trajectory fragment. It is streamed without unpacking, with the standard library only: the documents are split at the provider's layout (a closing brace at the start of a line), a document is parsed only if it overlaps the window, and reading stops once every later document must lie after the window.

Kept: the documents of direction whose time span overlaps [start, end), with their points in [start - margin_s, end + margin_s). They are written to out_dir as one parquet file per bucket_s (named after the local start time of the bucket, e.g. 2022-11-22T07-30-00.parquet; a fragment spanning buckets is split over them), in the sample format of read_i24motion with the column in_window (point in [start, end)). _window.json in out_dir records the window and marks it complete; a second call with the same arguments returns at once.

The file is not ordered by time. Reading stops when, in each direction read, the largest first_timestamp seen exceeds end + order_lag_s; on 2022-11-22 no document lay more than 45 min behind that maximum (I24_ORDER_LAG_S). order_lag_s=None reads the whole file.

Parameters:

Name Type Description Default
day_file Path | str

The provider's day archive (zip with an inner zip holding the .json array), or the inner zip.

required
start str | Timestamp

Start of the window, local time (America/Chicago), e.g. "2022-11-22 07:30".

required
end str | Timestamp

End of the window (excluded), local time.

required
out_dir Path | str

Folder for the bucket files; created if missing. It must be empty or hold the same window.

required
direction int | None

+1 (EB) or -1 (WB); None keeps both.

None
margin_s float

Time [s] kept before start and after end of the selected fragments, so that the kinematics and the lane tracking have context at the window ends.

30.0
bucket_s float

Length of a time bucket [s].

60.0
order_lag_s float | None

Largest delay [s] of a document behind the latest first_timestamp of its direction that the stop rule allows; None reads the whole file.

I24_ORDER_LAG_S

Returns:

Type Description
Path

out_dir, the source for read_i24motion_corridor.

Raises:

Type Description
ValueError

If end is not after start, direction is not +1, -1 or None, out_dir holds another window or bucket files without _window.json, or a document of the day file cannot be parsed (the file is not in the provider's layout).

FileNotFoundError

If day_file does not exist.

ImportError

If pyarrow is not installed (extra readers).

read_i24motion_corridor

read_i24motion_corridor(source: Path | str | DataFrame, direction: int | None = None, x_origin_ft: float | None = None) -> gpd.GeoDataFrame

Read one direction of I-24 MOTION (Gloudemans et al. 2023) with a fixed origin and the corridor's zones.

source is a folder written by read_i24motion_day, a parquet file or a DataFrame in the sample format of read_i24motion, which does the reading. Differences to it:

  • pos_lon starts at the fixed origin I24_ORIGIN_MM of the direction (miles x 5280 ft), the upstream end of the corridor, not at the data, so that the zones of the site files apply to every window;
  • the number of main lanes and the auxiliary-lane zones of the corridor site file (I24_SITES), converted to pos_lon with the same origin, are stored in attrs; trajlab.site_config_from_attrs turns them into the site settings of a run.

Parameters:

Name Type Description Default
source Path | str | DataFrame

Folder of read_i24motion_day, parquet file of a sample, or the sample as a DataFrame (not modified).

required
direction int | None

+1 (EB) or -1 (WB); None: the only direction of the source.

None
x_origin_ft float | None

x [ft] of pos_lon = 0. None: I24_ORIGIN_MM of the direction. With another origin the zones move with it.

None

Returns:

Type Description
GeoDataFrame

The RawFrame of read_i24motion with the further attrs site, n_lanes (from the site file),

GeoDataFrame

auxiliary_lane_zones (dicts of AuxLaneZone) and, for a folder of read_i24motion_day, window

GeoDataFrame

(its _window.json).

Raises:

Type Description
ValueError

If direction is None and the source holds both directions, or a folder holds no parquet file.

read_i24motion_zones

read_i24motion_zones(direction: int, *, x_origin_ft: float | None = None) -> pd.DataFrame

Return the auxiliary-lane zones of the I-24 MOTION corridor in one direction, in mile markers and pos_lon.

The zones of the site file (I24_SITES; zone_mm, visible_from_mm, lane_end_mm in miles, in the direction of travel) are converted with compute_i24motion_pos_lon.

Parameters:

Name Type Description Default
direction int

+1 (EB) or -1 (WB).

required
x_origin_ft float | None

x [ft] of pos_lon = 0; None: I24_ORIGIN_MM of the direction.

None

Returns:

Type Description
DataFrame

One row per zone, in the order of the site file: name, kind (an AuxLaneZone kind), mm_start,

DataFrame

mm_end [mi] (zone_mm, upstream end first), lon_start, lon_end [m] (``lon_start <

DataFrame

lon_end),visible_from_lonandlane_end_lon`` [m] (NaN where the site file has no such key).

Raises:

Type Description
KeyError

If direction is not +1 or -1.

compute_i24motion_pos_lon

compute_i24motion_pos_lon(mm: float | ndarray, direction: int, *, x_origin_ft: float | None = None) -> np.ndarray

Convert I-24 MOTION mile markers to pos_lon of read_i24motion_corridor.

pos_lon = direction * (mm * 5280 - x_origin_ft) * 0.3048, with MM 60 = 316 800 ft (data documentation v1.x).

Parameters:

Name Type Description Default
mm float | ndarray

Mile marker(s) [mi].

required
direction int

+1 (EB) or -1 (WB).

required
x_origin_ft float | None

x [ft] of pos_lon = 0; None: I24_ORIGIN_MM of the direction.

None

Returns:

Type Description
ndarray

pos_lon [m], an array of the shape of mm (0-d for a scalar).

compute_i24motion_mm

compute_i24motion_mm(pos_lon: float | ndarray | Series, direction: int, *, x_origin_ft: float | None = None) -> np.ndarray

Convert pos_lon of read_i24motion_corridor back to mile markers (compute_i24motion_pos_lon inverted).

Parameters:

Name Type Description Default
pos_lon float | ndarray | Series

Longitudinal position(s) [m].

required
direction int

+1 (EB) or -1 (WB).

required
x_origin_ft float | None

x [ft] of pos_lon = 0; None: I24_ORIGIN_MM of the direction.

None

Returns:

Type Description
ndarray

Mile marker(s) [mi], an array of the shape of pos_lon (0-d for a scalar).

read_i24motion_window

read_i24motion_window(folder: Path | str, direction: int) -> pd.DataFrame

Read a window of read_i24motion_day for the stitching: one direction, WINDOW_COLUMNS, no geometry.

The rows and values of these columns are those of read_i24motion_corridor (same conversions, same order): the bucket files are read with a filter on the direction and only the source columns that the conversion needs; the class names come from a lookup per class code instead of per row.

Parameters:

Name Type Description Default
folder Path | str

Folder of read_i24motion_day.

required
direction int

+1 (EB) or -1 (WB).

required

Returns:

Type Description
DataFrame

The positions of direction with WINDOW_COLUMNS and the attrs of read_i24motion_corridor.

Raises:

Type Description
ValueError

If the folder holds no parquet file.

ImportError

If pyarrow is not installed (extra readers).

INTERACTION reader (DR_CHN_Merging_ZS; planar frame, lanes from the lanelet map).

Main function: read_interaction; _read_interaction_like is shared with the MONA reader.

read_interaction

read_interaction(path: Path | str, base_timestamp: Timestamp = INTERACTION_BASE_TIMESTAMP) -> gpd.GeoDataFrame

Read one INTERACTION track file (vehicle_tracks_*.csv; Zhan et al. 2019), planar local metres, 10 Hz.

Lanes exist only in the lanelet2/OSM map of the scenario; no lane_gt.

Parameters:

Name Type Description Default
path Path | str

The track CSV.

required
base_timestamp Timestamp

Timestamp of timestamp_ms = 0.

INTERACTION_BASE_TIMESTAMP

Returns:

Type Description
GeoDataFrame

Planar RawFrame (trajlab.typing.RawFrame; columns as in "Common output" of docs/readers.md) in

GeoDataFrame

local coordinates without CRS; attrs["frame_rate"] = 10.0.

MONA reader (Munich, 25 Hz; planar local metres; corrupt positions dropped).

Main function: read_mona.

read_mona

read_mona(path: Path | str, base_timestamp: Timestamp = MONA_BASE_TIMESTAMP, time_window_s: tuple[float, float] | None = None) -> gpd.GeoDataFrame

Read one MONA file (trajectories.parquet), planar local metres, 25 Hz; INTERACTION-like columns.

Rows whose position is not finite or lies more than MONA_MAX_OFFSET_M from the median position are dropped (corrupt positions would break the principal axis the frame is oriented by).

Parameters:

Name Type Description Default
path Path | str

The parquet file.

required
base_timestamp Timestamp

Timestamp of timestamp_ms = 0.

MONA_BASE_TIMESTAMP
time_window_s tuple[float, float] | None

Optional (t0, t1) in seconds of timestamp_ms [s] to read a part only (t0 <= t < t1).

None

Returns:

Type Description
GeoDataFrame

Planar RawFrame (trajlab.typing.RawFrame; columns as in "Common output" of docs/readers.md) in

GeoDataFrame

local coordinates without CRS; attrs["frame_rate"] = 25.0.

NGSIM reader (I-80, US-101; feet to metres, provider lanes renumbered from the right).

Main functions: read_ngsim (original data), read_ngsim_relabelled (lane-level re-extraction) and read_ngsim_reconstructed (Montanino-Punzo reconstruction, longitudinal only).

read_ngsim

read_ngsim(path: Path | str, site: str | None = None) -> gpd.GeoDataFrame

Read one NGSIM vehicle-trajectory file (I-80 or US-101), road-aligned, feet -> metres.

Reads the original whitespace-separated trajectories-*.txt or a CSV export with the NGSIM column names. CSV exports with exactly 1 048 575 data rows were truncated by a spreadsheet program; the reader then switches to the .txt file next to it if present (and warns otherwise). Duplicate (Vehicle_ID, Global_Time) rows are dropped.

Local_Y is along the road, Local_X the distance from the left edge (lane 1 = leftmost). lane_gt: provider lanes renumbered from the right (I-80: lanes 1-6 main, 7 on-ramp -> 0; US-101: lanes 1-5 main, 6 auxiliary -> 0, 7/8 ramps -> -1). The provider lanes contain known errors (Coifman & Li 2017). attrs["auxiliary_lane_zones"]: the extent of the auxiliary lane (1-99 % quantiles of its pos_lon, only with at least 100 samples), ready for lanes.auxiliary_lane_zones (without it the auxiliary lane is counted as lane 1 and all lanes shift by one in that section).

Parameters:

Name Type Description Default
path Path | str

.txt (original) or .csv of one 15-minute period.

required
site str | None

"i-80" or "us-101"; None: the first site name contained in the path, else "i-80".

None

Returns:

Type Description
GeoDataFrame

Road-aligned RawFrame (trajlab.typing.RawFrame; columns as in "Common output" of

GeoDataFrame

docs/readers.md, datum from Global_Time [ms]) with lane_gt and lane_provider; attrs

GeoDataFrame

frame_rate = 10.0, n_lanes, site and auxiliary_lane_zones.

read_ngsim_relabelled

read_ngsim_relabelled(path: Path | str, columns: Mapping[str, str] | None = None, time_unit: Literal['D', 's', 'ms', 'us', 'ns'] | None = 'ms', length_unit_m: float = FT, lane_from_left: bool = True, n_main_lanes: int = 6, sep: str | None = None) -> gpd.GeoDataFrame

Read a lane-level re-extraction of NGSIM (e.g. Coifman & Li 2024).

The data are not publicly distributed; available from the authors.

Parameters:

Name Type Description Default
path Path | str

Table with one row per vehicle and time step.

required
columns Mapping[str, str] | None

Mapping of the roles id, time, lon, lat, lane (required) and length, width, class (optional) to the file's column names; defaults to the NGSIM names (NGSIM_RELABELLED_COLUMNS). lat may be missing (lane labels only): pos_lat is then NaN.

None
time_unit Literal['D', 's', 'ms', 'us', 'ns'] | None

Unit of the time column as a pd.to_datetime unit code: "ms" [ms] (NGSIM Global_Time, milliseconds since the Unix epoch), "s" [s], "us" [µs], "ns" [ns] or "D" [d]; None for parseable timestamps.

'ms'
length_unit_m float

Metres per unit of positions and dimensions [m] (feet by default).

FT
lane_from_left bool

Lane numbers count from the left (NGSIM); they are renumbered from the right (lanes above n_main_lanes: n_main_lanes + 1 -> 0, others -1). False: lanes up to n_main_lanes are kept, others -1.

True
n_main_lanes int

Main lanes (I-80: 6).

6
sep str | None

Column separator passed to pd.read_csv (None: separator detected by pandas' sniffer; r"\s+" for whitespace).

None

Returns:

Type Description
GeoDataFrame

Road-aligned RawFrame (trajlab.typing.RawFrame; columns as in "Common output" of

GeoDataFrame

docs/readers.md; class is "Other" without a class column, length NaN without a length column)

GeoDataFrame

with lane_gt (renumbered) and lane_provider; duplicate (id, datum) rows dropped. Without a

GeoDataFrame

lat column a GeoDataFrame without geometry, pos_lon shifted to start at 0 and

GeoDataFrame

attrs["coordinates"] = "labels only". The width role is not read.

Raises:

Type Description
KeyError

If a required column (id, time, lon, lane) is missing.

read_ngsim_reconstructed

read_ngsim_reconstructed(path: Path | str, base_timestamp: Timestamp = NGSIM_RECONSTRUCTED_BASE_TIMESTAMP) -> pd.DataFrame

Read the Montanino-Punzo reconstruction of NGSIM I-80 (RECONSTRUCTED trajectories-*.csv).

Longitudinal only: no lateral position, hence no geometry. For kinematic comparisons only.

Parameters:

Name Type Description Default
path Path | str

The reconstructed CSV.

required
base_timestamp Timestamp

Timestamp of frame 0 (10 Hz frames).

NGSIM_RECONSTRUCTED_BASE_TIMESTAMP

Returns:

Type Description
DataFrame

Plain DataFrame with id, datum, pos_lon [m], speed [km/h] and acceleration [m/s^2] (the

DataFrame

reconstruction's own), length [m], class (canonical), lane_provider and id_front (leader id,

DataFrame

NaN without leader).

UTE reader (Ubiquitous Traffic Eyes; Frenet CSV or XLSX, lane offsets and lower edge options).

Main function: read_ute; the helpers place the provider's lane-relative lateral positions in one common frame.

read_ute

read_ute(path: Path | str, lanes: Sequence[int] | None = None, lane_gt: Mapping[int, int] | None = None, base_timestamp: Timestamp = UTE_BASE_TIMESTAMP, lane_offsets: Literal['profile', 'constant'] = 'profile', lower_edge: Literal['auto', 'low', 'up'] = 'auto') -> gpd.GeoDataFrame

Read one UTE recording, road-aligned, 30 Hz: a Frenet workbook (frenet-up.xlsx) or a frenet.csv.

The workbook has one sheet per lane. pos_lon from longitudinalDistance along the direction of travel (the sign is taken from the median displacement of the vehicles). pos_lat:

  • workbook: lane k's lower line lies at the sum of the median widths (distanceToUpperLaneLine + distanceToLowerLaneLine per lane) of the lanes below it, plus the vehicle's distance to its lower line;
  • CSV: lateralDistance is the distance to the centre line of the vehicle's lane, so it jumps by a lane width at every lane change; each lane's centre line is placed from those jumps (_ute_lane_offsets).

A file may hold both directions of a road, each with its own laneID range: lanes keeps one of them. lane_gt maps the provider's laneID to the internal lane numbers (1 = rightmost main lane, 0 = auxiliary lane, -1 = neither, e.g. the outer lane of a two-lane ramp); ids it does not name become -1, and pos_lat is then oriented to grow with it (to the left). Without it lane_gt = laneID, assuming lane 1 is the rightmost lane (VERIFY per site). UTE has no classes: vehicles of at least 8 m length are Truck, the others Car (class_provider = "length rule"). Rows without a position or lane are dropped, as are duplicate (vehicleID, time) rows.

Parameters:

Name Type Description Default
path Path | str

The workbook or the CSV.

required
lanes Sequence[int] | None

Provider lane ids to keep (one direction of travel); all when None.

None
lane_gt Mapping[int, int] | None

Provider lane id -> internal lane number.

None
base_timestamp Timestamp

Time origin.

UTE_BASE_TIMESTAMP
lane_offsets Literal['profile', 'constant']

"profile" (default; per 25-m section, interpolated, _ute_lane_profile; removes the steps at lane changes where lane widths vary along the road) or "constant" (one width / offset per lane, as above; the default up to v1.0).

'profile'
lower_edge Literal['auto', 'low', 'up']

Workbook only: the column measured from the lane line on the side of the lower lane ids, "low" (distanceToLowerLaneLine; the default up to v1.0), "up" (on SQM-N-4 the "lower" line lies on the side of the higher lane ids; with "low" the position jumps by two lane widths at every lane change) or "auto" (default: the one with the smaller median step at the lane switches, _ute_switch_step; a warning is logged when the smaller step exceeds UTE_EDGE_AMBIGUOUS = half of the larger one or there are no lane switches, and attrs["lower_edge_auto"] records both steps).

'auto'

Returns:

Type Description
GeoDataFrame

Road-aligned RawFrame (trajlab.typing.RawFrame; columns as in "Common output" of

GeoDataFrame

docs/readers.md) with lane_gt and lane_provider; attrs frame_rate = 30.0, n_lanes

GeoDataFrame

(lanes >= 1 of lane_gt, else the number of provider lanes), lane_widths_m (lane width or centre-line

GeoDataFrame

step per provider lane [m]) and, with lower_edge="auto" on a workbook, lower_edge_auto.

Synthetic straight-road scenarios with known ground truth.

The generator builds a straight, eastbound motorway section in EPSG:25832 at an arbitrary round origin, not a real site (ORIGIN), with main lanes 1, 2, ... and an optional auxiliary lane 0 on the right. Vehicles move at constant speed in their lane; selected vehicles perform a lane change with a cosine lateral profile (a long duration gives a slow drift) and/or lateral excursions (out towards a lane boundary and back, also used for aborted lane changes). Because every position is known in closed form, the scenario comes with a ground-truth table for lanes, lane-change crossovers and surrounding vehicles.

The true lane is the lane the driver intends to be in: it switches only when a completed lane change crosses the boundary. Excursions and aborted lane changes keep the lane, even if the vehicle centre briefly passes the boundary.

Used by the tests and by the synthetic evaluation. Main functions: make_scenario, default_scenario and merge_scenario.

Coordinate conventions (the intended conventions of the pipeline):

  • pos_lat > 0 is left of the direction of travel. The road runs along +x, so the UTM northing offset y equals the true lateral position.
  • Lane 0 is the auxiliary lane, lane 1 the rightmost main lane, and lane IDs increase to the left.
  • *_left neighbours are in lane ID + 1, *_right neighbours in lane ID - 1.

Units: positions [m], times [s] after T0, speeds [m/s].

LaneChange dataclass

LaneChange(target_lane: int, t_start: float, duration: float = 4.0)

A lane change with a cosine lateral profile.

Attributes:

Name Type Description
target_lane int

True lane ID after the manoeuvre.

t_start float

Start of the lateral movement in seconds after T0.

duration float

Duration of the lateral movement in seconds. The true crossover (lane boundary passed) is at t_start + duration / 2. Defaults to 4.0.

t_cross property

t_cross: float

Time in seconds after T0 at which the lane boundary is crossed.

Excursion dataclass

Excursion(amplitude: float, t_start: float, duration: float = 4.0)

A lateral excursion without lane change: out by amplitude and back.

The lateral offset is amplitude * sin(pi * tau)^2 for tau from 0 to 1 over duration seconds, i.e. it peaks at t_start + duration / 2. A positive amplitude moves to the left. An aborted lane change is an excursion towards the target lane that turns back before (or shortly after) the boundary.

Attributes:

Name Type Description
amplitude float

Peak lateral offset in metres (positive = left).

t_start float

Start in seconds after T0.

duration float

Duration in seconds. Defaults to 4.0.

offset

offset(t: ndarray) -> np.ndarray

Return the lateral offset of the excursion, a sin² bump over duration.

Parameters:

Name Type Description Default
t ndarray

Times after T0 [s].

required

Returns:

Type Description
ndarray

The lateral offset [m] at each time (0 outside the excursion).

Vehicle dataclass

Vehicle(id: int, lane: int, x0: float, speed: float, length: float = 4.5, vclass: str = 'Car', lane_change: LaneChange | None = None, x_range: tuple[float, float] | None = None, excursions: list[Excursion] = list())

A vehicle moving at constant longitudinal speed.

Attributes:

Name Type Description
id int

Vehicle ID.

lane int

True lane ID at t = 0 (before any lane change).

x0 float

Longitudinal position along the road at t = 0 in metres. May be negative (the vehicle enters the road later).

speed float

Constant longitudinal speed in m/s.

length float

Vehicle length in metres. Defaults to 4.5.

vclass str

Vehicle class label. Defaults to "Car".

lane_change LaneChange | None

Optional lane change. Defaults to None.

x_range tuple[float, float] | None

Optional (x_min, x_max) window [m] outside of which the vehicle is not observed (used for auxiliary-lane traffic). Defaults to None (the whole road).

excursions list[Excursion]

Lateral excursions (no lane change). Defaults to none.

x

x(t: ndarray) -> np.ndarray

Return the longitudinal position at constant speed.

Parameters:

Name Type Description Default
t ndarray

Times after T0 [s].

required

Returns:

Type Description
ndarray

The position along the road [m] at each time.

y

y(t: ndarray) -> np.ndarray

Return the true lateral position: the lane centre, the lane change (cosine profile) and the excursions.

Parameters:

Name Type Description Default
t ndarray

Times after T0 [s].

required

Returns:

Type Description
ndarray

The lateral position [m] at each time.

true_lane

true_lane(t: ndarray) -> np.ndarray

Return the true lane ID; it switches to the target lane at the crossover of a lane change.

Parameters:

Name Type Description Default
t ndarray

Times after T0 [s].

required

Returns:

Type Description
ndarray

The lane ID at each time.

Scenario dataclass

Scenario(gdf: GeoDataFrame, ref_line: LineString, truth: dict[str, DataFrame], vehicles: list[Vehicle] = list())

A generated scenario.

Attributes:

Name Type Description
gdf GeoDataFrame

Raw trajectories with columns id, datum, geometry, length, class, orientation in EPSG:25832.

ref_line LineString

Reference line along the direction of travel.

truth dict[str, DataFrame]

Ground truth, see :func:make_scenario.

vehicles list[Vehicle]

The vehicle specifications used. Defaults to an empty list.

lane_center

lane_center(lane: int, lane_width: float = LANE_WIDTH) -> float

Return the true lateral centre of a lane.

Parameters:

Name Type Description Default
lane int

Lane ID (0 = auxiliary lane, 1 = rightmost main lane).

required
lane_width float

Lane width [m].

LANE_WIDTH

Returns:

Type Description
float

Lateral position [m]; the right edge of the main carriageway is at 0 (the auxiliary lane lies at

float

negative positions).

frame_times

frame_times(duration_s: float, fps: float = 30.0) -> tuple[np.ndarray, pd.DatetimeIndex]

Build the common camera clock.

Parameters:

Name Type Description Default
duration_s float

Recording duration [s].

required
fps float

Frame rate [Hz].

30.0

Returns:

Type Description
ndarray

Tuple (t, datum): times [s after T0] as a float array (round(duration_s * fps) + 1 frames) and

DatetimeIndex

the corresponding timestamps rounded to whole nanoseconds.

make_scenario

make_scenario(vehicles: Sequence[Vehicle], road_length: float = 600.0, duration_s: float = 30.0, fps: float = 30.0, noise_std: float = 0.0, seed: int = 0, truth_times: ndarray | None = None, include_length: bool = True) -> Scenario

Sample the given vehicles on a straight road.

Vehicles observed in fewer than two frames are left out.

Parameters:

Name Type Description Default
vehicles Sequence[Vehicle]

The vehicles (:class:Vehicle).

required
road_length float

Observed road length [m] (x in [0, road_length]). The reference line extends REF_LINE_MARGIN_M beyond both ends, so no point is clamped by the pipeline's projection step.

600.0
duration_s float

Recording duration [s].

30.0
fps float

Sampling rate [Hz].

30.0
noise_std float

Standard deviation of Gaussian noise added to both UTM coordinates [m].

0.0
seed int

Seed for the noise generator.

0
truth_times ndarray | None

Times [s after T0] at which to compute the true neighbours. Defaults to every 2 s.

None
include_length bool

Whether to emit the length column.

True

Returns:

Name Type Description
A Scenario

class:Scenario. truth holds three DataFrames:

Scenario
  • lanes: id, datum, t, lane, x, y for every sample, where x/y are the noise-free road coordinates [m].
Scenario
  • crossovers: id, from_lane, to_lane, direction, t_cross, datum_cross for every lane change (direction is "left" for a move towards a higher lane ID).
Scenario
  • neighbours: id, datum, t, lane, x plus id_<pos> for the six surrounding positions at each of truth_times.

default_scenario

default_scenario(aux_lane_x: tuple[float, float] | None = None, lane_changes: bool = True, noise_std: float = 0.0, seed: int = 0, road_length: float = 600.0, duration_s: float = 30.0, fps: float = 30.0, include_length: bool = True) -> Scenario

Build the standard 3-lane test scenario.

Lanes 1, 2 and 3 carry platoons at 25, 28 and 32 m/s with spacings of 50, 120 and 140 m, so the rightmost lane is the busiest and every 200 m GMM window holds thousands of points. The vehicle in front of and behind each lane changer in the source lane is half a spacing away, and the changer enters the middle of a gap in the target lane, so no two vehicles in the same lane ever come closer than about 20 m.

With lane_changes=True the scenario contains:

  • vehicle 1: lane 1 -> lane 2 ("left"), crossover at t = 10 s;
  • vehicle 2: lane 3 -> lane 2 ("right"), crossover at t = 18 s.

With aux_lane_x=(x_min, x_max) an auxiliary lane (lane 0) is observed between x_min and x_max, carrying a 22 m/s platoon with 40 m spacing (IDs from 900).

Parameters:

Name Type Description Default
aux_lane_x tuple[float, float] | None

Longitudinal range (x_min, x_max) of the auxiliary lane [m], or None.

None
lane_changes bool

Whether to include the two lane changers.

True
noise_std float

Gaussian position noise [m].

0.0
seed int

Noise seed.

0
road_length float

Road length [m].

600.0
duration_s float

Recording duration [s].

30.0
fps float

Sampling rate [Hz].

30.0
include_length bool

Whether to emit the length column.

True

Returns:

Name Type Description
A Scenario

class:Scenario (see :func:make_scenario).

merge_scenario

merge_scenario(aux_lane_x: tuple[float, float] = (150.0, 450.0), x_cross: float = 350.0, road_length: float = 600.0, duration_s: float = 30.0, fps: float = 30.0) -> Scenario

Build a 3-lane road with one vehicle merging from the auxiliary lane.

Lanes 1-3 carry the platoons of :func:default_scenario (without its lane changers). Vehicle 3 drives at the lane-1 speed (25 m/s) in the middle of a lane-1 gap; it is observed from aux_lane_x[0] on (first on the auxiliary lane) and merges into lane 1 ("left", lane 0 -> 1) with its crossover at x_cross (inside the auxiliary section) at t = 12 s. It is therefore never closer than half a lane-1 spacing (25 m) to any vehicle in the same lane. The true neighbours are computed every 0.5 s.

Parameters:

Name Type Description Default
aux_lane_x tuple[float, float]

Longitudinal range of the auxiliary lane in road metres; only its start is used (the merging vehicle is observed from there to the road end).

(150.0, 450.0)
x_cross float

Road position of the merge crossover [m].

350.0
road_length float

Road length [m].

600.0
duration_s float

Recording duration [s].

30.0
fps float

Sampling rate [Hz].

30.0

Returns:

Name Type Description
A Scenario

class:Scenario; vehicle 3 is the merging vehicle.

min_same_lane_gap

min_same_lane_gap(truth_lanes: DataFrame) -> float

Return the smallest centre-to-centre gap between two vehicles in the same true lane at the same instant.

A sanity check for scenario design.

Parameters:

Name Type Description Default
truth_lanes DataFrame

truth["lanes"] of a scenario.

required

Returns:

Type Description
float

Minimum gap [m] (inf if no lane is ever shared).