Skip to content

transitmatters.models

Data models returned by the client, e.g. Headway or RouteStops.

Every model is a frozen dataclass. Times are timezone-aware datetimes in Eastern time (America/New_York), dates are datetime.dates, and missing values are None.

transitmatters.to_dataframe turns a list of models into a pandas DataFrame; Model.to_dict gives one model as a dict.

Model dataclass

Model()

Base class for every model.

to_dict

to_dict() -> dict[str, Any]

The fields as a dict, with nested models as dicts too.

Source code in src/transitmatters/models.py
def to_dict(self) -> dict[str, Any]:
    """The fields as a dict, with nested models as dicts too."""
    return dataclasses.asdict(self)

Headway dataclass

Headway(
    *,
    route_id: str,
    direction: int,
    current_dep_dt: datetime,
    headway_time_sec: float,
    benchmark_headway_time_sec: float | None,
    vehicle_label: str,
    vehicle_consist: tuple[str, ...],
)

Bases: Model

The time between two consecutive departures from a stop.

route_id instance-attribute

route_id: str

Route of the departing trip, e.g. "Red", "28", "CR-Fairmount".

direction instance-attribute

direction: int

Direction ID, 0 or 1. transitmatters.TransitMatters.stops names them.

current_dep_dt instance-attribute

current_dep_dt: datetime

Departure time.

headway_time_sec instance-attribute

headway_time_sec: float

Seconds since the previous departure.

benchmark_headway_time_sec instance-attribute

benchmark_headway_time_sec: float | None

Scheduled headway in seconds, if known.

vehicle_label instance-attribute

vehicle_label: str

Vehicle label; may be empty.

vehicle_consist instance-attribute

vehicle_consist: tuple[str, ...]

Car numbers, e.g. ("1850", "1851"); empty when unknown.

Dwell dataclass

Dwell(
    *,
    route_id: str,
    direction: int,
    arr_dt: datetime,
    dep_dt: datetime,
    dwell_time_sec: float,
    vehicle_label: str,
    vehicle_consist: tuple[str, ...],
)

Bases: Model

The time a vehicle spent stopped at a stop.

route_id instance-attribute

route_id: str

Route of the trip, e.g. "Red", "1", "CR-Fairmount".

direction instance-attribute

direction: int

Direction ID, 0 or 1.

arr_dt instance-attribute

arr_dt: datetime

Arrival time.

dep_dt instance-attribute

dep_dt: datetime

Departure time.

dwell_time_sec instance-attribute

dwell_time_sec: float

Seconds between arrival and departure.

vehicle_label instance-attribute

vehicle_label: str

Vehicle label; may be empty.

vehicle_consist instance-attribute

vehicle_consist: tuple[str, ...]

Car numbers; empty when unknown.

TravelTime dataclass

TravelTime(
    *,
    route_id: str,
    direction: int,
    dep_dt: datetime,
    arr_dt: datetime,
    travel_time_sec: float,
    benchmark_travel_time_sec: float | None,
    tm_benchmark_travel_time_sec: float | None,
    vehicle_label: str,
    vehicle_consist: tuple[str, ...],
)

Bases: Model

One trip's travel time between an origin and a destination stop.

route_id instance-attribute

route_id: str

Route of the trip, e.g. "Red", "28", "CR-Fairmount".

direction instance-attribute

direction: int

Direction ID, 0 or 1.

dep_dt instance-attribute

dep_dt: datetime

Departure time from the origin.

arr_dt instance-attribute

arr_dt: datetime

Arrival time at the destination.

travel_time_sec instance-attribute

travel_time_sec: float

Travel time in seconds.

benchmark_travel_time_sec instance-attribute

benchmark_travel_time_sec: float | None

Scheduled travel time in seconds, if known.

tm_benchmark_travel_time_sec instance-attribute

tm_benchmark_travel_time_sec: float | None

TransitMatters' benchmark travel time in seconds for the stop pair (the same on every trip), or None for bus, commuter rail, and ferry.

vehicle_label instance-attribute

vehicle_label: str

Vehicle label; may be empty.

vehicle_consist instance-attribute

vehicle_consist: tuple[str, ...]

Car numbers; empty when unknown.

Alert dataclass

Alert(
    *,
    valid_from: datetime,
    valid_to: datetime | None,
    text: str | None,
)

Bases: Model

An archived service alert.

valid_from instance-attribute

valid_from: datetime

Start time.

valid_to instance-attribute

valid_to: datetime | None

End time, or None for an open-ended alert.

text instance-attribute

text: str | None

Alert header text.

LiveAlert dataclass

LiveAlert(
    *,
    id: str,
    type: str,
    header: str,
    active_period: tuple[ActivePeriod, ...],
    stops: tuple[str, ...],
    routes: tuple[str, ...],
    description: str | None,
)

