Skip to content

Transportation Module

The transportation module creates synthetic GTFS feeds from explicit stopping patterns, reports their assumptions, saves and restores them, and loads GTFS public transport archives and local GBFS shared-mobility JSON feeds into DuckDB. It also derives stop-to-stop origin–destination records and aggregates GTFS schedules into transportation network graphs.

See the tutorial on creating GTFS from OpenStreetMap for a first feed and the generation reference for field precedence, source-tag interpretation, partial service tables and default values.

GTFS transportation network utilities.

The functions in this module generate, inspect, save and load GTFS feeds, retrieve transport service from OSM, and derive stop-to-stop origin/destination records and transport summary graphs for analysis.

Classes:

Name Description
TransportData

Tables accepted by :func:create_gtfs and prepared by source adapters.

Functions:

Name Description
create_gtfs

Create a GTFS feed from stopping patterns and optional operating conditions.

get_gtfs_summary

Summarise generated GTFS service and inspect its recorded assumptions.

save_gtfs

Validate and save supported GTFS tables as a ZIP archive.

load_gtfs

Load a GTFS ZIP archive into an in-memory DuckDB database.

load_osm_transport

Retrieve OSM public transport relations and create a GTFS feed.

load_gbfs

Load GBFS JSON feeds from a directory into an in-memory DuckDB database.

get_od_pairs

Generate stop-to-stop OD pairs from GTFS trip stop sequences.

travel_summary_graph

Aggregate GTFS service into a weighted stop-to-stop summary graph.

TransportData

Bases: TypedDict


              flowchart TD
              city2graph.transportation.TransportData[TransportData]

              

              click city2graph.transportation.TransportData href "" "city2graph.transportation.TransportData"
            

Tables accepted by :func:create_gtfs and prepared by source adapters.

Identifiers link route patterns, stop occurrences and their source records.

create_gtfs

create_gtfs(
    data,
    services=None,
    *,
    agency=None,
    calendar=None,
    calendar_dates=None,
    speed_kph=None,
    dwell_time_secs=None,
    distance_method=None,
    start_time=None,
    end_time=None,
    headway_secs=None,
    group_headway_secs=None,
    pattern_ids=None,
    service_date=None,
    optional_tables=None
)

Create a GTFS feed from stopping patterns and optional operating conditions.

Each service row describes a scheduled departure or one headway period. Missing conditions use the deterministic simple-v1 reference-week model. Inputs are copied; source data and modelling assumptions remain traceable.

Parameters:

Name Type Description Default
data TransportData

routes and stops use GTFS columns. Stops may instead be a Point GeoDataFrame with a CRS. patterns contains pattern_id, route_id, direction_id and optional LineString geometry (with CRS). Redundant binary geometry in coordinate-valued pandas stop tables is ignored. Integral numeric direction codes, including 0.0 and 1.0, are accepted. Whitespace-only cells are missing values. Documented extended route types inherit their mode group's default speed and retain their codes. Optional service_group_id changes grouping for default frequency allocation. stop_sequences contains pattern_id, stop_id and stop_sequence. Optional incoming-leg columns are travel_time_secs, distance_m, speed_kph and cumulative shape_dist_traveled (metres). Complete arrival_offset_secs and departure_offset_secs already include dwell. Otherwise, supplied travel times, speeds and dwell times override the model defaults; no operating columns are required.

required
services DataFrame

Rows may supply pattern_id and service_id, plus either departure_time or start_time, end_time and headway_secs. Optional exact_times defaults to 0; use 1 only for an explicitly anchored timetable. Optional trip_id defaults to a deterministic service-row identifier avoiding explicit IDs. Repeating a trip_id is allowed only for separate frequency periods of the same pattern. Omit the table to generate every pattern, or omit pattern_id to apply supplied conditions to all patterns. Missing fields are filled from global overrides, source information and defaults, in that order. Unlisted patterns are retained and completed. Use pattern_ids to select a subset. Unknown columns raise an error. Optional trip_headsign, trip_short_name, wheelchair_accessible and bikes_allowed are preserved.

None
agency DataFrame

GTFS agency metadata. Source fields precede synthetic placeholders. A unique geographical timezone is estimated before a warned UTC fallback.

None
calendar DataFrame

GTFS weekly service calendar. Without dates, use seven days starting on the generation date.

None
calendar_dates DataFrame

GTFS date-specific service additions and removals.

None
speed_kph float

