Skip to content

transitlos

transitLOS: transit level-of-service accessibility scoring.

Ties street-network accessibility (UrbanAccessAnalyzer), transit stops (pyGTFSHandler), and population/census data (pycensus/geohierarchy) together into a single transit level-of-service accessibility score. The scoring formulas are in transitlos.scoring; transitlos.api is the consolidated public surface re-exported below.

level_of_service_to_h3(access_gdf, resolution, aoi=None, score_col='level_of_service', margin_m=10.0, fallback_radius_multiplier=5.0, no_access_value=0.0)

Resample a street-edges level_of_service column onto an H3 grid.

Each returned H3 cell holds the maximum score_col among streets that intersect it (or, absent that, its single nearest street within fallback_radius_multiplier cell-edge-lengths) -- see module docstring for the full policy. Cells with no qualifying street at all get no_access_value rather than a null, matching the fillna(0.0) convention used elsewhere in the downstream pipeline for "no coverage".

Parameters:

Name Type Description Default
access_gdf GeoDataFrame

Street-edges GeoDataFrame with score_col (e.g. the output of transitlos.level_of_service.compute_level_of_service).

required
resolution int

H3 resolution the grid is built at (typically the maximum/finest resolution configured for the AOI).

required
aoi Optional[GeoDataFrame]

Geometry whose extent the H3 grid should cover. Defaults to access_gdf's own extent (buffered implicitly by edges_to_h3_by_distance's search margin) if not given.

None
score_col str

Column in access_gdf to resample.

'level_of_service'
margin_m float

Extra distance (in meters) beyond one cell's own footprint still counted as "touching" a street -- forwarded to edges_to_h3_by_distance.

10.0
fallback_radius_multiplier Optional[float]

