Skip to content

transitlos.stops

Load a GTFS feed and build a per-stop table of raw transit level-of-service inputs.

Wraps pyGTFSHandler.feed.Feed loading plus its FeedAnalysisMixin methods (get_headway_at_stops, get_speed_at_stops, add_stop_coords) into a single call that produces the raw inputs transitlos.scoring needs: headway_minutes (from get_headway_at_stops, already returned in minutes) and avg_speed_kmh (from get_speed_at_stops's speed column, which is already km/h -- see its implementation: (distance_weight/1000) / (time_weight/3600)).

Honesty note on reliability: get_headway_at_stops returns only a harmonic mean headway per stop/route, not a distribution, so there is no headway coefficient-of-variation (headway_cv) available from pyGTFSHandler today. This module does not fabricate one -- the returned frame's headway_cv column is all-null, and stop_scores.compute_stop_scores documents how it handles that honestly (it does not silently assume perfect reliability without saying so).

pick_analysis_date(feed, route_types=None, day_type='weekday')

Automatically pick the analysis day for feed (no hard-coded dates needed): a working weekday, a Saturday or a Sunday.

  1. feed.get_representative_date over the part of the feed's calendar within _REPRESENTATIVE_DATE_HORIZON_DAYS of today (or the whole calendar if that doesn't overlap -- stale/historical feeds).
  2. Sanity check against total scheduled trips per day of that type (for weekdays: Mon-Fri, public holidays excluded) in that window: if the pick has under 80% of the busiest such day's trips (real case: Taipei's tdx_bus, a sparse baseline plus a short dense span the station-median score can't tell apart), use the middle date among those days with >= 95% of the maximum trips.

Raises:

Type Description
ValueError

if the feed has no dates to pick from.

Parameters:

Name Type Description Default
feed Feed

A loaded pyGTFSHandler Feed.

required
route_types

Optional route type filter.

None
day_type str

"weekday" (default), "saturday" or "sunday".

'weekday'

Returns:

Type Description
date

The analysis date.

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).

download_and_prepare_stops_per_feed(gtfs_dirs, **kwargs)

Score each GTFS directory in gtfs_dirs independently, then concatenate.

download_and_prepare_stops normally stacks every directory into one Feed and picks a SINGLE representative date shared across all of them (see its docstring's "Bug found and fixed 2026-08-24" note) -- correct and cheaper for the common case where every feed's calendar.txt covers roughly the same real-world window. That assumption breaks when feeds are genuinely from different times: real case found 2026-08-24, Taipei -- its tdx_bus feed's calendar is valid only 2026-05-01 to 2026-06-30 (a narrow real-time TDX export snapshot), while its trtc_metro feed's calendar spans 2025-08-18 to 2026-12-31. No single date can be representative of both feeds' real service at once: a near-term-bounded search barely overlaps tdx_bus's narrow window (starves it down to a handful of stops), while an unbounded search can only get both feeds right by coincidence.

This function sidesteps the problem entirely by never stacking feeds in the first place: each directory in gtfs_dirs gets its own Feed, its own representative-date pick (independently, via the normal download_and_prepare_stops call), and its own stop scoring -- then the resulting per-feed GeoDataFrames are concatenated. Each feed's parent_station grouping (stop_group_distance, if passed via **kwargs) is computed WITHIN that feed only, not across feeds -- a bus stop and a metro entrance from two different feeds within 150m of each other will NOT be merged into one parent_station by this path (unlike the single-Feed path, where they would be). This is a deliberate, documented simplification, not an oversight: the point of this function is to fix the "no representative date works for every feed" problem, not to also solve cross-feed station deduplication -- use download_and_prepare_stops (single stacked Feed) whenever every feed's calendar genuinely overlaps well enough for one shared date.

Parameters:

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

One GTFS directory/zip path per feed -- each is scored completely independently (own Feed, own representative date).

required
**kwargs

Forwarded unchanged to download_and_prepare_stops for every feed (aoi, date_range, start_time, end_time, route_types, by, at, how, stop_group_distance, ...). date_range, if a plain (start, end) tuple, is used as-is for every feed alike. If a {feed_directory_name: (start, end)} dict, only the named feed(s) get that explicit pin -- every other feed still auto-detects its own date (matching by Path(gtfs_dir).name, e.g. {"tdx_bus": (d, d)} pins only the directory literally named tdx_bus). Leave None (the default, recommended) to let every feed auto-detect independently, searching each ONE feed's full real calendar range with no horizon bound -- see the "Not just unneeded, actively harmful" note above for why this deliberately does NOT reuse download_and_prepare_stops's own horizon-bounded auto-detect. A real per-feed pin is still sometimes necessary even with unbounded per-feed search, though -- see CityConfig's Taipei entry for a real feed (tdx_bus) whose median-service-based auto-detect can't reliably tell its genuinely dense weeks apart from sparse ones (most low-traffic stations have near-constant baseline service across its whole range, masking a real ~6-week span of much denser real data in the per-station MEDIAN this algorithm scores by).

{}

Returns:

Type Description
GeoDataFrame

Concatenated geopandas.GeoDataFrame, same columns as

GeoDataFrame

download_and_prepare_stops's single-feed return, one row set per

GeoDataFrame

feed stacked on top of the others (ignore_index=True -- no

GeoDataFrame

cross-feed index meaning to preserve).

Raises:

Type Description
ValueError

If every feed in gtfs_dirs fails to produce stops (each feed's own download_and_prepare_stops failure is logged but not fatal -- one bad/empty feed among several real ones shouldn't abort the whole city, matching this codebase's "one bad workbook/level shouldn't abort everything" convention elsewhere -- see pycensus.census.countries.germany.ba.loader).

build_parent_station_keys(stops_meta_df, distance_m=150.0)

Assign every GTFS stop a station_key grouping it with its physical station.

Prefers the real GTFS parent_station field where present (a station's platforms/entrances are usually already linked there by the agency). Stops with no parent_station (null/missing, or the column absent entirely) are instead grouped by 150m spatial-proximity clustering (_proximity_cluster_ids) -- this is the fallback the module docstring and the stop-clustering requirement call for: real-world GTFS feeds frequently split one physical station into several unlinked stop_ids (opposite-direction platforms, separate entrances) with no parent_station set at all.

Parameters:

Name Type Description Default
stops_meta_df DataFrame

A polars DataFrame with at least stop_id, stop_lat, stop_lon columns (as on feed.stops), and optionally parent_station.

required
distance_m float

Proximity threshold in meters for the spatial fallback. Defaults to 150m per the clustering requirement.

150.0

Returns:

Type Description
DataFrame

stops_meta_df with a station_key column added: parent_station

DataFrame

where present, else "cluster_<n>" for stops grouped purely by

DataFrame

proximity. Each individual stop_id keeps its own row/coordinates --

DataFrame

this only adds the grouping key, it does not collapse rows.