Metadata-Version: 2.4
Name: transitfreq
Version: 0.1.2
Summary: Transit service frequency analysis for GTFS Schedule feeds: trips per hour, headways, span of service, frequent network maps, TCQSM quality-of-service bands and GeoJSON export, pure Python.
Author-email: Yusuf Eminoğlu <geospacephilo@gmail.com>
License-Expression: MIT
Project-URL: Homepage, https://gitlab.com/geophilo1/transitfreq_sdk
Project-URL: Repository, https://gitlab.com/geophilo1/transitfreq_sdk
Project-URL: Documentation, https://gitlab.com/geophilo1/transitfreq_sdk#readme
Project-URL: Issues, https://gitlab.com/geophilo1/transitfreq_sdk/-/work_items
Project-URL: Changelog, https://gitlab.com/geophilo1/transitfreq_sdk/-/blob/main/CHANGELOG.md
Project-URL: SDK dashboard, https://geophilo.com/sdk-dashboard/
Project-URL: DOI, https://doi.org/10.5281/zenodo.24122205
Keywords: gtfs,gtfs-schedule,transit,public-transport,headway,service-frequency,trips-per-hour,frequent-network,span-of-service,tcqsm,level-of-service,transit-planning,geojson,gis
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Education
Classifier: Environment :: Console
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: GIS
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: pandas
Requires-Dist: pandas>=1.3.0; extra == "pandas"
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
Requires-Dist: ruff>=0.1.0; extra == "dev"
Requires-Dist: mypy>=1.0.0; extra == "dev"
Dynamic: license-file

<p align="center">
  <a href="https://geophilo.com/sdk-dashboard/"><img src="https://geophilo.com/assets/sdk_icons/transitfreq_sdk.svg" width="120" height="120" alt="transitfreq icon"></a>
</p>

# transitfreq

