### get_start_and_end_times Source: https://github.com/araichev/gtfs_kit_docs/blob/master/index.html Retrieves the start and end times for services on a given date. ```APIDOC ## get_start_and_end_times ### Description Return a list of strings representing the start and end times for services on the given date. ### Parameters #### Query Parameters - **date** (str | None, optional) - The date string in YYYYMMDD format. If None, considers all dates in the feed. ### Returns - list[str]: A list containing the start and end times. ``` -------------------------------- ### gtfs_kit.helpers.get_max_runs Source: https://github.com/araichev/gtfs_kit_docs/blob/master/index.html Finds the runs of the maximum value in a list and returns their start and end indices. ```APIDOC ## gtfs_kit.helpers.get_max_runs ### Description Given a list of numbers, return a NumPy array of pairs (start index, end index + 1) of the runs of max value. Assume x is not empty. ### Parameters * **x** (list) - A list of numbers. ### Returns * array - A NumPy array of [start, end+1] indices for each run of the maximum value. ### Example ```python >>> get_max_runs([7, 1, 2, 7, 7, 1, 2]) array([[0, 1], [3, 5]]) ``` ``` -------------------------------- ### Get Max Value Runs Source: https://github.com/araichev/gtfs_kit_docs/blob/master/index.html Finds the start and end indices of runs where the maximum value occurs in a list of numbers. Assumes the input list is not empty. ```python gtfs_kit.helpers.get_max_runs(_x_) -> array ``` ```python >>> get_max_runs([7, 1, 2, 7, 7, 1, 2]) array([[0, 1], [3, 5]]) ``` -------------------------------- ### Generate Quick GTFS Feed Summary with describe() Source: https://context7.com/araichev/gtfs_kit_docs/llms.txt Returns a DataFrame of high-level feed indicators. Optionally specialize to a sample date to count only entities active on that date. ```python import gtfs_kit as gk feed = gk.read_feed("gtfs.zip", dist_units="km") # Overall summary summary = feed.describe() print(summary) # indicator value # 0 num_routes 42 # 1 num_stops 512 # ... # Summary for a specific date summary_date = feed.describe(sample_date="20240715") print(summary_date) # Shows counts restricted to trips active on 2024-07-15 ``` -------------------------------- ### Get Segment Length on Linestring Source: https://github.com/araichev/gtfs_kit_docs/blob/master/index.html Calculates the distance between two projected points on a Shapely linestring. If only one point is provided, it calculates the distance from the start of the linestring to that point's projection. ```python gtfs_kit.helpers.get_segment_length(_linestring: LineString_, _p: Point_, _q: Point | None = None_) -> float ``` -------------------------------- ### gtfs_kit.routes.build_route_timetable Source: https://github.com/araichev/gtfs_kit_docs/blob/master/index.html Returns a timetable for a given route and dates, including trip and stop time information. ```APIDOC ## gtfs_kit.routes.build_route_timetable ### Description Return a timetable for the given route and dates (YYYYMMDD date strings). Return a table whose columns are all those in `feed.trips` plus those in `feed.stop_times` plus `'date'`. The trip IDs are restricted to the given route ID. The result is sorted first by date then by grouping by trip ID and sorting the groups by their first departure time. Skip dates outside of the Feed’s dates. If there is no route activity on the given dates, then return an empty table. ### Parameters - **feed** (Feed) - The GTFS Feed object. - **route_id** (str) - The ID of the route. - **dates** (list[str]) - A list of YYYYMMDD date strings. ### Returns - pd.DataFrame - A DataFrame representing the route timetable. ``` -------------------------------- ### Build Route Timetable Source: https://github.com/araichev/gtfs_kit_docs/blob/master/index.html Constructs a timetable DataFrame for a specified route ID and a list of dates. The resulting table includes all columns from feed.trips and feed.stop_times, plus a 'date' column. ```python feed.build_route_timetable(route_id='route1', dates=['20230101', '20230102']) ``` -------------------------------- ### build_route_timetable Source: https://github.com/araichev/gtfs_kit_docs/blob/master/index.html Generates and returns a timetable for a specified route ID and a list of dates (YYYYMMDD format). The resulting table includes columns from 'feed.trips', 'feed.stop_times', and an added 'date' column. ```APIDOC ## build_route_timetable ### Description Return a timetable for the given route and dates (YYYYMMDD date strings). Return a table whose columns are all those in `feed.trips` plus those in `feed.stop_times` plus `'date'`. The trip IDs are restricted to the given route ID. ### Method feed.build_route_timetable(_route_id: str_, _dates: list[str]_) ### Returns pd.DataFrame ``` -------------------------------- ### copy Source: https://github.com/araichev/gtfs_kit_docs/blob/master/index.html Creates and returns a shallow copy of the current Feed object. ```APIDOC ## copy ### Description Return a copy of this feed, that is, a feed with all the same attributes. ### Method `copy() -> Feed` ### Parameters None ### Request Example None ### Response #### Success Response (200) - **Feed** (object) - A copy of the original Feed object. #### Response Example None ``` -------------------------------- ### Get Distance Conversion Function Source: https://github.com/araichev/gtfs_kit_docs/blob/master/index.html Returns a function that converts distances between specified units. Supports units defined in constants.DIST_UNITS. ```python gtfs_kit.helpers.get_convert_dist(_dist_units_in: str_, _dist_units_out: str_) -> Callable[[float], float] ``` -------------------------------- ### gtfs_kit.trips.get_trips Source: https://context7.com/araichev/gtfs_kit_docs/llms.txt Returns `feed.trips`, optionally filtered to trips that start on a given date and are in service at a given time. Can return a GeoDataFrame of trip shapes when `as_gdf=True`. ```APIDOC ## `gtfs_kit.trips.get_trips` — Query active trips Returns `feed.trips`, optionally filtered to trips that start on a given date and are in service at a given time. Can return a GeoDataFrame of trip shapes when `as_gdf=True`. ### Parameters - `date` (str, optional): Filter trips that start on this date in 'YYYYMMDD' format. - `time` (str, optional): Filter trips that are in service at this time (e.g., '08:30:00'). - `as_gdf` (bool, optional): If True, return a GeoDataFrame of trip shapes. Defaults to False. - `use_utm` (bool, optional): If True and `as_gdf` is True, project geometries to UTM. Defaults to False. ### Returns pandas.DataFrame or geopandas.GeoDataFrame: A DataFrame or GeoDataFrame of trips, optionally with geometry. ``` -------------------------------- ### gtfs_kit.helpers.make_html Source: https://github.com/araichev/gtfs_kit_docs/blob/master/index.html Converts a dictionary into an HTML table with two columns: keys and values. ```APIDOC ## gtfs_kit.helpers.make_html ### Description Convert the given dictionary into an HTML table (string) with two columns: keys of dictionary, values of dictionary. ### Parameters None ### Returns - **str**: An HTML table string. ``` -------------------------------- ### Get Stops in Area using GeoDataFrame Source: https://context7.com/araichev/gtfs_kit_docs/llms.txt Reads a GeoJSON file defining an area and retrieves stops within that area from the GTFS feed. Requires the 'geopandas' library. ```python import geopandas as gpd area = gpd.read_file("downtown_polygon.geojson") stops_in_area = feed.get_stops_in_area(area) print(stops_in_area.shape) ``` -------------------------------- ### gtfs_kit.helpers.make_ids Source: https://github.com/araichev/gtfs_kit_docs/blob/master/index.html Generates a list of unique, sequentially labeled string IDs. ```APIDOC ## gtfs_kit.helpers.make_ids ### Description Return a length `n` list of unique sequentially labelled strings for use as IDs. ### Parameters * **n** (int) - The desired number of IDs. * **prefix** (str, optional) - The prefix for the generated IDs. Defaults to 'id_'. ### Returns - **list[str]**: A list of unique string IDs. ### Example ```python >>> make_ids(11, prefix="s") ['s00', s01', 's02', 's03', 's04', 's05', 's06', 's07', 's08', 's09', 's10'] ``` ``` -------------------------------- ### describe Source: https://github.com/araichev/gtfs_kit_docs/blob/master/index.html Returns a DataFrame containing various feed indicators and values, optionally specialized for a given sample date. ```APIDOC ## describe ### Description Return a DataFrame of various feed indicators and values, e.g., number of routes. Specialize some of those indicators to the given YYYYMMDD sample date string, e.g., number of routes active on the date. ### Method `describe(sample_date: str | None = None) -> pd.DataFrame` ### Parameters #### Path Parameters None #### Query Parameters - **sample_date** (str or None, optional) - A date string in YYYYMMDD format to specialize the indicators. Defaults to None. #### Request Body None ### Request Example None ### Response #### Success Response (200) - **indicator** (string) - The name of the indicator (e.g., 'num_routes'). - **value** (any) - The value of the indicator (e.g., 27). #### Response Example None ``` -------------------------------- ### compute_route_time_series Source: https://github.com/araichev/gtfs_kit_docs/blob/master/index.html Computes route statistics in time series form for trips starting on specified dates. It can optionally split stats by direction and allows for specifying time series frequency. ```APIDOC ## compute_route_time_series ### Description Computes route stats in time series form for the trips that lie in the trip stats subset, which defaults to the output of [`trips.compute_trip_stats()`](#gtfs_kit.trips.compute_trip_stats "gtfs_kit.trips.compute_trip_stats"), and that start on the given dates (YYYYMMDD date strings). If `split_directions`, then separate each routes’s stats by trip direction. Specify the time series frequency with a Pandas frequency string, e.g. `'5Min'`. Return a time series DataFrame with the following columns. * `datetime`: datetime object * `route_id` * `direction_id`: direction of route; presest if and only if `split_directions` * `num_trips`: number of trips in service on the route at any time within the time bin * `num_trip_starts`: number of trips that start within the time bin * `num_trip_ends`: number of trips that end within the time bin, ignoring trips that end past midnight * `service_distance`: sum of the service distance accrued during the time bin across all trips on the route; measured in kilometers if `feed.dist_units` is metric; otherwise measured in miles; * `service_duration`: sum of the service duration accrued during the time bin across all trips on the route; measured in hours * `service_speed`: `service_distance/service_duration` for the route ### Parameters #### Path Parameters - `_dates` (list[str]): A list of date strings in YYYYMMDD format. - `_trip_stats` (pd.DataFrame | None): Optional pre-computed trip statistics. - `_freq` (str): The time series frequency (default: 'h'). - `split_directions` (bool): Whether to split stats by direction (default: False). ### Notes * If you’ve already computed trip stats in your workflow, then you should pass that table into this function to speed things up significantly. * See the notes for `compute_route_time_series_0()` * Raise a ValueError if `split_directions` and no non-null direction ID values present ``` -------------------------------- ### map_routes Source: https://github.com/araichev/gtfs_kit_docs/blob/master/index.html Generates a map visualization for specified routes. ```APIDOC ## map_routes ### Description Generates a map visualization for specified routes, with options to filter by route IDs or short names, customize the color palette, and show stops. ### Method Signature `map_routes(_route_ids: Iterable[str] | None = None_, _route_short_names: Iterable[str] | None = None_, _color_palette: Iterable[str] = ['#66c2a5', '#fc8d62', '#8da0cb', '#e78ac3', '#a6d854', '#ffd92f', '#e5c494', '#b3b3b3']_, _*_, _show_stops: bool = False_)` ``` -------------------------------- ### Query Active Trips Source: https://context7.com/araichev/gtfs_kit_docs/llms.txt Returns GTFS trips, optionally filtered to trips that start on a given date and are in service at a given time. Can return a GeoDataFrame of trip shapes when `as_gdf=True`. ```python import gtfs_kit as gk feed = gk.read_feed("gtfs.zip", dist_units="km") # All trips on a date trips_on_date = feed.get_trips(date="20240715") # Trips in service at a specific time trips_at_time = feed.get_trips(date="20240715", time="08:30:00") # As GeoDataFrame of LineStrings (requires feed.shapes) trips_gdf = feed.get_trips( date="20240715", as_gdf=True, use_utm=False, ) print(trips_gdf.crs) print(trips_gdf.geometry.geom_type.unique()) ``` -------------------------------- ### gtfs_kit.calendar.get_first_week Source: https://github.com/araichev/gtfs_kit_docs/blob/master/index.html Returns a list of YYYYMMDD date strings for the first Monday-Sunday week for which the Feed is valid. Optionally returns datetime.date objects. ```APIDOC ## gtfs_kit.calendar.get_first_week ### Description Return a list of YYYYMMDD date strings for the first Monday–Sunday week (or initial segment thereof) for which the given Feed is valid. If the feed has no Mondays, then return the empty list. If `as_date_obj`, then return date objects, otherwise return date strings. ### Parameters - **feed** (Feed) - The GTFS Feed object. - **as_date_obj** (bool) - If True, return datetime.date objects; otherwise, return date strings. Defaults to False. ### Returns - list[str] or list[datetime.date] - A list of dates for the first week. ``` -------------------------------- ### compute_stop_activity Source: https://github.com/araichev/gtfs_kit_docs/blob/master/index.html Marks stops as active or inactive on specified dates. A stop is considered active if any trip starting on that date visits it. Returns a DataFrame indicating activity for each stop on each provided date. ```APIDOC ## compute_stop_activity(dates: list[str]) -> pd.DataFrame ### Description Marks stops as active or inactive on the given dates (YYYYMMDD date strings). A stop is _active_ on a given date if some trips that starts on the date visits the stop (possibly after midnight). ### Parameters #### Path Parameters - **dates** (list[str]) - Required - A list of date strings in YYYYMMDD format. ### Response #### Success Response - **stop_id** (string) - The unique identifier for the stop. - **dates[0]** (integer) - 1 if the stop has at least one trip visiting it on the first date in the input list; 0 otherwise. - **dates[1]** (integer) - 1 if the stop has at least one trip visiting it on the second date in the input list; 0 otherwise. - **etc.** - **dates[-1]** (integer) - 1 if the stop has at least one trip visiting it on the last date in the input list; 0 otherwise. If all dates lie outside the Feed period, then return an empty DataFrame. ``` -------------------------------- ### Get Peak Indices from Time Series Source: https://github.com/araichev/gtfs_kit_docs/blob/master/index.html Identifies the indices corresponding to the longest period of maximum trip counts within a given time series. Assumes times and counts have the same non-zero length. ```python gtfs_kit.helpers.get_peak_indices(_times: list_, _counts: list_) -> array ``` ```python >>> times = [0, 10, 20, 30, 31, 32, 40] >>> counts = [7, 1, 2, 7, 7, 1, 2] >>> get_peak_indices(times, counts) array([0, 1]) ``` ```python >>> counts = [0, 0, 0] >>> times = [18000, 21600, 28800] >>> get_peak_indices(times, counts) array([0, 3]) ``` -------------------------------- ### gtfs_kit.shapes.build_geometry_by_shape Source: https://github.com/araichev/gtfs_kit_docs/blob/master/index.html Builds a dictionary of Shapely LineStrings representing shapes, with an option for UTM coordinates. ```APIDOC ## gtfs_kit.shapes.build_geometry_by_shape ### Description Return a dictionary of the form -> . If the Feed has no shapes, then return the empty dictionary. If `use_utm`, then use local UTM coordinates; otherwise, use WGS84 coordinates. ### Parameters - **feed** (Feed) - The GTFS feed object. - **shape_ids** (Iterable[str] | None, optional) - A list of shape IDs to process. Defaults to None (all shapes). - **use_utm** (bool, optional) - If True, use local UTM coordinates. Defaults to False. ``` -------------------------------- ### describe Source: https://github.com/araichev/gtfs_kit_docs/blob/master/index.html Provides a DataFrame summarizing various indicators and values for a GTFS feed, optionally filtered by a sample date. ```APIDOC ## describe ### Description Returns a DataFrame containing various indicators and values for the GTFS feed. Some indicators can be specialized to a given sample date (YYYYMMDD format). ### Parameters * `_feed` (Feed): The GTFS Feed object. * `sample_date` (str | None, optional): A date string in YYYYMMDD format to filter indicators. If None, general feed indicators are returned. Defaults to None. ### Returns pd.DataFrame: A DataFrame with columns 'indicator' and 'value', describing feed statistics. ``` -------------------------------- ### Get Active Trips DataFrame Source: https://github.com/araichev/gtfs_kit_docs/blob/master/index.html Counts the number of active trips over time from a trip_times DataFrame. Assumes 'start_time' and 'end_time' columns exist. Returns a Series indexed by time with the count of active trips. ```python gtfs_kit.helpers.get_active_trips_df(_trip_times: DataFrame_) -> Series ``` -------------------------------- ### gtfs_kit.stops.build_geometry_by_stop Source: https://github.com/araichev/gtfs_kit_docs/blob/master/index.html Builds a dictionary mapping stop IDs to their corresponding Shapely Point geometries. ```APIDOC ## gtfs_kit.stops.build_geometry_by_stop ### Description Return a dictionary of the form -> . Optionally uses UTM projection. ### Parameters - **feed** (Feed) - The GTFS feed object. - **stop_ids** (Iterable[str] | None, optional) - An iterable of stop IDs to process. Defaults to None (all stops). - **use_utm** (bool, optional) - Whether to use UTM projection. Defaults to False. ### Returns - dict - A dictionary mapping stop IDs to Shapely Point objects. ``` -------------------------------- ### build_stop_timetable Source: https://github.com/araichev/gtfs_kit_docs/blob/master/index.html Generates a timetable for a specific stop ID across given dates. The resulting DataFrame includes columns from feed.trips and feed.stop_times, along with the date, and is sorted by date and departure time. ```APIDOC ## build_stop_timetable(_stop_id: str, _dates: list[str]) -> pd.DataFrame ### Description Return a (possibly empty) DataFrame containing the timetable for the given stop ID and dates (YYYYMMDD date strings). The columns are all those in `feed.trips` plus those in `feed.stop_times` plus `'date'`, and the stop IDs are restricted to the given stop ID. The result is sorted by date then departure time. ### Parameters #### Path Parameters - **_stop_id** (str) - Required - The ID of the stop for which to build the timetable. - **_dates** (list[str]) - Required - A list of dates in YYYYMMDD format. ### Response #### Success Response (pd.DataFrame) - A pandas DataFrame containing the stop's timetable, or an empty DataFrame if no activity is found for the given dates. ``` -------------------------------- ### Build Geometry by Stop ID Source: https://github.com/araichev/gtfs_kit_docs/blob/master/index.html Generates a dictionary mapping stop IDs to Shapely Point objects representing the stops. Optionally uses UTM coordinates for local precision. ```python feed.build_geometry_by_stop(use_utm=True) ``` -------------------------------- ### Compute Per-Trip Statistics with compute_trip_stats() Source: https://context7.com/araichev/gtfs_kit_docs/llms.txt Returns a DataFrame with one row per trip containing route info, stop counts, start/end times, distance, duration, speed, and loop/stop-pattern detection. Pass pre-computed trip stats to downstream functions to avoid recomputing them repeatedly. ```python import gtfs_kit as gk feed = gk.read_feed("gtfs.zip", dist_units="km") # All trips trip_stats = feed.compute_trip_stats() print(trip_stats.columns.tolist()) # ['trip_id', 'route_id', 'route_short_name', 'route_type', # 'direction_id', 'shape_id', 'stop_pattern_name', 'num_stops', # 'start_time', 'end_time', 'start_stop_id', 'end_stop_id', # 'is_loop', 'distance', 'duration', 'speed'] # Restrict to specific routes; compute distance from shapes trip_stats_r = feed.compute_trip_stats( route_ids=["route_001", "route_002"], compute_dist_from_shapes=True, ) print(trip_stats_r[["trip_id", "distance", "duration", "speed"]]) ``` -------------------------------- ### Map Trips with Stops and Directions Source: https://context7.com/araichev/gtfs_kit_docs/llms.txt Visualizes specified trip shapes on an interactive Folium map. Can optionally display stop markers and direction arrows. Requires a list of trip IDs. ```python import gtfs_kit as gk feed = gk.read_feed("gtfs.zip", dist_units="km") trip_ids = feed.trips["trip_id"].iloc[:5].tolist() m = feed.map_trips( trip_ids=trip_ids, show_stops=True, show_direction=True, ) m.save("trips_map.html") # open in a browser ``` -------------------------------- ### Map Stops with Custom Styling Source: https://context7.com/araichev/gtfs_kit_docs/llms.txt Generates an interactive Folium map displaying stop locations as circle markers. Allows for custom styling of the markers and requires a list of stop IDs. Raises ValueError for unknown stop IDs. ```python import gtfs_kit as gk feed = gk.read_feed("gtfs.zip", dist_units="km") stop_ids = feed.stops["stop_id"].iloc[:20].tolist() m = feed.map_stops( stop_ids=stop_ids, stop_style={"color": "#1f78b4", "radius": 6, "fillOpacity": 0.8, "weight": 1, "fill": "true"}, ) m.save("stops_map.html") ``` -------------------------------- ### Compute Route Statistics by Date Source: https://context7.com/araichev/gtfs_kit_docs/llms.txt Aggregates trip stats to the route level across given dates. Pass pre-computed trip stats via `trip_stats` for performance. Headway metrics, peak-service windows, service distance/duration/speed are produced. ```python import gtfs_kit as gk feed = gk.read_feed("gtfs.zip", dist_units="km") trip_stats = feed.compute_trip_stats() route_stats = feed.compute_route_stats( dates=["20240715", "20240716"], trip_stats=trip_stats, headway_start_time="06:00:00", headway_end_time="20:00:00", split_directions=True, ) print(route_stats.columns.tolist()) ``` -------------------------------- ### Load GTFS Feed with gtfs_kit.feed.read_feed Source: https://context7.com/araichev/gtfs_kit_docs/llms.txt Load a GTFS feed from a local zip file or a remote URL. Specify distance units for all distance-related outputs. Inspect available tables and their shapes. ```python import gtfs_kit as gk # Load from a local zip feed = gk.read_feed("path/to/gtfs.zip", dist_units="km") # Load directly from a URL feed = gk.read_feed( "https://transitfeeds.com/p/trimet/43/latest/download", dist_units="mi", ) # Inspect available tables print(feed.routes.head()) print(feed.stops.shape) # (num_stops, num_columns) print(feed.trips.columns.tolist()) print(feed.dist_units) # 'mi' ``` -------------------------------- ### gtfs_kit.calendar.get_week Source: https://github.com/araichev/gtfs_kit_docs/blob/master/index.html Given a Feed and an integer k, returns a list of YYYYMMDD date strings for the kth Monday-Sunday week. Optionally returns datetime.date objects. ```APIDOC ## gtfs_kit.calendar.get_week ### Description Given a Feed and a positive integer `k`, return a list of YYYYMMDD date strings corresponding to the kth Monday–Sunday week (or initial segment thereof) for which the Feed is valid. For example, k=1 returns the first Monday–Sunday week (or initial segment thereof). If the Feed does not have k Mondays, then return the empty list. If `as_date_obj`, then return datetime.date objects instead. ### Parameters - **feed** (Feed) - The GTFS Feed object. - **k** (int) - The week number (positive integer). - **as_date_obj** (bool) - If True, return datetime.date objects; otherwise, return date strings. Defaults to False. ### Returns - list[str] or list[datetime.date] - A list of dates for the kth week. ``` -------------------------------- ### gtfs_kit.stops.build_stop_timetable Source: https://github.com/araichev/gtfs_kit_docs/blob/master/index.html Constructs a timetable DataFrame for a specific stop ID across given dates. ```APIDOC ## gtfs_kit.stops.build_stop_timetable ### Description Return a (possibly empty) DataFrame containing the timetable for the given stop ID and dates (YYYYMMDD date strings). The columns are all those in `feed.trips` plus those in `feed.stop_times` plus `'date'`, and the stop IDs are restricted to the given stop ID. The result is sorted by date then departure time. ### Parameters - **feed** (Feed) - The GTFS feed object. - **stop_id** (str) - The ID of the stop for which to build the timetable. - **dates** (list[str]) - A list of dates in YYYYMMDD format. ### Returns - pd.DataFrame - A DataFrame containing the stop's timetable. ``` -------------------------------- ### Build Geometry by Shape ID Source: https://github.com/araichev/gtfs_kit_docs/blob/master/index.html Generates a dictionary mapping shape IDs to Shapely LineString objects representing the shapes. Optionally uses UTM coordinates for local precision. ```python feed.build_geometry_by_shape(use_utm=True) ``` -------------------------------- ### Compute Network-wide Statistics by Date Source: https://context7.com/araichev/gtfs_kit_docs/llms.txt Aggregates all routes and trips to produce network-level stats per date. Pass pre-computed trip stats to speed up workflows. Can split rows per route_type. ```python import gtfs_kit as gk feed = gk.read_feed("gtfs.zip", dist_units="km") trip_stats = feed.compute_trip_stats() network = feed.compute_network_stats( dates=["20240715", "20240716"], trip_stats=trip_stats, split_route_types=True, ) print(network.columns.tolist()) ``` -------------------------------- ### Compute Stop Statistics by Date Source: https://context7.com/araichev/gtfs_kit_docs/llms.txt Computes headway, trip count, route count, and service hours at each stop across the given dates. Accepts an optional list of stop IDs to restrict the computation. ```python import gtfs_kit as gk feed = gk.read_feed("gtfs.zip", dist_units="km") stop_stats = feed.compute_stop_stats( dates=["20240715"], stop_ids=["stop_001", "stop_002", "stop_003"], headway_start_time="07:00:00", headway_end_time="19:00:00", split_directions=False, ) print(stop_stats[["stop_id", "num_routes", "num_trips", "mean_headway", "start_time", "end_time"]]) ``` -------------------------------- ### Generate Unique IDs with Prefix Source: https://github.com/araichev/gtfs_kit_docs/blob/master/index.html Generates a list of unique, sequentially labeled strings for use as IDs. Useful for creating unique identifiers for elements in GTFS data. ```python >>> make_ids(11, prefix="s") ['s00', s01', 's02', 's03', 's04', 's05', 's06', 's07', 's08', 's09', 's10'] ``` -------------------------------- ### Assess GTFS Feed Quality with assess_quality() Source: https://context7.com/araichev/gtfs_kit_docs/llms.txt Returns a DataFrame of quality indicators, such as the number of trips missing shapes. Useful for a quick sanity-check before deeper analysis. ```python import gtfs_kit as gk feed = gk.read_feed("gtfs.zip", dist_units="km") quality = feed.assess_quality() print(quality) # indicator value # 0 num_trips_missing_shapes 5 # 1 num_stop_times_with_null_departure_time 0 # ... ``` -------------------------------- ### build_aggregate_routes_dict Source: https://github.com/araichev/gtfs_kit_docs/blob/master/index.html Builds a dictionary to map old route IDs to new aggregated route IDs based on route short names. This is a helper function for aggregating routes. ```APIDOC ## build_aggregate_routes_dict ### Description Given a DataFrame of routes, group the routes by route short name and assign new route IDs using the given prefix. Return a dictionary of the form -> . ### Parameters - **_routes** (DataFrame) - The DataFrame containing route information. - **by** (str, optional) - The column to group routes by. Defaults to 'route_short_name'. - **route_id_prefix** (str, optional) - The prefix to use for new route IDs. Defaults to 'route_'. ### Returns dict[str, str] - A dictionary mapping old route IDs to new route IDs. ``` -------------------------------- ### clean Source: https://github.com/araichev/gtfs_kit_docs/blob/master/index.html Applies a sequence of cleaning functions to a GTFS Feed object. ```APIDOC ## clean ### Description Apply the following functions to the given Feed in order and return the resulting Feed. 1. `clean_ids()` 2. `clean_times()` 3. `clean_route_short_names()` 4. `drop_zombies()` ### Parameters - **feed** (Feed) - The GTFS Feed object to clean. ### Returns Feed - The cleaned GTFS Feed object. ``` -------------------------------- ### get_first_week Source: https://github.com/araichev/gtfs_kit_docs/blob/master/index.html Retrieves the dates for the first week the GTFS feed is valid, optionally as date objects. ```APIDOC ## get_first_week ### Description Return a list of YYYYMMDD date strings for the first Monday–Sunday week (or initial segment thereof) for which the given Feed is valid. If the feed has no Mondays, then return the empty list. ### Parameters #### Query Parameters - **as_date_obj** (bool, optional) - If True, return datetime.date objects instead of date strings. Defaults to False. ### Returns - list[str] or list[datetime.date]: A list of date strings or date objects for the first week. ``` -------------------------------- ### list_fields Source: https://github.com/araichev/gtfs_kit_docs/blob/master/index.html Lists all fields for GTFS tables within a feed or a specific table. ```APIDOC ## list_fields ### Description Returns a DataFrame that describes all the fields present in the GTFS tables within the given feed. If a specific table name is provided, it lists the fields only for that table. ### Parameters * `_feed` (Feed): The GTFS Feed object. * `table` (str | None, optional): The name of a specific GTFS table to list fields for. If None, lists fields for all tables in the feed. Defaults to None. ### Returns pd.DataFrame: A DataFrame describing the fields of the specified GTFS table(s). ``` -------------------------------- ### gtfs_kit.stops.map_stops Source: https://context7.com/araichev/gtfs_kit_docs/llms.txt Generates an interactive Folium map displaying stop positions as circle markers. Raises ValueError for unknown stop IDs. ```APIDOC ## `gtfs_kit.stops.map_stops` — Visualize stops on an interactive map Returns a Folium map with stop positions rendered as circle markers; raises a `ValueError` for any stop IDs not in the feed. ### Method ```python feed.map_stops( stop_ids: list[str], stop_style: dict = None ) ``` ### Parameters - **stop_ids** (list[str]) - A list of stop IDs to visualize. - **stop_style** (dict, optional) - A dictionary defining the style of the stop markers (e.g., color, radius). Defaults to None. ### Request Example ```python import gtfs_kit as gk feed = gk.read_feed("gtfs.zip", dist_units="km") stop_ids = feed.stops["stop_id"].iloc[:20].tolist() m = feed.map_stops( stop_ids=stop_ids, stop_style={"color": "#1f78b4", "radius": 6, "fillOpacity": 0.8, "weight": 1, "fill": "true"}, ) m.save("stops_map.html") ``` ### Response Returns a Folium map object. ``` -------------------------------- ### Compute Screen Line Counts with GTFS Kit Source: https://context7.com/araichev/gtfs_kit_docs/llms.txt Calculates the number of trips crossing specified screen lines. Requires a GeoDataFrame with 'screen_line_id' and 'geometry' columns. ```python import geopandas as gpd from shapely.geometry import LineString screen_lines = gpd.GeoDataFrame( {"screen_line_id": ["bridge"]}, geometry=[LineString([(-122.68, 45.52), (-122.66, 45.52)])], crs="EPSG:4326", ) counts = feed.compute_screen_line_counts( screen_lines=screen_lines, dates=["20240715"], ) print(counts[["screen_line_id", "trip_id", "route_short_name", "crossing_time", "crossing_direction"]].head()) ``` -------------------------------- ### get_dates Source: https://github.com/araichev/gtfs_kit_docs/blob/master/index.html Returns a list of all valid dates for the GTFS feed, optionally as date objects. ```APIDOC ## get_dates ### Description Return a list of YYYYMMDD date strings for which the given Feed is valid. This could be an empty list if the Feed has no calendar information. ### Parameters #### Query Parameters - **as_date_obj** (bool, optional) - If True, return datetime.date objects instead of date strings. Defaults to False. ### Returns - list[str] or list[datetime.date]: A list of valid dates. ``` -------------------------------- ### gtfs_kit.routes.map_routes Source: https://github.com/araichev/gtfs_kit_docs/blob/master/index.html Generates a Folium map displaying specified routes and optionally their stops. ```APIDOC ## gtfs_kit.routes.map_routes ### Description Return a Folium map showing the given routes and (optionally) their stops. At least one of `route_ids` and `route_short_names` must be given. If both are given, then combine the two into a single set of routes. If any of the given route IDs are not found in the feed, then raise a ValueError. ### Parameters - **feed** (Feed) - The GTFS feed object. - **route_ids** (Iterable[str] | None, optional) - A list of route IDs to display. Defaults to None. - **route_short_names** (Iterable[str] | None, optional) - A list of route short names to display. Defaults to None. - **color_palette** (Iterable[str], optional) - A list of colors to use for the routes. Defaults to a predefined palette. - **show_stops** (bool, optional) - If True, display the stops for the routes. Defaults to False. ``` -------------------------------- ### get_stops Source: https://github.com/araichev/gtfs_kit_docs/blob/master/index.html Retrieves stops, with options to filter by date, trip IDs, route IDs, and to return as a GeoDataFrame. ```APIDOC ## get_stops ### Description Return `feed.stops`. If a YYYYMMDD date string is given, then subset to stops active (visited by trips) on that date. If trip IDs are given, then subset further to stops visited by those trips. If route IDs are given, then ignore the trip IDs and subset further to stops visited by those routes. If `in_stations`, then subset further stops in stations if station data is available. If `as_gdf`, then return the result as a GeoDataFrame with a ‘geometry’ column of points instead of ‘stop_lat’ and ‘stop_lon’ columns. The GeoDataFrame will have a UTM CRS if `use_utm` and a WGS84 CRS otherwise. ### Method Signature `get_stops(_date: str | None = None_, _trip_ids: Iterable[str] | None = None_, _route_ids: Iterable[str] | None = None_, _*_, _in_stations: bool = False_, _as_gdf: bool = False_, _use_utm: bool = False_) -> pd.DataFrame` ``` -------------------------------- ### build_aggregate_stops_dict Source: https://github.com/araichev/gtfs_kit_docs/blob/master/index.html Builds a dictionary to map old stop IDs to new aggregated stop IDs based on stop codes. This is a helper function for aggregating stops. ```APIDOC ## build_aggregate_stops_dict ### Description Given a DataFrame of stops, group the stops by stop code and assign new stop IDs using the given prefix. Return a dictionary of the form -> . ### Parameters - **_stops** (DataFrame) - The DataFrame containing stop information. - **by** (str, optional) - The column to group stops by. Defaults to 'stop_code'. - **stop_id_prefix** (str, optional) - The prefix to use for new stop IDs. Defaults to 'stop_'. ### Returns dict[str, str] - A dictionary mapping old stop IDs to new stop IDs. ``` -------------------------------- ### Resample Time Series Data with GTFS Kit Helper Source: https://context7.com/araichev/gtfs_kit_docs/llms.txt Resamples a time series DataFrame (e.g., from compute_route_time_series) to a coarser Pandas frequency. The data remains unchanged if the requested frequency is finer than the original. ```python import gtfs_kit as gk from gtfs_kit.helpers import downsample feed = gk.read_feed("gtfs.zip", dist_units="km") trip_stats = feed.compute_trip_stats() # Compute 1-minute time series, then downsample ts_route = feed.compute_route_time_series( dates=["20240715"], trip_stats=trip_stats, freq="h", ) ts_4h = downsample(ts_route, "4h") print(ts_4h.head()) ``` -------------------------------- ### gtfs_kit.miscellany.describe Source: https://context7.com/araichev/gtfs_kit_docs/llms.txt Provides a DataFrame summarizing high-level indicators of a GTFS feed, such as the number of routes, trips, and stops. It can optionally be filtered to count entities active on a specific sample date. ```APIDOC ## `gtfs_kit.miscellany.describe` — Quick feed summary Returns a DataFrame of high-level feed indicators (number of routes, trips, stops, etc.) optionally specialised to a sample date so that only entities active on that date are counted. ### Method `describe(sample_date: str = None)` ### Parameters #### Query Parameters - **sample_date** (str) - Optional - A date string in 'YYYYMMDD' format to filter counts for entities active on that date. ### Request Example ```python import gtfs_kit as gk feed = gk.read_feed("gtfs.zip", dist_units="km") # Overall summary summary = feed.describe() print(summary) # Summary for a specific date summary_date = feed.describe(sample_date="20240715") print(summary_date) ``` ### Response #### Success Response (DataFrame) - **summary** (DataFrame) - A DataFrame containing feed indicators. - **summary_date** (DataFrame) - A DataFrame containing feed indicators filtered by the sample date. ### Response Example ```python # Overall summary output example: # indicator value # 0 num_routes 42 # 1 num_stops 512 # ... # Summary for a specific date output example: # Shows counts restricted to trips active on 2024-07-15 ``` ``` -------------------------------- ### gtfs_kit.miscellany.compute_network_stats Source: https://context7.com/araichev/gtfs_kit_docs/llms.txt Aggregates all routes and trips to produce network-level stats per date: total stops/routes/trips, peak service window, total service distance/duration/speed. Pass pre-computed trip stats to speed up workflows. ```APIDOC ## `gtfs_kit.miscellany.compute_network_stats` — Network-wide statistics by date Aggregates all routes and trips to produce network-level stats per date: total stops/routes/trips, peak service window, total service distance/duration/speed. Pass pre-computed trip stats to speed up workflows. ### Parameters - `dates` (list[str]): A list of dates in 'YYYYMMDD' format to compute stats for. - `trip_stats` (pandas.DataFrame, optional): Pre-computed trip statistics. If not provided, it will be computed internally. - `split_route_types` (bool, optional): If True, statistics will be separated by route type. Defaults to False. ### Returns pandas.DataFrame: A DataFrame containing network-level statistics for the specified dates. ``` -------------------------------- ### build_geometry_by_shape Source: https://github.com/araichev/gtfs_kit_docs/blob/master/index.html Returns a dictionary mapping shape IDs to their corresponding Shapely LineString representations. If the Feed has no shapes, an empty dictionary is returned. Optionally uses local UTM coordinates if `use_utm` is True. ```APIDOC ## build_geometry_by_shape ### Description Return a dictionary of the form -> . If the Feed has no shapes, then return the empty dictionary. If `use_utm`, then use local UTM coordinates; otherwise, use WGS84 coordinates. ### Method feed.build_geometry_by_shape(_shape_ids: Iterable[str] | None = None_, _*_, _use_utm: bool = False_) ### Returns dict ``` -------------------------------- ### gtfs_kit.miscellany.create_shapes Source: https://context7.com/araichev/gtfs_kit_docs/llms.txt Generates straight-line shapes for trips that are missing shape information, enabling geometric analysis on incomplete datasets. ```APIDOC ## `gtfs_kit.miscellany.create_shapes` — Generate synthetic shapes Creates straight-line shapes from stop sequences for trips that are missing a `shape_id`, making it possible to compute geometric stats on feeds that lack shapes data. ### Method ```python feed.create_shapes( all_trips: bool = False ) ``` ### Parameters - **all_trips** (bool, optional) - If True, generates shapes for all trips, overwriting existing ones. Defaults to False. ### Request Example ```python import gtfs_kit as gk feed = gk.read_feed("gtfs.zip", dist_units="km") # Trips without shapes: count before missing_before = feed.trips["shape_id"].isna().sum() # Add straight-line shapes for trips missing them feed_with_shapes = feed.create_shapes() missing_after = feed_with_shapes.trips["shape_id"].isna().sum() print(f"Before: {missing_before} missing shapes") print(f"After: {missing_after} missing shapes") # Optionally regenerate ALL trip shapes (overwrites existing shapes) feed_rebuilt = feed.create_shapes(all_trips=True) ``` ### Response Returns a new `Feed` object with synthetic shapes added for trips that were missing them. ``` -------------------------------- ### gtfs_kit.routes.compute_route_time_series Source: https://context7.com/araichev/gtfs_kit_docs/llms.txt Computes route-level stats in a long-form time series at a configurable Pandas frequency (e.g., hourly 'h', 15-minute '15min'), returning columns `datetime`, `route_id`, `num_trips`, `num_trip_starts`, `num_trip_ends`, `service_distance`, `service_duration`, and `service_speed`. ```APIDOC ## `gtfs_kit.routes.compute_route_time_series` — Route time series Computes route-level stats in a long-form time series at a configurable Pandas frequency (e.g., hourly `'h'`, 15-minute `'15min'`), returning columns `datetime`, `route_id`, `num_trips`, `num_trip_starts`, `num_trip_ends`, `service_distance`, `service_duration`, and `service_speed`. ### Parameters - `dates` (list[str]): A list of dates in 'YYYYMMDD' format to compute stats for. - `trip_stats` (pandas.DataFrame, optional): Pre-computed trip statistics. If not provided, it will be computed internally. - `freq` (str): The Pandas frequency string for the time series (e.g., 'h', '30min', '15min'). - `split_directions` (bool, optional): If True, statistics will be computed separately for each direction of a route. Defaults to False. ### Returns pandas.DataFrame: A DataFrame containing route-level statistics in a time series format. ``` -------------------------------- ### Aggregate Routes by Short Name Source: https://github.com/araichev/gtfs_kit_docs/blob/master/index.html Aggregates routes based on their short names and assigns new route IDs with a specified prefix. This function updates relevant Feed tables. ```python feed.aggregate_routes(_by='route_short_name', _route_id_prefix='route_') ``` -------------------------------- ### to_file Source: https://github.com/araichev/gtfs_kit_docs/blob/master/index.html Writes the GTFS feed to a specified file path, either as a zip archive or a directory of CSV files. Allows control over decimal precision. ```APIDOC ## to_file ### Description Write this Feed to the given path. If the path ends in ‘.zip’, then write the feed as a zip archive. Otherwise assume the path is a directory, and write the feed as a collection of CSV files to that directory, creating the directory if it does not exist. Round all decimals to `ndigits` decimal places, if given. All distances will be the distance units `feed.dist_units`. By the way, 6 decimal degrees of latitude and longitude is enough to locate an individual cat. ### Method `to_file(path: Path, ndigits: int | None = None)` ### Parameters #### Path Parameters - **path** (Path) - Required - The path to write the feed to. Can be a directory or a .zip file. - **ndigits** (int | None) - Optional - The number of decimal places to round to. ``` -------------------------------- ### gtfs_kit.shapes.split_simple_0 Source: https://github.com/araichev/gtfs_kit_docs/blob/master/index.html Splits a single LineString into simple sub-LineStrings. ```APIDOC ## gtfs_kit.shapes.split_simple_0 ### Description Split the given LineString into simple sub-LineStrings by greedily building the segments from the LineString points and binary search, checking for simplicity at every step. ### Parameters #### Path Parameters - **ls** (LineString) - Required - The LineString to split. ### Returns - list[LineString] - A list of simple sub-LineStrings. ``` -------------------------------- ### create_shapes Source: https://github.com/araichev/gtfs_kit_docs/blob/master/index.html Creates new shapes for trips that are missing shape IDs by connecting their stops. ```APIDOC ## create_shapes ### Description Generates a shape for every trip in the feed that does not have an associated shape ID. This is done by creating straight line segments connecting the stops of each trip. The function returns the feed with updated shapes and trips tables. ### Parameters * `_feed` (Feed): The GTFS Feed object. * `all_trips` (bool, optional): If True, creates new shapes for all trips by connecting their stops and removes the old shapes. Defaults to False. ### Returns Feed: The GTFS Feed object with newly created shapes for trips. ```