Bases: Model

A current MBTA service alert.

Which fields are set depends on type: routes for DELAY and DETOUR, and description for elevator and escalator closures.

id instance-attribute

id: str

MBTA alert ID.

type instance-attribute

type: str

Effect, e.g. DELAY, DETOUR, SHUTTLE, SUSPENSION, STOP_CLOSURE, ELEVATOR_CLOSURE, or ESCALATOR_CLOSURE.

header instance-attribute

header: str

Alert header text.

active_period instance-attribute

active_period: tuple[ActivePeriod, ...]

When the alert is active.

stops instance-attribute

stops: tuple[str, ...]

Affected stop IDs, unordered: platform IDs like "70061" for DELAY and DETOUR, station IDs like "place-dwnxg" otherwise.

routes instance-attribute

routes: tuple[str, ...]

Affected route IDs, possibly repeated; empty unless DELAY or DETOUR.

description instance-attribute

description: str | None

Long-form description, for elevator and escalator closures.

ActivePeriod dataclass

ActivePeriod(
    *,
    start: datetime | None,
    end: datetime | None,
    current: bool,
    upcoming: bool,
)

Bases: Model

A period during which a live alert is active.

start instance-attribute

start: datetime | None

Start time.

end instance-attribute

end: datetime | None

End time, or None if open-ended.

current instance-attribute

current: bool

Whether the period includes the current time.

upcoming instance-attribute

upcoming: bool

Whether the period hasn't started yet, or is open-ended.

SummaryStats dataclass

SummaryStats(
    *,
    count: int,
    mean: float,
    min: float,
    max: float,
    std: float,
    sum: float,
    p25: float,
    p50: float,
    p75: float,
)

Bases: Model

Summary statistics of a set of times, in seconds.

count instance-attribute

count: int

Number of events.

mean instance-attribute

mean: float

Mean.

min instance-attribute

min: float

Minimum.

max instance-attribute

max: float

Maximum.

std instance-attribute

std: float

Population standard deviation.

sum instance-attribute

sum: float

Sum.

p25 instance-attribute

p25: float

25th percentile.

p50 instance-attribute

p50: float

Median.

p75 instance-attribute

p75: float

75th percentile.

DailyStats dataclass

DailyStats(
    *,
    count: int,
    mean: float,
    min: float,
    max: float,
    std: float,
    sum: float,
    p25: float,
    p50: float,
    p75: float,
    service_date: date,
    peak: str,
    holiday: bool,
    weekend: bool,
)

Bases: SummaryStats

Statistics for one service date and peak period.

service_date instance-attribute

service_date: date

Service date. Service after midnight counts toward the day before.

peak instance-attribute

peak: str

"all" for the whole day. aggregate_travel_times_v2 also has "am_peak", "pm_peak", and "off_peak" entries.

holiday instance-attribute

holiday: bool

Whether the service date is a US federal holiday.

weekend instance-attribute

weekend: bool

Whether the service date is a Saturday or Sunday.

DailyHeadwayStats dataclass

DailyHeadwayStats(
    *,
    count: int,
    mean: float,
    min: float,
    max: float,
    std: float,
    sum: float,
    p25: float,
    p50: float,
    p75: float,
    service_date: date,
    peak: str,
    holiday: bool,
    weekend: bool,
    bunched: int,
    on_time: int,
)

Bases: DailyStats

Headway statistics for one service date, with bunching and on-time counts.

bunched instance-attribute

bunched: int

Headways at most half the scheduled headway (0 without a schedule).

on_time instance-attribute

on_time: int

Headways within 25% of the scheduled headway (0 without a schedule).

TimeOfDayStats dataclass

TimeOfDayStats(
    *,
    count: int,
    mean: float,
    min: float,
    max: float,
    std: float,
    sum: float,
    p25: float,
    p50: float,
    p75: float,
    dep_time: timedelta,
    is_peak_day: bool,
)

Bases: SummaryStats

Statistics for one 30-minute departure-time slot across a date range.

dep_time instance-attribute

dep_time: timedelta

Start of the slot, as time since the service day's midnight. Service after midnight is past 24 hours, so 00:30 is timedelta(hours=24, minutes=30).

is_peak_day instance-attribute

is_peak_day: bool

True for non-holiday weekdays, False for weekends and holidays.

TravelTimeStats dataclass

TravelTimeStats(
    *,
    by_date: tuple[DailyStats, ...],
    by_time: tuple[TimeOfDayStats, ...],
)

Bases: Model

Travel-time statistics by date and by time of day.

by_date instance-attribute

by_date: tuple[DailyStats, ...]

One entry per service date and peak period.

by_time instance-attribute

by_time: tuple[TimeOfDayStats, ...]