[![PyPI version](https://img.shields.io/pypi/v/transitfreq.svg)](https://pypi.org/project/transitfreq/)
[![Python versions](https://img.shields.io/pypi/pyversions/transitfreq.svg)](https://pypi.org/project/transitfreq/)
[![pipeline status](https://gitlab.com/geophilo1/transitfreq_sdk/badges/main/pipeline.svg)](https://gitlab.com/geophilo1/transitfreq_sdk/-/pipelines)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://gitlab.com/geophilo1/transitfreq_sdk/-/blob/main/LICENSE)
[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.24122205.svg)](https://doi.org/10.5281/zenodo.24122205)
[![Downloads](https://static.pepy.tech/badge/transitfreq/month)](https://pepy.tech/project/transitfreq)

**Transit service frequency analysis from a GTFS Schedule feed.**

`transitfreq` answers the everyday service-planning questions about a GTFS feed for
one date: which services run, how many trips per hour each route and stop gets, what
the average and worst headways are in a time window, how long the span of service is,
which routes and stops form the *frequent network*, and how they fall into the
TCQSM quality-of-service bands. Results export to CSV/JSON and to GeoJSON with the
frequency attributes attached, ready for QGIS or a web map.

- Reads a `.zip` or an unpacked folder, streaming `stop_times.txt` and `shapes.txt` with the standard `csv` module.
- No runtime dependencies (standard library only); `pandas` is an optional extra.
- Resolves `calendar.txt` + `calendar_dates.txt`, expands `frequencies.txt`, interpolates untimed stops, handles times past `24:00:00`.
- Command line tool and a small, typed Python API.

```bash
pip install transitfreq            # stdlib only
pip install "transitfreq[pandas]"  # + DataFrame helpers
```

Requires Python 3.9 or newer.

> `transitfreq` does not validate feeds. Check a feed first with a validator such as
> [`gtfslint-cli`](https://pypi.org/project/gtfslint-cli/) (`pip install gtfslint-cli`)
> or the MobilityData GTFS Validator; broken calendars or stop times give misleading
> frequencies.

---

## Quick start (command line)

```bash
# What runs on that date?
transitfreq services gtfs.zip --date 2024-05-06

# Route / direction summary for the AM peak and midday, as CSV
transitfreq routes gtfs.zip --date 2024-05-06 \
    --window 07:00-09:00 --window 09:00-15:00 --format csv -o routes.csv

# Combined headways at each stop (platforms grouped by parent station)
transitfreq stops gtfs.zip --date 2024-05-06 --by-station --format csv -o stops.csv

# Frequent network: 10 minutes or better, 06:00-21:00, every direction
transitfreq frequent gtfs.zip --date 2024-05-06 --threshold 10 --window 06:00-21:00

# Trips per hour per route and direction
transitfreq tph gtfs.zip --date 2024-05-06 --by route_direction --format csv

# GeoJSON layers with frequency attributes
transitfreq geojson gtfs.zip --date 2024-05-06 --stops stops.geojson --routes routes.geojson

transitfreq summary gtfs.zip --date 2024-05-06
```

Common options: `--window HH:MM-HH:MM` (repeatable, default `07:00-19:00`),
`--threshold` (frequent headway in minutes, default 15), `--frequent-window`,
`--measure max|mean`, `--any-direction`, `--include-previous-day`,
`--format table|csv|json`, `-o FILE`. `python -m transitfreq` works too.

## Quick start (Python)

```python
import transitfreq as tf

day = tf.ServiceDay("gtfs.zip", "2024-05-06")
print(sorted(day.service_ids))

for r in day.route_summaries(["07:00-09:00", "09:00-15:00"]):
    am = r.windows[0]
    print(r.route_name, r.direction_id, am.trips_per_hour, am.mean_headway_min,
          am.max_headway_min, r.frequency_los[am.window], r.hours_of_service, r.hours_los)

for s in day.stop_summaries(by_station=True):
    print(s.stop_name, s.route_ids, s.windows[0].mean_headway_min, s.frequent)

print(day.frequent_routes())                                    # <= 15 min, 07:00-19:00
print(day.frequent_routes(tf.FrequentCriteria(max_headway_min=10,
                                              windows=("06:00-21:00",))))

tf.write_geojson(tf.stops_geojson(day), "stops.geojson")
tf.write_geojson(tf.routes_geojson(day), "routes.geojson")
```

A runnable example over the bundled synthetic feed is in
[`examples/quickstart.py`](https://gitlab.com/geophilo1/transitfreq_sdk/-/blob/main/examples/quickstart.py).

## API overview

| Object | Purpose |
|---|---|
| `GTFSFeed(path)` / `load_feed(path)` | Zip or folder; `iter_rows(file)` streams any table; cached `stops`, `routes`, `trips`, `frequencies`; `shapes(ids)` |
| `active_service_ids(feed, date)` | `service_id`s running on a date (`calendar` + `calendar_dates`) |
| `service_departures(feed, date, include_previous_day=False)` | Every stop event of the service day as `Departure(time, stop_id, trip_id, route_id, direction_id, stop_sequence, first_stop, boarding)`, with `frequencies.txt` expanded |
| `ServiceDay(feed, date, ...)` | The analysis object below |
| `.route_summaries(windows)` | `RouteSummary` per route and direction (trip start times): trips, first/last trip, span, hours of service, peak trips/h, per-window `HeadwayStats`, LOS bands, `frequent` |
| `.stop_summaries(windows, by_station=False, route_ids=None)` | `StopSummary` per stop or parent station, all routes combined |
| `.trips_per_hour(by)` | Hourly counts by `route`, `route_direction`, `stop` or `stop_route` |
| `.frequent_routes(criteria)`, `.frequent_stops(criteria)` | The frequent network under a `FrequentCriteria` |
| `.summary()` | System overview |
| `headway_stats(times, window)`, `span_of_service(times)`, `tcqsm_hours_of_service(times)`, `trips_per_hour(times)` | Pure functions on sorted departure times |
| `frequency_los(headway, table)`, `hours_of_service_los(hours, table)` | Quality-of-service bands; `TCQSM_*` (3rd ed.) or `TCQSM2_*` (2nd ed. letters) tables, or your own `FrequencyBand` / `HoursBand` list |
| `stops_geojson(day)`, `routes_geojson(day)`, `write_geojson(fc, path)` | GeoJSON export |
| `transitfreq.pandas_ext` | `departures_frame`, `stops_frame`, `routes_frame` |

Every summary has `.as_dict()` giving flat columns such as `0700-0900_trips_per_hour`,
`0700-0900_mean_headway_min`, `0700-0900_max_headway_min` and `0700-0900_frequency_los`.

## Method and sources

**Service calendar.** A `service_id` is active when `calendar.txt` covers the date and the
weekday flag is 1, then `calendar_dates.txt` adds (`exception_type=1`) or removes (`2`) it
for that date ([GTFS Schedule Reference](https://gtfs.org/documentation/schedule/reference/)).
Feeds that use only `calendar_dates.txt` work.

**Service day and times.** GTFS times count from the start of the service day and may
exceed 24:00:00; they are kept as seconds since the start of the service day. With
`include_previous_day=True` the after-midnight part of the previous day's trips is added,
shifted by -24 h.

**Frequency-based trips.** For each `frequencies.txt` row, trips start at
`start_time, start_time + headway_secs, ...` strictly before `end_time`, and the template
trip's stop-time offsets are replayed for each start. `exact_times=0` and `1` are expanded
the same way.

**Untimed stops** are interpolated linearly by stop order between the surrounding timed
stops.

**Departures that count.** At stops, only boarding opportunities count: the last stop of a
trip and stops with `pickup_type=1` are excluded. Routes are measured at trip start times
(the first stop of each trip), per direction.

**Headway measures** for a half-open window `[start, end)` holding `n` departures:

| Measure | Definition |
|---|---|
| trips per hour | `n / window hours` |
| mean headway | `window minutes / n`, i.e. 60 / vehicles per hour, the TCQSM "average headway" |
| mean gap | average interval between consecutive departures in the window |
| max headway | longest wait for a passenger arriving at any moment in the window: largest difference in `[start, t1, ..., tn, end]` |

Worked example: departures at 07:00, 07:05 and 07:30 in 07:00-08:00 give 3 trips/h, a mean
headway of 20 min, a mean gap of 15 min and a max headway of 30 min (07:30 to 08:00).

**Span and hours of service.** `span_hours` is last minus first departure.
`hours_of_service` follows TCQSM 3rd ed., Chapter 5, p. 5-7: for service at least hourly,
last minus first departure plus 1 h, rounded down; for hourly-or-worse service, the
number of departures. Days that mix both are split into runs with gaps of at most 60 min
and the first rule is applied to each run. The manual's examples are reproduced in the
tests: every 30 min from 05:30 to 20:00 gives 15 h; departures at 5:30, 6:30, 7:30, 10:00,
13:00, 15:30, 16:30 and 17:30 give 8 h.

**Quality-of-service bands.** The default tables come from TCRP Report 165, *Transit
Capacity and Quality of Service Manual*, 3rd ed. (TRB, 2013), Chapter 5:

| Exhibit 5-2: average headway | Exhibit 5-3: hours of service |
|---|---|
| `<=5 min`, `>5-10 min`, `11-15 min`, `16-30 min`, `31-59 min`, `60 min`, `>60 min` | `>18 h`, `15-18 h`, `12-14 h`, `7-11 h`, `4-6 h`, `<4 h` |

The 3rd edition attaches **no A-F letter grades** to these measures (p. 5-1), so band
labels are returned. For non-integer averages the ranges are closed upward (10.5 min falls
in `11-15 min`). For users who need letters, `TCQSM2_FREQUENCY_LOS` and `TCQSM2_HOURS_LOS`
give the 2nd edition (TCRP Report 100, 2003) A-F grades, but these values were **not
checked against the primary document** for this release. All thresholds are
configurable: pass any list of `FrequencyBand` / `HoursBand` as `frequency_table=` /
`hours_table=`.

**Frequent network.** The default `FrequentCriteria()` is *15 min or better, 07:00-19:00,
in every direction, measured by max headway*. This is a common planning convention used
in frequent network maps (J. Walker, *Human Transit*, 2012), and TCQSM Exhibit 5-2 notes
that 11-15 min service is "often branded as 'frequent service'". It is not a standard:
the threshold, windows, measure (`max` or `mean`) and direction rule can all be changed.

**GeoJSON.** Stops are Points with `StopSummary` attributes. Routes are one
MultiLineString per route and direction built from every distinct `shapes.txt` shape used
that day; route directions without usable shapes (no `shape_id`, or a shape missing from
`shapes.txt`) fall back to straight segments between their stops (`geometry_source` tells
which). Coordinates are WGS 84 longitude/latitude (RFC 7946).

## Limitations

- Scheduled service only: no GTFS Realtime, no reliability or headway adherence measures.
- No feed validation (see `gtfslint-cli`), no `timezone` handling, no GTFS-Flex or `location_groups`.
- Route-level figures use trip start times; on branching or short-turn routes, all starts in a direction are pooled.
- Combined stop headways count every route equally, even when two routes leave within the same minute.
- Untimed stops are interpolated by stop order, not by `shape_dist_traveled`.
- All active stop times of the chosen date are held in memory (the whole feed is not); very large feeds need a few hundred MB for a busy weekday.
- `exact_times=0` frequency trips are placed exactly at `start_time + k * headway_secs`.

## Development

```bash
git clone https://gitlab.com/geophilo1/transitfreq_sdk.git
cd transitfreq_sdk
pip install -e ".[dev,pandas]"
python -m pytest
python -m ruff check . && python -m ruff format --check src tests
python -m mypy
```

The tests use a small synthetic GTFS feed in `tests/data/mini_gtfs` (frequency-based and
scheduled trips, a holiday exception, a calendar_dates-only service, a parent station,
untimed stops, a trip past midnight and a shape) with hand-computed expected values.

## Academic citation

```bibtex
@software{eminoglu_transitfreq,
  author  = {Eminoğlu, Yusuf},
  title   = {transitfreq},
  year    = {2026},
  version = {0.1.2},
  doi     = {10.5281/zenodo.24122205},
  url     = {https://gitlab.com/geophilo1/transitfreq_sdk}
}
```

See also [`CITATION.cff`](https://gitlab.com/geophilo1/transitfreq_sdk/-/blob/main/CITATION.cff).

## Related Geophilo SDKs

- [gtfslint-cli](https://pypi.org/project/gtfslint-cli/): pure-Python GTFS Schedule validator and feed quality report.
- [routematrix](https://pypi.org/project/routematrix/): origin-destination travel-time and distance matrices from OSRM, Valhalla, GraphHopper and openrouteservice.
- [todindex](https://pypi.org/project/todindex/): transit-oriented development assessment of station areas.
- [odflows](https://pypi.org/project/odflows/): origin-destination flow toolkit for mobility and commuting analysis.

## License

MIT License, copyright (c) 2026 Yusuf Eminoğlu. See [LICENSE](https://gitlab.com/geophilo1/transitfreq_sdk/-/blob/main/LICENSE).
Contact: geospacephilo@gmail.com