Speed for legs without timings or per-leg speed. Defaults depend on mode and are unverified average-speed assumptions including stopping effects.

None
dwell_time_secs float

Additional dwell for stops without per-stop values. Defaults to zero. Supplied offsets already include dwell and are not modified.

None
distance_method str

Defaults to "auto": use supplied distances, usable directed shape, then geodesic stop-to-stop distance. Explicit "shape" requires a usable directed alignment; "geodesic" skips shape projection.

None
start_time str

Global frequency-period start, default "06:00:00" without a source value.

None
end_time str

Global frequency-period end, default "22:00:00" without a source value.

None
headway_secs float

Global positive integer headway in seconds, per pattern. Exclusive with group_headway_secs. Individual service rows take precedence.

None
group_headway_secs float

Positive integer reference headway shared across each selected group. Each pattern receives this interval multiplied by the group's pattern count. Overrides source intervals, but not individual service rows. Without either override or source intervals, the shared default is 900 s. Explicit pattern overrides and closures do not redistribute unused shares.

None
pattern_ids str or sequence of str

Generate only these patterns. Defaults to all patterns, including those omitted from services. Known service rows outside the selection are excluded; unknown IDs and empty selections raise an error.

None
service_date str

Explicit YYYYMMDD service date for one day. If all date inputs are omitted, use seven days starting on the generation date in the local system timezone. Cannot be combined with calendar or calendar_dates.

None
optional_tables mapping of str to pandas.DataFrame

Additional transfers, pathways, levels, feed_info or attributions tables.

None

Returns:

Type Description
DuckDBPyConnection

An in-memory feed compatible with load_gtfs and the analysis functions.

Raises:

Type Description
ValueError

If inputs are incomplete, ambiguous or inconsistent with the contract.

get_gtfs_summary

get_gtfs_summary(con)

Summarise generated GTFS service and inspect its recorded assumptions.

The report uses persisted generation records and survives GTFS save/load. Edge counts are directed and cover all active service days in the feed.

Parameters:

Name Type Description Default
con DuckDBPyConnection

Generated feed, optionally restored with embedded metadata.

required

Returns:

Type Description
dict of str to pandas.DataFrame

summary contains one row with model, start_date, end_date, service_days, route_count, pattern_count, stop_count, expected_departures, mean_daily_departures, min_speed_kph, max_speed_kph, specified_pattern_count, completed_pattern_count and excluded_relation_count. Daily averages include closed dates between the bounds. Speed bounds cover adopted speeds for untimed legs only. assumptions lists adopted values and ignored source information; services lists each date and service period with its activity and number of departures; edges gives combined stop-to-stop traversals with start_date and end_date identifying the frequency aggregation period. Frequency-based departures are expected counts unless exact_times is 1. Service columns and their order are stable. Non-applicable frequency fields are null for fixed departures. Counts and seconds are numeric, integer fields are nullable Int64, and IDs, dates and clocks are strings.

Raises:

Type Description
ValueError

If generation metadata is unavailable or predates effective records.

save_gtfs

save_gtfs(
    con, path, *, include_metadata=_INCLUDE_METADATA, overwrite=_OVERWRITE
)

Validate and save supported GTFS tables as a ZIP archive.

Analysis scratch tables and geometry columns are excluded. Metadata is included as JSON so copying or renaming the archive preserves its history.

Parameters:

Name Type Description Default
con DuckDBPyConnection

Connection returned by create_gtfs, a transport loader or load_gtfs.

required
path str or Path

Destination ZIP file. Its parent directory must exist.

required
include_metadata bool

Include city2graph_metadata.json when metadata is present. load_gtfs restores it automatically. Set False to export only GTFS tables.

True
overwrite bool

Explicitly permit replacing an existing archive.

False

Returns:

Type Description
Path

Path to the saved ZIP archive.

Raises:

Type Description
ValueError

If the feed is incomplete or contains unsupported persistent tables.

FileExistsError

If an output already exists and overwrite is False.

load_gtfs

load_gtfs(path, *, include_metadata=_INCLUDE_METADATA)

Load a GTFS ZIP archive into an in-memory DuckDB database.

The function reads *.txt GTFS files as tables, registers a time parsing UDF, and materializes stops.geometry as points from stop_lon/stop_lat when stop coordinates are available.

Parameters:

Name Type Description Default
path str | Path

Path to a GTFS .zip file.

required
include_metadata bool