One entry per 30-minute departure-time slot.

TripMetrics dataclass

TripMetrics(
    *,
    date: date,
    line: str,
    count: float,
    total_time: float,
    miles_covered: float,
    avg_car_age: float | None,
    pct_new_trips: float | None,
    fleet_mix: dict[str, float],
)

Bases: Model

Delivered trips on a line for one day, week, or month.

date instance-attribute

date: date

Day, Monday of the week, or first day of the month.

line instance-attribute

line: str

Line ID, e.g. "line-red".

count instance-attribute

count: float

Trips delivered; the median daily count for weekly and monthly data.

total_time instance-attribute

total_time: float

Total trip time in seconds.

miles_covered instance-attribute

miles_covered: float

Total miles covered.

avg_car_age instance-attribute

avg_car_age: float | None

Average car age in years, if known.

pct_new_trips instance-attribute

pct_new_trips: float | None

Percentage of trips run with new cars, if known.

fleet_mix instance-attribute

fleet_mix: dict[str, float]

Percentage of trips by fleet type, e.g. {"red1": 25.5, "red4": 30.1}; empty when unknown.

BusTripMetrics dataclass

BusTripMetrics(
    *,
    date: date,
    route: str,
    count: float,
    total_time: float,
    miles_covered: float,
    n_traversals: float,
    median_speed_mph: float | None,
    mean_speed_mph: float | None,
    fleet_trips: float | None,
    avg_bus_age: float | None,
    pct_battery_trips: float | None,
    fleet_mix: dict[str, float],
)

Bases: Model

Delivered trips on a bus route for one day, week, or month.

Average speed in miles per hour is miles_covered / (total_time / 3600).

date instance-attribute

date: date

Day, Monday of the week, or first day of the month.

route instance-attribute

route: str

Route ID, e.g. "1", or the comma-separated routes requested together.

count instance-attribute

count: float

Trips delivered, summed over the week or month.

total_time instance-attribute

total_time: float

Total trip time in seconds.

miles_covered instance-attribute

miles_covered: float

Total miles covered.

n_traversals instance-attribute

n_traversals: float

Segment traversals measured.

median_speed_mph instance-attribute

median_speed_mph: float | None

Median speed in miles per hour, for daily entries covering the whole day.

mean_speed_mph instance-attribute

mean_speed_mph: float | None

Mean speed in miles per hour, for daily entries covering the whole day.

fleet_trips instance-attribute

fleet_trips: float | None

Trips with a known bus, if any.

avg_bus_age instance-attribute

avg_bus_age: float | None

Average bus age in years, if known.

pct_battery_trips instance-attribute

pct_battery_trips: float | None

Percentage of trips run with battery-electric buses, if known.

fleet_mix instance-attribute

fleet_mix: dict[str, float]

Percentage of trips by propulsion, e.g. {"hybrid": 81.3, "cng": 18.7}; empty when unknown.

BusRouteSpeed dataclass

BusRouteSpeed(
    *,
    route: str,
    count: float,
    total_time: float,
    miles_covered: float,
    n_traversals: float,
)

Bases: Model

A bus route's delivered trips over a date range.

Average speed in miles per hour is miles_covered / (total_time / 3600).

route instance-attribute

route: str

Route ID, e.g. "1".

count instance-attribute

count: float

Trips delivered.

total_time instance-attribute

total_time: float

Total trip time in seconds.

miles_covered instance-attribute

miles_covered: float

Total miles covered.

n_traversals instance-attribute

n_traversals: float

Segment traversals measured.

CommuterRailTripMetrics dataclass

CommuterRailTripMetrics(
    *,
    date: date,
    route: str,
    fleet_trips: float | None,
    avg_cab_car_age: float | None,
    fleet_mix: dict[str, float],
)

Bases: Model

The fleet that ran a commuter rail route for one day, week, or month.

date instance-attribute

date: date

Day, Monday of the week, or first day of the month.

route instance-attribute

route: str

Route ID, e.g. "CR-Fairmount", or "all".

fleet_trips instance-attribute

fleet_trips: float | None

Trips with a known cab car, if any.

avg_cab_car_age instance-attribute

avg_cab_car_age: float | None

Average cab car age in years, if known.

fleet_mix instance-attribute

fleet_mix: dict[str, float]

Percentage of trips by fleet type, e.g. {"rotem": 75.9, "kawasaki": 23.0}; empty when unknown.

LineDelays dataclass

LineDelays(
    *,
    date: date,
    line: str,
    total_delay_time: int,
    brake_problem: int,
    car_traffic: int,
    disabled_vehicle: int,
    door_problem: int,
    fire: int,
    flooding: int,
    mechanical_problem: int,
    medical_emergency: int,
    other: int,
    police_activity: int,
    power_problem: int,
    signal_problem: int,
    switch_problem: int,
    track_issue: int,
    track_work: int,
)

