Skip to content

transitlos.scoring

Public API of the transitLOS scoring module: pure math on floats (standard library only).

Re-exports

mrc_score, MR_mode, MR_CV, comfort_score: the mode / reliability / comfort sub-score and its components (mrc.py). mode_category: classifies a GTFS route_type as "rail", "tram" or "bus". mode_score: MR_mode(mode_category(route_type)). speed_score: V(speed) (speed.py). frequency_score: H(headway) (frequency.py). stop_score: the combination of MRC, speed and frequency (stop_score.py). walk_decay: the walk-access decay D(t; stop_score) (walk_access.py). walk_time_for_decay: closed-form inverse of walk_decay. accessibility_score: stop_score * walk_decay(...) = PTLOS (accessibility_score.py).

RegionParameters(weights=(1.0 / 3, 1.0 / 3, 1.0 / 3), walking_speed_mps=1.3, t_plateau_distance_m=200.0, t0_base_minutes=(lambda: {'bus': 6.6, 'rail': 9.4, 'tram': 14.55})(), k_quality=2.5, p_shape=1.0, h_saturation_minutes=5.0, h_elasticity_p=-0.06581572485740672, h_elasticity_q=0.15634627853115843, v_anchor_kmh=30.0, v_ceiling_bonus=0.15, v_shape_n=2.0, mr_mode=(lambda: {'rail': 1.0, 'tram': 0.894, 'bus': 0.8})(), comfort_scores=(lambda: {'EMPTY': 1.0, 'MANY_SEATS_AVAILABLE': 1.0, 'FEW_SEATS_AVAILABLE': 0.85, 'STANDING_ROOM_ONLY': 0.55, 'CRUSHED_STANDING_ROOM_ONLY': 0.4, 'FULL': 0.0, 'NOT_ACCEPTING_PASSENGERS': 0.0})()) dataclass

Container for the scoring model's default parameters.

Attributes:

Name Type Description
weights tuple[float, float, float]

(w_mrc, w_v, w_h) weights of MRC, V and H in stop_score's weighted geometric mean (equal thirds).

walking_speed_mps float

Walking speed, m/s (1.3).

t_plateau_distance_m float

Walk distance (m) at or below which D(t) = 1 whatever the stop score (200 m, ~2.56 min).

t0_base_minutes dict[str, float]

Per-mode base scale (minutes) of D's decay before the (1 + k * stop_score) scaling: bus 6.6, rail 9.4, tram 14.55.

k_quality float

Quality coupling k in t0(stop_score) = t0_base(mode) * (1 + k * stop_score) (2.5).

p_shape float

Shape exponent p in D(t) = (1 + (t - t_plateau) / t0)^(-p) (1.0, all modes).

h_saturation_minutes float

Headway (min) at or below which H(headway) = 1 (5 min).

h_elasticity_p float

Intercept p of the local headway elasticity eps(headway) = p + q * ln(headway).

h_elasticity_q float

Slope q of the same elasticity.

v_anchor_kmh float

Speed (km/h) at which V(v) = M * v^n / (v^n + K^n) equals 1 (30 km/h).

v_ceiling_bonus float

Asymptotic ceiling of V above 1: V -> M = 1 + bonus as v -> infinity (0.15).

v_shape_n float

Hill exponent n of V (2.0: keeps V low near walking speed).

mr_mode dict[str, float]

MR_mode(mode) lookup: rail 1.000, tram / light rail / BRT 0.894, bus 0.800.

comfort_scores dict[str, float]

C(occupancy_status) lookup keyed by GTFS-realtime VehiclePosition.OccupancyStatus (optional, not used by the default pipeline).

build_intelligent_distance_matrix(stop_scores, mode, region='global', max_distance_m=None)

Build a distance_matrix + stop_score-bucket map from transitlos's own decay.

Parameters:

Name Type Description Default
stop_scores Sequence[float]

The distinct (or a representative sample of) stop_score values actually present in the stops being scored, for ONE mode (see module docstring). Only their range matters -- the maximum is used as the reference stop_score for distance-step placement; each stop's own value is used for its own bucket signature.

required
mode str

One of "bus", "rail", "tram" -- selects t0_base for every stop passed here (see mrc.mode_category). All stops passed to one call must share this mode.

required
region str

Region key forwarded to accessibility_score/walk_decay (see parameters.py -- every region uses the same decay-shape defaults unless explicitly overridden).

'global'
max_distance_m float | None

