Code style
trajlab is read by people who want to understand or reuse a method: transport researchers more often than software engineers. Code that users are likely to read or change must be easy to follow; the backend may stay compact.
User-facing: the public API (read_dataset, run_pipeline, the entry points of trajlab.analysis and
trajlab.visualization), the configuration (presets, site and dataset YAML files), the readers, the top level of
the pipeline steps 00–11, and the examples.
Backend: internals of the HMM, the trajectory reconstruction, the stitching cascade and the export tools. The
boundary is a package boundary: backend code lives in private names and in modules and subpackages whose names start
with an underscore (the configuration adapter processing/_config_adapter.py, the configuration sections
config/_sections), and
tests/release/test_package_boundary.py checks that they are used only inside their top-level package.
The guidelines build on PEP 8, PEP 257 and the Google Python Style Guide (docstrings in Google style; see the section Docstrings). Most guidelines have a short example from trajlab: before is code as it was (or still is), after is how new code is written.
1. A small, obvious public API
- Every package has an
__all__; the API reference shows exactly these names. - The quickstart fits in under 20 lines: read a dataset → run the pipeline → get the events → draw one figure.
- The same verb for the same kind of work:
read_(load data),run_(a whole chain),detect_(find events),estimate_(fit a quantity from data),compute_(derive columns),calibrate_(fit model parameters),plot_(draw). - The same parameter order everywhere: data first, then the configuration, then options as keywords only.
# before: "calculate" and "extract" for two kinds of work
sur = calculate_surroundings(df, default_length_m=config.surroundings.default_vehicle_length_m)
intervals = extract_all_lane_changes(df, lat_speed_threshold_mps=lc.lat_speed_threshold_mps)
# after: compute_ derives columns, detect_ finds events
sur = compute_surroundings(df, default_length_m=config.surroundings.default_vehicle_length_m)
intervals = detect_lane_changes(df, lat_speed_threshold_mps=lc.lat_speed_threshold_mps)
2. Deep modules, not shallow ones
A function or class is worth having when it hides more than its interface costs (Ousterhout 2018, ch. 4). Pass-through functions, helpers with a single caller, and abstractions with a single implementation (registries, factories, plugin layers) are folded into their caller until a second real implementation exists.
# before: a method that only forwards to the section that owns the value
class PipelineConfig:
def get_smooth_window_frames(self, fs=None):
return self.kinematics.get_smooth_window_frames(fs)
window = config.get_smooth_window_frames()
# after: callers ask the section that holds the value
window = config.kinematics.get_smooth_window_frames()
3. Functions with one job
- About 50 lines or fewer.
- At most 5–6 parameters; beyond that, a dataclass.
- No boolean switches that change what a function does. Use two functions, or an
Enum/Literal.
# before: one flag changes the return type (and needs four overloads)
raw, truth = trajlab.examples.synthetic_motorway(duration_s=40.0, return_truth=True)
out, events = trajlab.run_pipeline(sub, ref, cfg, return_events=True)
# after: two functions, one return type each
raw = trajlab.examples.synthetic_motorway(duration_s=40.0)
raw, truth = trajlab.examples.synthetic_motorway_with_truth(duration_s=40.0)
out = trajlab.run_pipeline(sub, ref, cfg)
res = trajlab.run_pipeline_detailed(sub, ref, cfg) # a PipelineResult
out, events = res.tracks, res.events
A boolean that only selects a detail of the same job (dropna=True) is fine; a boolean that selects a different
job or result is not.
4. Read the flow from the top
The orchestrator comes first and names its steps with the names of the documentation pages
(docs/pipeline/00–11). The details follow below it, or in modules named after the same pages.
# before: processing/pipeline.py (1530 lines) opened with 26 step functions and helpers;
# the step list followed at line 1080, run_pipeline at line 1358
# after: processing/pipeline.py opens with the step list, one comment per page of docs/pipeline/; each step
# calls the entry function of the subpackage named after its page (reference_line/, perspective/, ...)
PIPELINE_STEPS = (
# 01 reference line and projection
PipelineStep(
name="projection",
requires=(C.GEOMETRY,),
produces=(C.POS_LON, C.POS_LAT),
enabled=lambda cfg: cfg.projection.enabled,
run=_run_projection,
extra_outputs=(C.POS_LON_REF, C.REF_LINE_REVERSED),
),
# 02 perspective correction
PipelineStep(
name="perspective",
requires=(C.POS_LAT,),
produces=(),
enabled=lambda cfg: cfg.perspective.enabled,
run=_run_perspective,
),
..., # 03 alignment, 04 stitching and imputation, 05 kinematics, 06 lanes, 07-09, 10
)
# the entry function of a step calls its sub-steps from the top, one comment line each
def estimate_lane_geometry(tracks, *, params=None, layout=None):
...
# 1. rolling GMM lane tracking
df_labeled, _, centers = estimate_lanes_rolling_tracker(tracks, ...)
# 2. lanes numbered from the right
standardised = collapse_and_standardize_lanes(df_labeled, max_lanes=layout.max_main_lanes())
# 3. lane centers in the standardized numbering, stability diagnostics
...
5. Domain terms, one glossary
The terms are defined in the glossary: leader, follower, gap (net), spacing (gross), time gap, headway, lane change, excursion, merge. One term per thing, in the code as in the documentation.
SI units are the default (m, s, m/s, m/s²). A unit suffix appears only where a name deviates from SI (_kmh,
_deg) or where the unit is not obvious from the term (_m, _s for lengths and durations in event tables).
# before: "headway" for a distance, "clearance" for the net gap
d = row["headway_front"] # center to center [m]
g = row["clearance_front"] # bumper to bumper [m]
# after (new code; the output columns keep their names until 3.0, see the glossary)
spacing_m = row["headway_front"]
gap_m = row["clearance_front"]
time_gap_s = gap_m / v
6. Configuration as a type, not a dict
- Defaults live in one place (the configuration schema and the presets), not in function signatures as well.
- Numbers in code only as named constants with their unit and source.
7. Column names from the schema module
Column names come from trajlab.conventions (and the schemas in trajlab.typing), not from string literals
scattered through the code.
# before
"v": out["speed"].to_numpy(dtype=float) / 3.6,
# after (`from trajlab import conventions as C`)
"v": out[C.SPEED].to_numpy(dtype=float) / C.KMH_PER_MPS,
8. Fail early and clearly
- No blanket
try/except Exception. Where a broadexceptis the honest choice (the process-pool fallback ofdetect_lane_changes: the pool fails in platform-dependent ways), a comment says why. - No checks for states that cannot occur.
- Error messages and warnings say what the user can do.
# before: any error in a GMM fit, a bug included, silently skips the component count
for k in range(1, k_max + 1):
try:
gmm = GaussianMixture(n_components=k, random_state=42)
with warnings.catch_warnings():
warnings.simplefilter("ignore", ConvergenceWarning)
gmm.fit(y_vals_window)
...
except Exception:
continue
# after: only the failure we expect, and why it is expected
for k in range(1, k_max + 1):
try:
gmm = GaussianMixture(n_components=k, random_state=42)
with warnings.catch_warnings():
warnings.simplefilter("ignore", ConvergenceWarning)
gmm.fit(y_vals_window)
...
except ValueError:
# GaussianMixture.fit rejects NaN / infinite lateral positions and ill-defined covariances
# (numpy's LinAlgError is a ValueError); such a component count is skipped.
continue
9. Comments explain why
Comments say why, not what. No comments that repeat the code, and no history (decision numbers, "changed in phase N", who decided). Every formula cites its source.
# before
lowpass_cutoff_hz: float = 0.5 # cut-off of the Butterworth filter (decision 31)
# after
# Montanino & Punzo (2015) use 1.0 Hz; on drone data many 1 s windows then keep more than one jerk sign
# inversion (their criterion 3j), so the cut-off is lowered to 0.5 Hz.
lowpass_cutoff_hz: float = 0.5
10. Lines without riddles
- Split long chained pandas expressions and nested comprehensions into named steps.
- But no extra variables that only rename.
- No deserts of blank lines.
# before
standstill = float(
np.diff(standing["t"]).clip(min=0)[standing["v"].to_numpy()[:-1] * C.KMH_PER_MPS < W.STANDSTILL_KMH].sum()
)
# after
dt = np.diff(standing["t"]).clip(min=0)
is_standing = standing["v"].to_numpy()[:-1] * C.KMH_PER_MPS < W.STANDSTILL_KMH
standstill_s = float(dt[is_standing].sum())
11. Tests as examples
Test names describe the behavior (test_lane_change_ends_in_other_lane), not the task that produced them.
Fixtures are small and named after what they contain.
# before
def test_default_reproduces_d136_bitwise(): ...
# after
def test_default_matches_reference_bitwise(): ...
12. Documentation by kind (Diátaxis)
| kind | purpose | in trajlab |
|---|---|---|
| tutorial | learn by doing | README quickstart, examples/quickstart.py |
| how-to | reach a goal | own dataset (docs/readers.md), own preset (docs/configuration.md) |
| reference | look things up | API reference, docs/configuration.md, docs/output_format.md, glossary |
| explanation | understand | docs/method.md, docs/limitations.md, docs/pipeline/ |
Docstrings
Google style, checked in CI (ruff --select D, pydoclint, interrogate at 100 % for the public API):
- a one-line summary; then what and why, with the source (paper, equation);
Args:with the unit in brackets ([m],[m/s],[m/s²],[s]; dimensionless[-]with its range; window lengths[samples]); column names and flags need no unit;Returns:refers to the schema (TrackFrame,EventFrame,docs/output_format.md) instead of listing columns again;Raises:for every check that raises; an exception raised by a callee is kept, with the callee named, and marked# noqa: DOC502after the closing quotes;- no empty sections; a docstring that only repeats the signature is replaced by the reason.
Sources
- PEP 8, PEP 257; Google Python Style Guide (google.github.io/styleguide/pyguide.html).
- J. Ousterhout (2018). A Philosophy of Software Design. Yaknyam Press.
- G. Wilson, J. Bryan, K. Cranston, J. Kitzes, L. Nederbragt, T. K. Teal (2017). Good enough practices in scientific computing. PLoS Computational Biology 13(6), e1005510. https://doi.org/10.1371/journal.pcbi.1005510
- Scientific Python Development Guide (learn.scientific-python.org/development); Diátaxis (diataxis.fr).