Bases: Model

Alert-reported delay on a line for one day or week, in minutes, by cause.

date instance-attribute

date: date

Day, or the Monday starting the week.

line instance-attribute

line: str

Line as requested, e.g. "Red", "Green-B", "CR-Fairmount".

ServiceHours dataclass

ServiceHours(
    *, date: date, scheduled: float, delivered: float
)

Bases: Model

Scheduled and delivered service hours for one day, week, or month.

date instance-attribute

date: date

Day, Monday of the week, or last day of the month.

scheduled instance-attribute

scheduled: float

Scheduled service hours.

delivered instance-attribute

delivered: float

Delivered service hours.

Ridership dataclass

Ridership(*, date: date, count: int)

Bases: Model

Ridership on a line for one week.

date instance-attribute

date: date

Week start date.

count instance-attribute

count: int

Ridership count.

ScheduledService dataclass

ScheduledService(
    *,
    start_date: date,
    end_date: date,
    start_date_service_levels: ServiceLevels,
    end_date_service_levels: ServiceLevels,
    counts: tuple[ScheduledServiceCount, ...],
)

Bases: Model

Scheduled trips on a route over a date range.

start_date instance-attribute

start_date: date

Requested start date.

end_date instance-attribute

end_date: date

Requested end date.

start_date_service_levels instance-attribute

start_date_service_levels: ServiceLevels

Service on the first weekday, Saturday, and Sunday in the range.

end_date_service_levels instance-attribute

end_date_service_levels: ServiceLevels

Service on the last weekday, Saturday, and Sunday in the range.

counts instance-attribute

counts: tuple[ScheduledServiceCount, ...]

Scheduled trips at the requested aggregation level.

ScheduledServiceCount dataclass

ScheduledServiceCount(*, date: date, count: float)

Bases: Model

Scheduled trips for one day, week, or month.

date instance-attribute

date: date

Day, Monday of the week, or last day of the month.

count instance-attribute

count: float

Scheduled trips; the median daily count for weekly and monthly data.

ServiceLevels dataclass

ServiceLevels(
    *,
    weekday: DayServiceLevels | None,
    saturday: DayServiceLevels | None,
    sunday: DayServiceLevels | None,
)

Bases: Model

Scheduled service on a weekday, Saturday, and Sunday.

weekday instance-attribute

weekday: DayServiceLevels | None

None when the date range has no weekday.

saturday instance-attribute

saturday: DayServiceLevels | None

None when the date range has no Saturday.

sunday instance-attribute

sunday: DayServiceLevels | None

None when the date range has no Sunday.

DayServiceLevels dataclass

DayServiceLevels(
    *, date: date, service_levels: tuple[int, ...]
)

Bases: Model

Scheduled trips by hour on one reference day.

date instance-attribute

date: date

Reference date.

service_levels instance-attribute

service_levels: tuple[int, ...]

Scheduled trips by hour, index 0 = midnight; empty if unavailable.

TimePredictionWeek dataclass

TimePredictionWeek(
    *,
    route_id: str,
    week: date,
    prediction: tuple[TimePredictionBucket, ...],
)

Bases: Model

Prediction accuracy for a route over one week.

route_id instance-attribute

route_id: str

Route ID.

week instance-attribute

week: date

Week start date.

prediction instance-attribute

prediction: tuple[TimePredictionBucket, ...]

Accuracy per prediction horizon.

TimePredictionBucket dataclass

TimePredictionBucket(
    *,
    weekly: date,
    mode: str,
    route_id: str,
    bin: str,
    arrival_departure: str,
    num_predictions: int,
    num_accurate_predictions: int,
)

Bases: Model

Prediction accuracy for one week and prediction horizon.

weekly instance-attribute

weekly: date

Week start date.

mode instance-attribute

mode: str

Mode, e.g. "subway" or "bus".

route_id instance-attribute

route_id: str

Route ID.

bin instance-attribute

bin: str

Prediction horizon: "0-3 min", "3-6 min", "6-12 min", or "12-30 min".

arrival_departure instance-attribute

arrival_departure: str

Prediction type, e.g. "blended".

num_predictions instance-attribute

num_predictions: int

Number of predictions.

num_accurate_predictions instance-attribute

num_accurate_predictions: int

Number of accurate predictions.

SpeedRestrictions dataclass

SpeedRestrictions(
    *,
    available: bool,
    date: date | None,
    zones: tuple[SpeedRestriction, ...],
)

Bases: Model

Speed restrictions on a line on one date.

available instance-attribute

available: bool

Whether there is speed restriction data for the date.

date instance-attribute

date: date | None