How many cell-edge-lengths a cell may look for its nearest street once the normal margin turns up nothing. None disables the fallback (matches edges_to_h3_by_distance's own default meaning).

5.0
no_access_value float

Value assigned to a cell that found no street even within the fallback radius.

0.0

Returns:

Type Description
GeoDataFrame

GeoDataFrame with "h3", "geometry", and score_col -- one row

GeoDataFrame

per H3 cell covering aoi (or access_gdf's extent), every row

GeoDataFrame

populated.

compute_level_of_service(aoi, feed_source=None, network=None, stops=None, region='global', cache_dir=None, walk_distance_steps=(400, 800, 1200), weights=None, pbf_path=None, date_range=None, score_bins=50, max_walk_distance_m=None, chunk_h3_resolution=None, chunk_buffer_m=1000.0, stops_crop_buffer_m=500.0, **stops_kwargs)

Compute a street-edges GeoDataFrame with a transit-access level_of_service column.

Parameters:

Name Type Description Default
aoi AreaOfInterest

Area of interest for the network and (if stops not given) the GTFS feed.

required
feed_source

GTFS feed source forwarded to stops.download_and_prepare_stops if stops is not given.

None
network Optional[StreetNetwork]

A pre-built StreetNetwork; if None, network.prepare_street_network(aoi, cache_dir=cache_dir, pbf_path=pbf_path) is called.

None
stops Optional[GeoDataFrame]

A pre-built stops GeoDataFrame; if None, stops.download_and_prepare_stops(feed_source, aoi=aoi, date_range=date_range, **stops_kwargs) is called. If given but missing a stop_score column, stop_scores.compute_stop_scores is applied to it.

None
region str

Region key forwarded to compute_stop_scores and to build_intelligent_distance_matrix (selects the decay-shape defaults walk_decay/accessibility_score use).

'global'
cache_dir Optional[str]

Passed to prepare_street_network for network caching.

None
walk_distance_steps Sequence[float]

Deprecated/unused by default as of 2026-08-12 -- distance thresholds are now derived automatically by build_intelligent_distance_matrix from transitLOS's own decay curve (see module docstring). Kept only so existing calls don't break; passing a non-default value has no effect unless you also bypass build_intelligent_distance_matrix yourself.

(400, 800, 1200)
weights Optional[tuple[float, float, float]]

Optional (w1, w2, w3, w4) weights forwarded to compute_stop_scores.

None
pbf_path Optional[str]

Passed to prepare_street_network when a network must be built from scratch.

None
date_range Optional[tuple[Union[date, datetime], Union[date, datetime]]]

Optional (start_date, end_date) forwarded to download_and_prepare_stops (ignored if stops is given directly). Strongly recommended whenever you already know a valid service date for feed_source: it skips download_and_prepare_stops's expensive service-day auto-detection fallback, which alone can cost ~7s of a ~10s call on a real multi-file GTFS feed (see that function's docstring for details). If omitted, the safe (but slower) auto-detection default is used.

None
score_bins Optional[int]

Deprecated/unused by default as of 2026-08-12 -- build_intelligent_distance_matrix already collapses stop_score into output-equivalent buckets (see module docstring), which supersedes this parameter's quantile-bucketing approach.

50
max_walk_distance_m Optional[float]

Optional hard outer walk-distance cutoff (meters) forwarded to build_intelligent_distance_matrix. The decay curve (walk_access.walk_decay) never truly reaches zero, so without this the isochrone search radius can extend several kilometers for the lowest access tier; set this to cap it (e.g. 2000 m) while still searching the entire requested radius (see that function's docstring for how the cutoff is applied). None (default) leaves the search radius unbounded.

None
chunk_h3_resolution Optional[int]

Opt-in memory-bounded isochrone computation -- forwarded to UrbanAccessAnalyzer.api.AccessibilityAnalyzer.run's chunk_h3_resolution. None (default) is the original whole-network behavior, unaffected. Set to e.g. 4 for oversized AOIs (Boston, Shanghai) where the unchunked path OOMs.

None
chunk_buffer_m float

Forwarded as chunk_buffer_m when chunk_h3_resolution is set. Must be >= the largest isochrone search radius the chosen decay curve can produce (see max_walk_distance_m above and AccessibilityAnalyzer.run/compute_node_access_chunked's own docstrings) or results near chunk boundaries will be truncated.

1000.0
stops_crop_buffer_m float

Metres to buffer aoi by before querying stops (only when stops is not given directly) -- see the note where it's used, below. 0 for the exact-AOI behavior.

500.0
**stops_kwargs

Extra keyword arguments forwarded to download_and_prepare_stops (e.g. route_types).

{}

Returns:

Type Description
GeoDataFrame

geopandas.GeoDataFrame of street edges (network CRS) with a

GeoDataFrame

level_of_service column, ceiling-discretized onto `{0.0, 0.1, ...,

GeoDataFrame

1.0}` internally (see module docstring, point 3) and then rescaled

GeoDataFrame

to {0, 10, ..., 100} -- 2026-09-23, explicit user request that

GeoDataFrame

every 0-1 score be displayed/stored on a 0-100 scale.

compute_stop_scores(stops_df, region='global', weights=None, default_headway_cv=None, stop_score_mode='nested')

Add mrc_score/speed_score/frequency_score/stop_score columns.

Parameters:

Name Type Description Default
stops_df Union[DataFrame, 'gpd.GeoDataFrame']

A pandas DataFrame or GeoDataFrame with headway_minutes, headway_cv, avg_speed_kmh, and (optionally) route_type columns (as produced by transitlos.stops.download_and_prepare_stops). Rows with a null headway_minutes or avg_speed_kmh get NaN scores. Rows with a missing/absent route_type fall back to the "bus" mode category (see transitlos.scoring.mrc.mode_category).

required
region str

Region key forwarded to every transitlos.scoring call. Kept for backward compatibility -- every region now shares identical, universal parameters (see scoring/parameters.py).

'global'
weights Optional[tuple[float, float, float]]

Only meaningful when stop_score_mode is "harmonic" or "geometric" (the legacy flat three-way mean) -- forwarded to stop_score. Must be left None for the default stop_score_mode="nested" (see scoring.stop_score's docstring -- the nested default has no weight parameter by construction).

None
stop_score_mode str

Forwarded to scoring.stop_score as mode. Defaults to "nested" (sqrt(MRC*V)*H, 2026-09-29 default). Pass "harmonic"/"geometric" to reproduce the prior flat generalized-power-mean forms, e.g. for before/after comparisons.

'nested'
default_headway_cv Optional[float]

No longer substituted into mrc_score (see module docstring's honesty note -- doing so would silently erase the mode-categorical default for every stop). Kept as an accepted, unused parameter for backward-compatibility only; passing a non-None value has no effect. Use reliability_score_is_assumed to identify rows using the mode-categorical fallback.

None

Returns:

Type Description
Union[DataFrame, 'gpd.GeoDataFrame']

stops_df (same type, a copy) with mode_category, mrc_score,

Union[DataFrame, 'gpd.GeoDataFrame']

speed_score, frequency_score, stop_score, and

Union[DataFrame, 'gpd.GeoDataFrame']

reliability_score_is_assumed columns added.

cross_with_population(access_gdf, population_source='worldpop', aoi=None, region_for_census=None, id_col='edge_id', access_columns=None, census_level='tract', census_dataset='acs', worldpop_date=None, worldpop_resolution='1km', worldpop_folder=None, **kwargs)

Combine access_gdf (street edges with an level_of_service column) with population data.

Parameters:

Name Type Description Default
access_gdf GeoDataFrame

Street-edges GeoDataFrame with an level_of_service column (e.g. from transitlos.level_of_service.compute_level_of_service).

required
population_source str

"worldpop" (global gridded population, any country) or "us_census" (pycensus.census.countries.usa.acs5/.dhc, US only).

'worldpop'
aoi Optional[GeoDataFrame]

Area of interest, required for "worldpop" (used to download the raster) and used as a fallback to derive us_census's states if region_for_census is not given.

None
region_for_census Optional[Union[str, list]]

For "us_census": state name(s)/abbreviation(s)/ FIPS code(s) forwarded to pycensus.census.countries.usa.acs5.load/.dhc.load as states. If None, derived from aoi.

None
id_col str

Name to give the population polygon's unique-id column in the returned GeoDataFrame (GEOID for us_census is renamed to this; a synthetic pixel index is used for worldpop).

'edge_id'
access_columns Optional[list]

Edge columns from access_gdf to aggregate onto the population polygons. Defaults to ["level_of_service"].

None
census_level str

Geometry level forwarded to pycensus.census.countries.usa.acs5.load/ .dhc.load (only used when population_source="us_census").

'tract'
census_dataset str

"acs" or "dhc" -- which pycensus.usa submodule to use for "us_census".

'acs'
worldpop_date

Year (or date/datetime) forwarded to download_worldpop_population; required for "worldpop".

None
worldpop_resolution str

"100m" or "1km", forwarded to download_worldpop_population. "1km" is the safer default to keep the pixel-grid vectorization tractable.

'1km'
worldpop_folder Optional[str]

Download destination forwarded to download_worldpop_population.

None
**kwargs

Extra keyword arguments forwarded to the underlying pycensus loader.

{}

Returns:

Type Description
GeoDataFrame

GeoDataFrame with one row per population polygon: id_col,

GeoDataFrame

geometry, population, and the aggregated access_columns.

Raises:

Type Description
ValueError

If population_source is not "worldpop"/"us_census", or a required argument for the chosen source is missing.

download_and_prepare_stops(feed_source, aoi=None, date_range=None, start_time=time.min, end_time=time.max, route_types=None, by='route_id', at='parent_station', how='add', scoring='direction_best', speed_method='straight', window_min=15.0, window_direction='both', **kwargs)

Load a GTFS feed and build a per-stop headway/speed table.

scoring="direction_best" (default) scores every parent station from the MERGED departures of all routes split in the two directions of travel, searching mode tier x minimum trip speed for the best stop score (scoring.direction_subset); by/how then do not apply and the table already carries stop_score. scoring="route" is the previous route-level headway (by/how) with the speed max.

feed_source is passed straight through to pyGTFSHandler.feed.Feed's gtfs_dirs constructor argument -- this function does not implement any downloading/geocoding-to-feed-source resolution of its own, it only orchestrates a Feed that has already been (or can already be) loaded from a path/URL/list understood by pyGTFSHandler.

Parameters:

Name Type Description Default
feed_source Union[str, Path, Sequence[Union[str, Path]]]

One or more GTFS directory/zip paths, forwarded to Feed(gtfs_dirs=feed_source, ...).

required
aoi Optional[GeoDataFrame]

Optional Area of Interest GeoDataFrame/GeoSeries used to geospatially filter stops while loading the feed.

None
date_range Optional[tuple[Union[date, datetime], Union[date, datetime]]]

Optional (start_date, end_date) used as Feed's start_date/end_date filters, and as the single analysis date (start_date) for get_headway_at_stops/ get_speed_at_stops.

Performance: passing date_range explicitly skips the auto-detection fallback below entirely. That fallback (calling feed.get_representative_date, which groups dates into calendar weeks, scores each week by its median daily service intensity, and returns the day within the best week with the most services -- see pyGTFSHandler.representative_date.select_representative_date for the full algorithm) is safe but expensive -- on a real multi-file Cambridge, MA GTFS feed it accounted for ~7.3s of this function's ~10.2s total runtime. If you already know a valid service date for the feed (e.g. from a prior run, from inspecting calendar.txt/calendar_dates.txt, or from documentation), pass date_range=(that_date, that_date) -- it is strongly recommended whenever you have this information, since it turns a ~10s call into roughly ~3s. If omitted, the auto-detection fallback runs as described below (the safe default for callers who don't know a good date up front).

None
start_time Union[datetime, time]

Start of the daily analysis window, forwarded to both get_headway_at_stops and get_speed_at_stops. Defaults to midnight (full day). Pass e.g. time(6, 0) to restrict headway and speed to a specific service window (e.g. excluding overnight low-frequency service from the score).

min
end_time Union[datetime, time]

End of the daily analysis window, forwarded the same way. Defaults to end of day.

max
route_types Optional[Union[list, int, str]]

Optional GTFS route type filter, forwarded to both Feed and the two analysis calls.

None
by str

Grouping key forwarded to get_headway_at_stops/ get_speed_at_stops ("route_id" or "shape_direction").

'route_id'
at str

Spatial stop-identity column forwarded to both analysis calls ("parent_station" or "stop_id").

'parent_station'
how str

Aggregation strategy forwarded to both analysis calls. Note get_headway_at_stops and get_speed_at_stops interpret how independently (see their own docstrings); for speed there is no "best" option so "best" is mapped to "max".

Changed from "best" to "add" (2026-08-12), at the user's explicit request -- diagnosed against a real multi-branch trunk stop (MBTA Green Line at Boylston, served by 4 branches): how="best" groups headway per (stop, route, direction) and keeps only the single most-frequent one, which can never reflect the combined frequency riders actually experience at a stop served by multiple routes/branches -- it reported 49.68 min there (one branch's own headway) when the real combined Green Line frequency is close to 4-6 min. This was not a rare edge case: on a full Boston run, 89% of stops ended up with a null stop_score and the median reported headway was ~7.3 hours, because most real-world stops are served by >=2 routes/directions and "best" structurally can't combine them. how="add" (see get_headway_at_stops's own docstring) combines routes via a harmonic sum of their rates (1 / (1/headway).sum()) within each direction, then -- with mix_directions=False, the default forwarded here -- keeps whichever direction has the better (lower) combined headway, rather than requiring both directions' data to be good. Verified against the same real Green Line stop: headway dropped from 49.68 min to 11.07 min, matching the user-confirmed real-world frequency far more closely.

'add'
speed_method str

How the speed at a stop is measured: "straight" (default) -- straight-line distance the trip gets from the stop in the window, so winding lines are slower; "shape" -- distance along the shape (pyGTFSHandler Feed.get_window_distances).

'straight'
window_min float

Minutes on each side of the stop the speed is measured over (default 15).

15.0
window_direction str

"both" (default), "forward" or "backward".

'both'
**kwargs

Extra keyword arguments forwarded to Feed(...) (e.g. stop_group_distance, check_files).

{}

Returns:

Type Description
GeoDataFrame

geopandas.GeoDataFrame with columns: stop_id (or the at column

GeoDataFrame

used), geometry (Point, lon/lat, from add_stop_coords),

GeoDataFrame

headway_minutes, headway_cv (always null -- see module

GeoDataFrame

docstring), avg_speed_kmh, and route_id/route_ids if produced

GeoDataFrame

by the underlying calls.

Raises:

Type Description
ValueError

If the feed has no usable date to analyze (no date_range given and the feed exposes no service dates).

equity_statistics(combined_gdf, score_col='level_of_service', population_col='population', groups=None, thresholds=(0.25, 0.5, 0.75))

Compute population-weighted access-equity statistics.

Parameters:

Name Type Description Default
combined_gdf DataFrame

DataFrame/GeoDataFrame with score_col and population_col columns (e.g. from transitlos.population.cross_with_population).

required
score_col str

Column holding the per-row level of service.

'level_of_service'
population_col str

Column holding the per-row population count, used as weights throughout.

'population'
groups Optional[Union[str, Sequence[str]]]

Optional column name (or list of column names) to also break statistics down by, in addition to the overall figures.

None
thresholds Sequence[float]

Score thresholds used to report the population share above/below each one.

(0.25, 0.5, 0.75)

Returns:

Type Description
dict

A dict with keys "overall" (a dict of weighted_mean,

dict

weighted_median, gini, and pct_population_above_threshold/

dict

pct_population_below_threshold sub-dicts keyed by threshold), and,

dict

if groups was given, "by_group": a pandas.DataFrame indexed by

dict

the group column(s) with the same statistics per group.

prepare_street_network(aoi, cache_dir=None, cluster_distance=10.0, pbf_path=None, network_type='all', ignore_oneway=True)

Return a simplified, AOI-cropped StreetNetwork, using a cache if available.

Parameters:

Name Type Description Default
aoi AreaOfInterest

Area of interest the network is built/cropped for.

required
cache_dir Optional[str]

Directory to load a previously .save()d network from (via StreetNetwork.load), and to .save() a freshly built one to. If None, no caching is attempted -- the network is always rebuilt and never persisted.

None
cluster_distance float

Cluster distance (meters) passed to StreetNetwork.simplify.

10.0
pbf_path Optional[str]

Path to a local .osm.pbf file, forwarded to StreetNetwork.from_pbf. If it doesn't exist, it is downloaded for aoi via Geofabrik (see StreetNetwork.from_pbf's docstring). Required when cache_dir is None or has no cached network yet.

None
network_type str

Defaults to "all" -- every public road included regardless of walk-permission, including highway/trunk. This was briefly "walk" (2026-09-04, an explicit request to exclude highway/trunk roads except where needed for connectivity), reverted the same day (explicit follow-up: "delete this idea of excluding highway and only include edges really needed for the graph. Include all public roads regardless if they are walk or not including highway"). No highway-tag filter at all -- see osm_io.NETWORK_PROFILES["all"].

'all'
ignore_oneway bool

Defaults to True -- forwarded to StreetNetwork.from_pbf/osm_io.load_pbf so every included edge is traversable in both directions for this walking-access graph, regardless of any OSM oneway tag (a vehicle-traffic restriction pedestrians aren't bound by).

True

Returns:

Type Description
StreetNetwork

A StreetNetwork already simplified and cropped to aoi.

Raises:

Type Description
ValueError

If no cached network is found and pbf_path is None.