Optional hard outer walk-distance cutoff (meters). Since D(t) is a gentle, asymptotically-declining curve rather than a hard cutoff, its own natural output-tier thresholds can extend arbitrarily far (the lowest 0.05-D0.1 tier's threshold is several kilometers out) -- an isochrone search out to that distance for every stop is expensive and, past some point, not meaningfully different from "no access". When given, any natural threshold beyond max_distance_m is dropped, and max_distance_m itself is appended as the final distance step (its own real, ceiling-discretized D(t) value, not silently truncated to whatever tier happened to fall just under it) so isochrones still search the entire requested radius, just no further.

None

Returns:

Name Type Description
distance_matrix DataFrame

a polars.DataFrame with one row per bucket representative poi_score and one column per str(distance_in_meters), values ceiling-discretized onto the output grid -- directly usable as AccessibilityAnalyzer.run(distance_matrix, poi_score_col=...)'s first argument.

bucket_map dict[float, float]

{original_stop_score: bucket_representative} for every distinct input stop_score -- callers must remap their own stops' score column through this before calling .run(), so the join against distance_matrix["poi_score"] lines up exactly (see level_of_service.py).

distance_steps_m list[float]

the chosen distance thresholds in meters (ascending), for logging/inspection.

ceil_to_grid(value, step=OUTPUT_GRID_STEP)

Ceiling-round a scalar level_of_service onto the {0, step, 2*step, ..., 1.0} grid.

E.g. ceil_to_grid(0.91) == 1.0, ceil_to_grid(0.0) == 0.0, ceil_to_grid(0.30) == 0.3 (exact multiples are not pushed to the next tier -- the small epsilon subtraction guards against float error like 0.3 / 0.1 == 2.9999999999999996 incorrectly ceiling-ing to 0.4).

Parameters:

Name Type Description Default
value float

The raw level_of_service, expected in [0, 1] (any floating-point overshoot just above 1.0 is clipped to the grid's max).

required
step float

Grid spacing. Defaults to OUTPUT_GRID_STEP (0.1).

OUTPUT_GRID_STEP

Returns:

Type Description
float

A float on the grid, clipped to [0.0, 1.0].

ceil_to_grid_array(values, step=OUTPUT_GRID_STEP)

Vectorized ceil_to_grid, for a final safety-net pass over a whole level_of_service column.

Parameters:

Name Type Description Default
values ndarray

Scores.

required
step float

Grid step.

OUTPUT_GRID_STEP

Returns:

Type Description
ndarray

Scores rounded up to the grid, clipped to [0, 1].

frequency_score(headway_minutes, region='global', saturation_minutes=None, elasticity_p=None, elasticity_q=None)

Compute H(headway), a [0, 1] frequency score from a service headway.

Below saturation_minutes (5 min) the score is exactly 1.0. Above it, the score follows the log-linear-elasticity closed form described in the module docstring.

Parameters:

Name Type Description Default
headway_minutes float

Scheduled or average headway in minutes. Must be

= 0.

required
region str

Region key into parameters.REGIONS. Kept for backward compatibility -- every region now shares identical, universal parameters (see parameters.py's module docstring).

'global'
saturation_minutes float | None

Headway (min) at/below which score is 1.0. Defaults to the region's h_saturation_minutes (5.0).

None
elasticity_p float | None

Intercept of eps(headway) = p + q*ln(headway). Defaults to the region's h_elasticity_p.

None
elasticity_q float | None

Slope of the same fit. Defaults to the region's h_elasticity_q.

None

Returns:

Type Description
float

A float in (0, 1]: 1.0 at/below the saturation headway, decaying

float

smoothly (but never reaching exactly 0) as headway grows.

Raises:

Type Description
ValueError

If headway_minutes is negative.

MR_CV(headway_cv)

Compute the optional CV-of-scheduled-headway reliability refinement.

MR_CV(CV) = 1 / (1 + CV^2), the inverse of the average-wait inflation factor (1 + CV^2). MR_CV(0)=1.0, MR_CV(1)=0.5, MR_CV(2)~=0.2. Mode-agnostic by construction; preferred over MR_mode whenever scheduled-headway CV data exists, since it reflects the stop's own actual pattern.

Parameters:

Name Type Description Default
headway_cv float

Coefficient of variation of scheduled headways (stddev / mean), a unitless non-negative number.

required

Returns:

Type Description
float

A float in (0, 1].

Raises:

Type Description
ValueError

If headway_cv is negative.

MR_mode(mode, region='global')

Compute the mode-based categorical default MR_mode(mode).

Rail / subway / metro / commuter rail = 1.000; tram / light rail / BRT = 0.894 (geometric mean of rail and bus); local bus = 0.800.

Parameters:

Name Type Description Default
mode str

One of "rail", "tram", "bus" (see mode_category).

required
region str

Region key into parameters.REGIONS. Kept for backward compatibility -- every region shares identical, universal values.

'global'

Returns:

Type Description
float

A float in (0, 1].

Raises:

Type Description
ValueError

If mode is not one of "rail", "tram", "bus".

comfort_score(occupancy_status, region='global')

Compute the optional comfort/crowding refinement C(occupancy_status).

A categorical lookup keyed to the standardized GTFS-realtime VehiclePosition.OccupancyStatus enum. Defaults to 1.0 (comfort-neutral) when occupancy data is unavailable -- the common case, since this refinement needs GTFS-realtime data this project's pipeline typically does not have.

Parameters:

Name Type Description Default
occupancy_status Optional[str]

One of the GTFS-realtime OccupancyStatus enum string values ("EMPTY", "MANY_SEATS_AVAILABLE", "FEW_SEATS_AVAILABLE", "STANDING_ROOM_ONLY", "CRUSHED_STANDING_ROOM_ONLY", "FULL", "NOT_ACCEPTING_PASSENGERS"), or None if unavailable.

required
region str

Region key into parameters.REGIONS. Kept for backward compatibility -- every region shares identical, universal values.

'global'

Returns:

Type Description
float

A float in [0, 1]. Exactly 1.0 if occupancy_status is None.

Raises:

Type Description
ValueError

If occupancy_status is a string not in the known enum.

mode_category(route_type)

Classify a GTFS route_type into "rail", "tram", or "bus".

Parameters:

Name Type Description Default
route_type Optional[int]

Standard GTFS route_type code (0-7), or None/NaN for a route with no usable route_type -- falls back to "bus".

required

Returns:

Type Description
str

"rail", "tram", or "bus".

mode_score(route_type, region='global')

Compute MR_mode(mode_category(route_type)) directly from a GTFS route_type.

Convenience wrapper combining mode_category + MR_mode.

Parameters:

Name Type Description Default
route_type Optional[int]

GTFS route type.

required
region str

Scoring region.

'global'

Returns:

Type Description
float

The mode value.

mrc_score(route_type=None, headway_cv=None, occupancy_status=None, region='global')

Compute the combined MRC(mode/reliability/comfort) sub-score.

MRC = MR_component * C_component, where MR_component is MR_CV(headway_cv) if headway_cv is supplied (preferred, richer data), else MR_mode(mode_category(route_type)) (the primary, load-bearing GTFS-static-only default); C_component is comfort_score(occupancy_status), defaulting to 1.0 (comfort-neutral) when occupancy_status is None -- the common case, so mrc_score(route_type) == MR_mode(mode_category(route_type)) exactly when no other data is supplied.

Parameters:

Name Type Description Default
route_type Optional[int]

Standard GTFS route_type code, or None. Used only if headway_cv is not supplied.

None
headway_cv Optional[float]

Coefficient of variation of scheduled headways, or None if unavailable. When supplied, takes precedence over route_type for the mode/reliability component.

None
occupancy_status Optional[str]

GTFS-realtime OccupancyStatus enum value, or None if unavailable (the common case; defaults to comfort-neutral).

None
region str

Region key into parameters.REGIONS. Kept for backward compatibility -- every region shares identical, universal values.

'global'

Returns:

Type Description
float

A float in [0, 1] (or up to (0, 1] * (0, 1] -- always <= 1.0 since

float

both components are individually <= 1.0).

speed_score(avg_speed_kmh, region='global', anchor_kmh=None, ceiling_bonus=None, shape_n=None)

Compute V(speed) from average operating speed.

Parameters:

Name Type Description Default
avg_speed_kmh float

Average operating (commercial) speed in km/h -- i.e. distance/time averaged over the whole route, INCLUDING dwell time at stops, not pure between-stops cruising speed. Must be >= 0.

required
region str

Region key into parameters.REGIONS. Kept for backward compatibility -- every region now shares identical, universal parameters (see parameters.py's module docstring).

'global'
anchor_kmh float | None

Speed at which V reaches exactly 1.0. Defaults to the region's v_anchor_kmh (30.0).

None
ceiling_bonus float | None

The curve's asymptotic ceiling above 1.0, approached as avg_speed_kmh -> infinity, never hit at any specific finite speed and NOT pinned to any named high-speed benchmark (an earlier same-day revision tried pinning it to German Regional-Express's speed and was reverted -- see module docstring, Revision 4). Defaults to the region's v_ceiling_bonus (0.15), an explicit design-judgment choice.

None
shape_n float | None

Hill-function exponent controlling how quickly the curve rises below the anchor (higher n => lower scores at low speed). Defaults to the region's v_shape_n (2.0).

None

Returns:

Type Description
float

A float, strictly increasing in avg_speed_kmh, exactly 0.0 only at

float

avg_speed_kmh == 0, asymptotically approaching (but never reaching)

float

1 + ceiling_bonus as avg_speed_kmh -> infinity.

Raises:

Type Description
ValueError

If avg_speed_kmh is negative.

walk_decay(walk_time_minutes, stop_score, mode, region='global', t_plateau_minutes=None, p=None, t0_base_minutes=None, k=None)

Compute the walk-access decay factor D(t; stop_score).

Flat at 1.0 up to t_plateau_minutes, then (1 + (t - t_plateau) / t0(stop_score)) ^ (-p) beyond it, where t0(stop_score) = t0_base(mode) * (1 + k * stop_score) -- see module docstring. PTLOS = stop_score * walk_decay(...) (accessibility_score.accessibility_score computes this product).

Parameters:

Name Type Description Default
walk_time_minutes float

Walking time to the stop, in minutes. Must be

= 0.

required
stop_score float

The stop-level quality score (from stop_score.stop_score). Must be >= 0.

required
mode str

One of "bus", "rail", "tram" -- selects t0_base (see mrc.mode_category). Ignored if t0_base_minutes is passed explicitly.

required
region str

Region key into parameters.REGIONS. Kept for backward compatibility -- every region shares identical, universal parameters.

'global'
t_plateau_minutes float | None

Walk time at/below which D(t)=1.0 exactly. If None, derived from the region's t_plateau_distance_m and walking_speed_mps (200 m -> ~2.56 min at 1.3 m/s).

None
p float | None

Shape parameter. If None, defaults to the region's p_shape (1.0).

None
t0_base_minutes float | None

Per-mode base scale override, forwarded to t0_of_stop_score.

None
k float | None

Quality-coupling constant override, forwarded to t0_of_stop_score.

None

Returns:

Type Description
float

A float in (0, 1]: exactly 1.0 for walk_time_minutes <=

float

t_plateau_minutes, monotonically decreasing and asymptotically

float

approaching (but never reaching) 0 as walk_time_minutes grows

float

beyond it.

Raises:

Type Description
ValueError

If walk_time_minutes or stop_score is negative.

walk_time_for_decay(target_decay, stop_score, mode, region='global', t_plateau_minutes=None, p=None, t0_base_minutes=None, k=None)

Invert walk_decay: the walk time at which D(t; stop_score) == target_decay.

Since p is fixed at 1.0 by default, this remains a closed-form inverse for the default shape parameter (and any other p, since the offset-power form (1+x)^(-p) inverts in closed form for any p != 0); t0 itself already depends on stop_score/mode, which are required inputs here rather than something to additionally solve for. Kept alongside walk_decay so the two never drift out of sync. Used by distance_matrix.build_intelligent_distance_matrix to choose distance thresholds that land exactly on desired output access-score values.

Parameters:

Name Type Description Default
target_decay float

Desired D(t; stop_score) value, in (0, 1]. 1.0 returns t_plateau_minutes (the start of the plateau).

required
stop_score float

The stop-level quality score this curve is being inverted for (must match the walk_decay call being inverted).

required
mode str

One of "bus", "rail", "tram" (must match the walk_decay call being inverted).

required
region str

Same meaning as in walk_decay -- must match the call whose curve is being inverted.

'global'
t_plateau_minutes float | None

Same meaning as in walk_decay -- must match the call whose curve is being inverted.

None
p float | None

Same meaning as in walk_decay -- must match the call whose curve is being inverted.

None
t0_base_minutes float | None

Same meaning as in walk_decay -- must match the call whose curve is being inverted.

None
k float | None

Same meaning as in walk_decay -- must match the call whose curve is being inverted.

None

Returns:

Type Description
float

The walk time (minutes) at which

float

walk_decay(t, stop_score, mode) == target_decay.

Raises:

Type Description
ValueError

If target_decay is not in (0, 1], or stop_score is negative.