Date of the data, which may be earlier than the requested date.

zones instance-attribute

zones: tuple[SpeedRestriction, ...]

Restrictions in effect; empty when unavailable.

SpeedRestriction dataclass

SpeedRestriction(
    *,
    id: str,
    date: date,
    line_id: str,
    description: str,
    direction: str,
    reason: str,
    from_stop_id: str | None,
    to_stop_id: str | None,
    reported: date,
    speed_mph: int,
    track_feet: int,
)

Bases: Model

A speed restriction in effect on a line.

id instance-attribute

id: str

Restriction ID.

date instance-attribute

date: date

Date of the data.

line_id instance-attribute

line_id: str

Line ID, e.g. "line-Red".

description instance-attribute

description: str

Location description.

direction instance-attribute

direction: str

Track direction, e.g. "NB" or "SB".

reason instance-attribute

reason: str

Reason for the restriction.

from_stop_id instance-attribute

from_stop_id: str | None

Station ID where the restriction starts, e.g. "place-cntsq".

to_stop_id instance-attribute

to_stop_id: str | None

Station ID where it ends, or None for a single location.

reported instance-attribute

reported: date

Date the restriction was reported.

speed_mph instance-attribute

speed_mph: int

Speed limit in miles per hour.

track_feet instance-attribute

track_feet: int

Length of restricted track in feet.

Reliability dataclass

Reliability(
    *,
    date: date,
    days: int,
    completed: int | None,
    on_time: int | None,
    requests: int | None,
    no_shows: int | None,
    missed: int | None,
    otp_numerator: int | None,
    otp_denominator: int | None,
    cancelled: int | None,
    peak: ReliabilityCounts | None,
    off_peak: ReliabilityCounts | None,
)

Bases: Model

On-time performance of The RIDE or commuter rail for one day, week, or month.

The RIDE entries set completed through missed, and commuter rail entries set otp_numerator through off_peak. The others are None.

date instance-attribute

date: date

Day, Monday of the week, or first day of the month.

days instance-attribute

days: int

Service days with data in the period.

completed instance-attribute

completed: int | None

The RIDE trips completed.

on_time instance-attribute

on_time: int | None

The RIDE trips completed on time.

requests instance-attribute

requests: int | None

The RIDE trip requests, if recorded on every day of the period.

no_shows instance-attribute

no_shows: int | None

The RIDE rider no-shows, if recorded on every day of the period.

missed instance-attribute

missed: int | None

The RIDE missed trips, if recorded on every day of the period.

otp_numerator instance-attribute

otp_numerator: int | None

Commuter rail trips that ran on time.

otp_denominator instance-attribute

otp_denominator: int | None

Commuter rail trips measured for on-time performance.

cancelled instance-attribute

cancelled: int | None

Commuter rail cancelled trips.

peak instance-attribute

peak: ReliabilityCounts | None

Commuter rail counts for peak periods.

off_peak instance-attribute

off_peak: ReliabilityCounts | None

Commuter rail counts outside peak periods.

ReliabilityCounts dataclass

ReliabilityCounts(
    *,
    otp_numerator: int,
    otp_denominator: int,
    cancelled: int,
)

Bases: Model

On-time and cancelled commuter rail trips in one part of the day.

otp_numerator instance-attribute

otp_numerator: int

Trips that ran on time.

otp_denominator instance-attribute

otp_denominator: int

Trips measured for on-time performance.

cancelled instance-attribute

cancelled: int

Cancelled trips.

CommuterRailScorecard dataclass

CommuterRailScorecard(
    *,
    date: date | None,
    route_id: str | None,
    days: int,
    outbound: ScorecardDirection,
    inbound: ScorecardDirection,
    peak_trips: float | None,
    reverse_peak_trips: float | None,
)

Bases: Model

A commuter rail schedule measured against Regional Rail standards.

date instance-attribute

date: date | None

Day, Monday of the week, or first day of the month; None for "commuter-rail", which has one entry per route instead.

route_id instance-attribute

route_id: str | None

Route ID, for "commuter-rail"; otherwise None.

days instance-attribute

days: int

Days averaged.

outbound instance-attribute

Outbound service.

inbound instance-attribute

Inbound service.

peak_trips instance-attribute

peak_trips: float | None

Peak trains, both directions.

reverse_peak_trips instance-attribute

reverse_peak_trips: float | None

Reverse-peak trains, both directions.

ScorecardDirection dataclass

ScorecardDirection(
    *,
    trips: float | None,
    first_trip: timedelta | None,
    last_trip: timedelta | None,
    max_gap_midday: float | None,
    max_gap_evening: float | None,
    hours_at_target: float | None,
    clock_face_share: float | None,
    by_hour: tuple[float | None, ...],
)

Bases: Model