Restore embedded city2graph_metadata.json when present. Set False to load only the GTFS tables.

True

Returns:

Type Description
DuckDBPyConnection

In-memory DuckDB connection containing imported GTFS tables.

load_osm_transport

load_osm_transport(
    services=None,
    *,
    agency=None,
    area=None,
    place_name=None,
    route_name=None,
    route_ref=None,
    relation_ids=None,
    modes=None,
    pattern_ids=None,
    stop_level="station",
    on_invalid="skip",
    data=None,
    overwrite_source=_OVERWRITE_SOURCE,
    endpoint=_OSM_ENDPOINT,
    timeout=_OSM_TIMEOUT,
    use_source_tags=_USE_SOURCE_TAGS,
    **gtfs_options
)

Retrieve OSM public transport relations and create a GTFS feed.

Relation IDs identify patterns as osm:relation:<id>. Ordered PTv2 stop members are retained, including stops outside the selection boundary. Operating conditions are passed to the shared create_gtfs implementation.

Parameters:

Name Type Description Default
services DataFrame

Optional operating conditions referring to the OSM pattern identifiers. Omit the table for all patterns with source-first completion; omit pattern_id to apply supplied periods to every selected pattern.

None
agency DataFrame

Explicit agency metadata. Missing metadata uses available source fields, unique geographical timezone inference and warned placeholders.

None
area (list, Polygon, MultiPolygon, GeoSeries or GeoDataFrame)

WGS84 bounding box or polygon selection. Exclusive with place_name. May be omitted when relation_ids is supplied.

None
place_name str

Place boundary to resolve with get_boundaries.

None
route_name str

Exact route-name filter. Ambiguous matches require relation_ids.

None
route_ref str

Exact route reference filter within the selected area.

None
relation_ids list of int

Explicit route relation IDs. These select complete relations.

None
modes str or sequence of str

Select tram (including light_rail), subway, train, bus, trolleybus, ferry, monorail or funicular. Defaults to all supported modes. Combined with relation_ids and pattern_ids by intersection. Also filters supplemental routes by their effective route_type. Documented extended GTFS types use the corresponding mode group; original route_type values are preserved.

None
pattern_ids str or sequence of str

Additional explicit pattern selection. Intersects modes and relation_ids. Unlisted service patterns otherwise remain in the generated feed. Applies to supplemental patterns too. Mode-excluded source IDs are known from candidate tags, without downloading their member geometry.

None
stop_level ('station', 'platform')

Use named OSM stop areas to consolidate their boarding elements. Ambiguous or missing stop-area membership retains individual source IDs. Platform mode preserves every source boarding ID. Station grouping adds no transfer time or platform accessibility information.

"station"
on_invalid ('raise', 'skip')

Report all invalid source relations together, or explicitly exclude them with a warning and persisted reasons. Network and explicit-input errors are never skipped; an empty result always raises an error.

"raise"
data mapping of str to pandas.DataFrame

Supplemental routes, stops, patterns or stop_sequences using common IDs. Supplied values are validated before retrieval, including excluded rows. Missing source route names and stop information may be completed here.

None
overwrite_source bool

Allow explicit replacement of source fields and stopping sequences.

False
endpoint str

Configurable Overpass endpoint.

"https://overpass-api.de/api/interpreter"
timeout float

HTTP and Overpass timeout in seconds.

180
use_source_tags bool

Adopt supported interval, opening_hours, duration and interval:conditional tags below explicit overrides. Unambiguous parent metadata can be inherited. Unsupported tags and rejection reasons remain in the generation report.

True
**gtfs_options Unpack[GenerationOptions]

Calendar, timing, headway, representative-date and optional-table overrides forwarded to create_gtfs, including group_headway_secs and pattern selection. Missing values use simple-v1. Unlisted service patterns remain.

{}

Returns:

Type Description
DuckDBPyConnection

Generated feed ready for analysis and save_gtfs.

Raises:

Type Description
ValueError

If selection is empty, ambiguous or cannot supply the required inputs.

RuntimeError

If Overpass fails or returns an incomplete response.

load_gbfs

load_gbfs(path)

Load GBFS JSON feeds from a directory into an in-memory DuckDB database.

The function reads GBFS JSON files from a local directory, flattens common feed structures into DuckDB tables, and materializes geometry columns from lon/lat fields when available.

Parameters:

Name Type Description Default
path str | Path

Path to a GBFS directory containing JSON files.

required