Scheduled commuter rail service in one direction, at the Boston terminal. Values are averages over the days measured.

trips instance-attribute

trips: float | None

Trains.

first_trip instance-attribute

first_trip: timedelta | None

First train, as time since midnight.

last_trip instance-attribute

last_trip: timedelta | None

Last train, as time since midnight. Trains after midnight are past 24 hours.

max_gap_midday instance-attribute

max_gap_midday: float | None

Longest midday wait, in minutes.

max_gap_evening instance-attribute

max_gap_evening: float | None

Longest evening wait, in minutes.

hours_at_target instance-attribute

hours_at_target: float | None

Hours from 5 AM to 1 AM with a train at least every 30 minutes.

clock_face_share instance-attribute

clock_face_share: float | None

Share of trains on a repeating hourly pattern, from 0 to 1.

by_hour instance-attribute

by_hour: tuple[float | None, ...]

Trains by hour, index 0 = midnight; empty if unavailable.

Weather dataclass

Weather(
    *,
    timestamp: datetime,
    temperature_f: float | None,
    weather_code: int | None,
    condition: str | None,
    precipitation_in: float | None,
    humidity_pct: int | None,
    wind_mph: float | None,
)

Bases: Model

One hour's weather in downtown Boston.

timestamp instance-attribute

timestamp: datetime

Start of the hour. On the night clocks fall back, the API has only one 1 AM entry, which is read as the first.

temperature_f instance-attribute

temperature_f: float | None

Air temperature in °F.

weather_code instance-attribute

weather_code: int | None

WMO weather code, from Open-Meteo.

condition instance-attribute

condition: str | None

"clear", "cloudy", "fog", "rain", "snow", "storm", or "unknown".

precipitation_in instance-attribute

precipitation_in: float | None

Precipitation in inches.

humidity_pct instance-attribute

humidity_pct: int | None

Relative humidity, from 0 to 100.

wind_mph instance-attribute

wind_mph: float | None

Wind speed in miles per hour.

Routes dataclass

Routes(
    *,
    rapid_transit: tuple[str, ...],
    bus: tuple[str, ...],
    commuter_rail: tuple[str, ...],
    ferry: tuple[str, ...],
)

Bases: Model

Every route ID the dashboard supports, by mode.

rapid_transit instance-attribute

rapid_transit: tuple[str, ...]

E.g. "Red", "Green".

bus instance-attribute

bus: tuple[str, ...]

E.g. "1", "104/109".

commuter_rail instance-attribute

commuter_rail: tuple[str, ...]

E.g. "CR-Fairmount".

ferry instance-attribute

ferry: tuple[str, ...]

E.g. "Boat-F1".

RouteStops dataclass

RouteStops(
    *,
    type: str,
    directions: dict[int, str],
    stations: tuple[Station, ...],
    service_start: date | None,
    service_end: date | None,
)

Bases: Model

The stations along a route, with stop IDs by direction.

Find a station with station, or the stop IDs for a trip with trip.

type instance-attribute

type: str

"rapidtransit", "bus", "commuter-rail", or "ferry".

directions instance-attribute

directions: dict[int, str]

Direction names by direction ID, e.g. {0: "northbound", 1: "southbound"}.

stations instance-attribute

stations: tuple[Station, ...]

Stations in route order.

service_start instance-attribute

service_start: date | None

When the route started running, for routes that changed.

service_end instance-attribute

service_end: date | None

When the route stopped running, for routes that changed.

station

station(name: str) -> Station

The station named name, e.g. "Davis", or with that station ID, e.g. "place-davis". Case-insensitive.

Raises:

Type Description
KeyError

No station matches; the message suggests close names.

Source code in src/transitmatters/models.py
def station(self, name: str) -> Station:
    """The station named `name`, e.g. `"Davis"`, or with that station ID,
    e.g. `"place-davis"`. Case-insensitive.

    Raises:
        KeyError: No station matches; the message suggests close names.
    """
    wanted = name.casefold()
    for station in self.stations:
        if wanted in (station.stop_name.casefold(), station.station.casefold()):
            return station
    names = [station.stop_name for station in self.stations]
    close = [n for n in names if wanted in n.casefold()]
    close += difflib.get_close_matches(name, names, n=3, cutoff=0.5)
    close = list(dict.fromkeys(close))[:3]
    hint = f"; did you mean {' or '.join(map(repr, close))}?" if close else ""
    raise KeyError(f"no station {name!r} on this route{hint}")

trip

trip(
    origin: str,
    destination: str,
    *,
    direction: int | None = None,
) -> StopPair

The platforms for travel from origin to destination.

Stations are looked up as in station. The direction is worked out from the stations' order along the route, unless given.

Raises:

Type Description
KeyError

A station isn't on this route.

ValueError

The stations are the same, on different branches, or have no platforms in direction.

Source code in src/transitmatters/models.py
def trip(
    self, origin: str, destination: str, *, direction: int | None = None
) -> StopPair:
    """The platforms for travel from `origin` to `destination`.

    Stations are looked up as in `station`. The direction is worked out
    from the stations' order along the route, unless given.

    Raises:
        KeyError: A station isn't on this route.
        ValueError: The stations are the same, on different branches, or
            have no platforms in `direction`.
    """
    start, end = self.station(origin), self.station(destination)
    if start.station == end.station:
        raise ValueError(f"{start.stop_name} is both the origin and destination")
    if (
        start.branches
        and end.branches
        and not set(start.branches) & set(end.branches)
    ):
        raise ValueError(
            f"{start.stop_name} and {end.stop_name} are on different branches"
        )
    if direction is None:
        # Stations are numbered in the direction 1 travels, on every mode.
        direction = 1 if end.order > start.order else 0
    from_stop, to_stop = start.stops.get(direction), end.stops.get(direction)
    if not from_stop or not to_stop:
        raise ValueError(
            f"no platforms in direction {direction} between "
            f"{start.stop_name} and {end.stop_name}"
        )
    return StopPair(from_stop=from_stop, to_stop=to_stop, direction=direction)

Station dataclass

Station(
    *,
    stop_name: str,
    station: str,
    order: float,
    stops: dict[int, tuple[str, ...]],
    branches: tuple[str, ...],
    accessible: bool,
    pedal_park: bool,
    enclosed_bike_parking: bool,
    terminus: bool,
    disabled: bool,
    short: str | None,
)

Bases: Model

A station or stop along a route.

stop_name instance-attribute

stop_name: str

Display name, e.g. "Davis".

station instance-attribute

station: str

Station ID, e.g. "place-davis".

order instance-attribute

order: float

Position along the route, starting at 1. Usually a whole number.

stops instance-attribute

stops: dict[int, tuple[str, ...]]

Platform stop IDs by direction ID.

branches instance-attribute

branches: tuple[str, ...]

Branches serving the station, e.g. ("A", "B"); empty if the route doesn't branch.

accessible instance-attribute

accessible: bool

Whether the station is ADA accessible.

pedal_park instance-attribute

pedal_park: bool

Whether the station has bike parking.

enclosed_bike_parking instance-attribute

enclosed_bike_parking: bool

Whether the station has enclosed bike storage.

terminus instance-attribute

terminus: bool

Whether this is a terminal station.

disabled instance-attribute

disabled: bool

Whether this stop is currently disabled.

short instance-attribute

short: str | None

Short display name, if any.

StopPair dataclass

StopPair(
    *,
    from_stop: tuple[str, ...],
    to_stop: tuple[str, ...],
    direction: int,
)

Bases: Model

The platforms for a trip between two stations, from RouteStops.trip.

Pass them to transitmatters.TransitMatters.travel_times or transitmatters.TransitMatters.aggregate_travel_times:

pair = tm.stops(Line.RED).trip("Davis", "Porter")
tm.travel_times("2025-03-04", from_stop=pair.from_stop, to_stop=pair.to_stop)

from_stop instance-attribute

from_stop: tuple[str, ...]

Stop IDs of the origin's platforms in direction.

to_stop instance-attribute

to_stop: tuple[str, ...]

Stop IDs of the destination's platforms in direction.

direction instance-attribute

direction: int

Direction ID of the trip.

Facility dataclass

Facility(
    *,
    id: str,
    type: str,
    long_name: str | None,
    short_name: str | None,
    latitude: float | None,
    longitude: float | None,
    stop_id: str | None,
    properties: tuple[FacilityProperty, ...],
)

Bases: Model

An MBTA facility, such as an elevator, escalator, or bike rack.

id instance-attribute

id: str

Facility ID.

type instance-attribute

type: str

E.g. "ELEVATOR", "ESCALATOR", "BIKE_STORAGE", "PARKING_AREA".

long_name instance-attribute

long_name: str | None

Full display name.

short_name instance-attribute

short_name: str | None

Short display name.

stop_id instance-attribute

stop_id: str | None

Station the facility belongs to, e.g. "place-andrw".

properties instance-attribute

properties: tuple[FacilityProperty, ...]

Other properties. A name can appear more than once.

FacilityProperty dataclass

FacilityProperty(*, name: str, value: str | None)

Bases: Model

A name/value property of a facility.

name instance-attribute

name: str

Property name, e.g. "capacity" or "excludes-stop".

value instance-attribute

value: str | None

Property value. Numbers are strings, e.g. "20".

Healthcheck dataclass

Healthcheck(*, status: str, failed_checks: dict[str, str])