Returns:

Type Description
DuckDBPyConnection

In-memory DuckDB connection containing imported GBFS tables.

get_od_pairs

get_od_pairs(
    con, start_date=None, end_date=None, include_geometry=True, directed=False
)

Generate stop-to-stop OD pairs from GTFS trip stop sequences.

For each trip_id, consecutive stops are paired into directed legs with departure/arrival timestamps and per-leg travel time in seconds. Service activity is derived from calendar and optionally adjusted using calendar_dates. Frequency-based trips remain template legs, not actual departures; their timestamps must not be used to infer connections.

Parameters:

Name Type Description Default
con DuckDBPyConnection

DuckDB connection with GTFS tables loaded.

required
start_date str | None

Inclusive start date (YYYYMMDD). Defaults to the earliest date in calendar or calendar_dates.

None
end_date str | None

Inclusive end date (YYYYMMDD). Defaults to the latest date in calendar or calendar_dates.

None
include_geometry bool

If True and stop geometries are available, include a line geometry for each OD pair.

True
directed bool

If True, preserve the original trip direction for each OD pair. If False (default), canonicalize each pair so that orig_stop_id < dest_stop_id and aggregate both directions together.

False

Returns:

Type Description
DataFrame | GeoDataFrame

One row per directed (or undirected) stop-to-stop leg.

travel_summary_graph

travel_summary_graph(
    con,
    start_time=None,
    end_time=None,
    calendar_start=None,
    calendar_end=None,
    as_nx=None,
    directed=False,
    use_frequencies=True,
)

Aggregate GTFS service into a weighted stop-to-stop summary graph.

The function builds a stop-level graph from the GTFS feed, where each edge represents the aggregated service between two consecutive stops.

Edge attributes ~~~~~~~~~~~~~~~ travel_time_sec Service-weighted average travel time in seconds across all trips serving this stop pair. frequency Total number of leg traversals in the resolved calendar window. When use_frequencies=True and frequencies.txt is present, headway-based services are expanded into effective trip counts. For example, a trip running every 10 minutes for 1 hour contributes 6 traversals per active service day. Non-exact frequency service uses expected counts (which may be fractional); exact service counts departures in the half-open frequency period. Time bounds apply to each leg, accounting for offsets from the first stop.

Edge geometry ~~~~~~~~~~~~~ Edge geometry is represented as a straight stop-to-stop line.

Parameters:

Name Type Description Default
con DuckDBPyConnection

DuckDB connection with GTFS tables loaded.

required
start_time str | None

Optional lower bound (inclusive) for departure time, HH:MM:SS.

None
end_time str | None

Optional upper bound (inclusive) for next-stop arrival time, HH:MM:SS.

None
calendar_start str | None

Optional calendar window start, YYYYMMDD.

None
calendar_end str | None

Optional calendar window end, YYYYMMDD.

None
as_nx bool

If True, return a NetworkX graph instead of GeoDataFrames. If not explicitly set, defaults to False (GeoDataFrame output).

.. deprecated:: as_nx is deprecated and will be removed in a future release. Use :func:gdf_to_nx on the returned GeoDataFrames instead to obtain a NetworkX graph.

None
directed bool

If True, return a directed graph (nx.DiGraph) preserving trip direction. If False (default), edges in opposite directions are merged into undirected edges (nx.Graph).

False
use_frequencies bool

If True and frequencies.txt exists, expand headway-based service into effective trip counts for the frequency attribute.

True

Returns:

Type Description
tuple[GeoDataFrame, GeoDataFrame] | DiGraph | Graph

(nodes_gdf, edges_gdf) when as_nx is False; otherwise a nx.DiGraph (directed=True) or nx.Graph (directed=False) built from those GeoDataFrames via :func:city2graph.utils.gdf_to_nx, following its shared conventions: integer node identifiers with the original stop_id values stored in the _original_index node attribute, node pos coordinates, and graph-level CRS and index metadata.

city2graph.transportation.GTFSGenerationWarning

Bases: UserWarning


              flowchart TD
              city2graph.transportation.GTFSGenerationWarning[GTFSGenerationWarning]

              

              click city2graph.transportation.GTFSGenerationWarning href "" "city2graph.transportation.GTFSGenerationWarning"
            

Warn that generated service uses estimates, assumptions or placeholders.

Inspect get_gtfs_summary for adopted values and rejection reasons. Standard Python warning filters can promote this warning to an error.