Bases: Model

The result of the API's health checks.

status instance-attribute

status: str

"pass" or "fail".

failed_checks instance-attribute

failed_checks: dict[str, str]

Failure detail by check name; empty when all pass.

ok property

ok: bool

Whether every check passed.

ServiceRidershipDashboard dataclass

ServiceRidershipDashboard(
    *,
    summary_data: DashboardSummary,
    mode_data: dict[str, DashboardSummary],
    line_data: dict[str, DashboardLine],
)

Bases: Model

The data behind the dashboard's service and ridership overview.

summary_data instance-attribute

summary_data: DashboardSummary

System-wide summary.

mode_data instance-attribute

mode_data: dict[str, DashboardSummary]

Summaries by mode: "rapid-transit", "regional-rail", "bus", "boat".

line_data instance-attribute

line_data: dict[str, DashboardLine]

Lines by line ID, e.g. "line-Red".

DashboardSummary dataclass

DashboardSummary(
    *,
    total_ridership_history: dict[date, float],
    total_service_history: dict[date, float],
    total_ridership_percentage: float,
    total_service_percentage: float,
    total_passengers: float,
    total_trips: float,
    total_routes_cancelled: int,
    total_reduced_service: int,
    total_increased_service: int,
    start_date: date,
    end_date: date,
)

Bases: Model

Service and ridership across the system or one mode.

total_ridership_history instance-attribute

total_ridership_history: dict[date, float]

Weekly median ridership by week start date.

total_service_history instance-attribute

total_service_history: dict[date, float]

Weekly median scheduled trips by week start date.

total_ridership_percentage instance-attribute

total_ridership_percentage: float

Currently always 0.

total_service_percentage instance-attribute

total_service_percentage: float

Currently always 0.

total_passengers instance-attribute

total_passengers: float

Weekly median ridership in the latest week.

total_trips instance-attribute

total_trips: float

Weekly median scheduled trips in the latest week.

total_routes_cancelled instance-attribute

total_routes_cancelled: int

Routes with cancelled service.

total_reduced_service instance-attribute

total_reduced_service: int

Routes with reduced service.

total_increased_service instance-attribute

total_increased_service: int

Routes with increased service.

start_date instance-attribute

start_date: date

First date covered.

end_date instance-attribute

end_date: date

Last date covered.

DashboardLine dataclass

DashboardLine(
    *,
    id: str,
    short_name: str,
    long_name: str,
    route_ids: tuple[str, ...],
    start_date: date,
    line_kind: str,
    ridership_history: dict[date, float],
    service_history: dict[date, float],
    service_regimes: ServiceRegimes,
)

Bases: Model

Service and ridership for one line.

id instance-attribute

id: str

Line ID, e.g. "line-Red", "line-1", "line-Fairmount".

short_name instance-attribute

short_name: str

Short name; may be empty.

long_name instance-attribute

long_name: str

Long name, e.g. "Red Line".

route_ids instance-attribute

route_ids: tuple[str, ...]

Route IDs on the line.

start_date instance-attribute

start_date: date

First date covered.

line_kind instance-attribute

line_kind: str

"red", "orange", "blue", "green", "silver", "regional-rail", "bus", or "boat".

ridership_history instance-attribute

ridership_history: dict[date, float]

Weekly median ridership by week start date; empty if unavailable.

service_history instance-attribute

service_history: dict[date, float]

Weekly median scheduled trips by week start date.

service_regimes instance-attribute

service_regimes: ServiceRegimes

Scheduled service now, a year ago, and before COVID.

ServiceRegimes dataclass

ServiceRegimes(
    *,
    current: ServiceRegime,
    one_year_ago: ServiceRegime,
    baseline: ServiceRegime,
)

Bases: Model

A line's scheduled service at three points in time.

current instance-attribute

current: ServiceRegime

Current service.

one_year_ago instance-attribute

one_year_ago: ServiceRegime

Service one year ago.

baseline instance-attribute

baseline: ServiceRegime

Pre-COVID baseline service.

ServiceRegime dataclass

ServiceRegime(
    *,
    weekday: ServiceDay,
    saturday: ServiceDay,
    sunday: ServiceDay,
)

Bases: Model

Scheduled service on a weekday, Saturday, and Sunday.

ServiceDay dataclass

ServiceDay(
    *,
    cancelled: bool,
    total_trips: int,
    trips_per_hour: tuple[float, ...],
)

Bases: Model

Scheduled service on one kind of day.

cancelled instance-attribute

cancelled: bool

Whether service is cancelled.

total_trips instance-attribute

total_trips: int

Total scheduled trips.

trips_per_hour instance-attribute

trips_per_hour: tuple[float, ...]

Scheduled trips by hour, index 0 = midnight; empty when cancelled.