Spaces:
Sleeping

dn commited on
Commit
a3c58b7
·
1 Parent(s): d276573

split parent_stations_from_gtfs from assign_tier_to_stops_from_gtfs. add tests

Browse files
notebooks/sb79map.py CHANGED
@@ -12,7 +12,7 @@
12
 
13
  import marimo
14
 
15
- from shared.pipelines.sb79 import assign_tier_to_stops_from_gtfs
16
 
17
  __generated_with = "0.23.5"
18
  app = marimo.App()
@@ -93,98 +93,6 @@ with app.setup(hide_code=True):
93
  parcels = parcels.groupby("PARCEL_APN", as_index=False).first()
94
  return parcels.set_crs("EPSG:4326").to_crs(f"EPSG:{wkid}")
95
 
96
- def compute_scag_density(scag_parcels: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
97
- """Add ``current_density_du_per_ac`` to SCAG parcels using LA / non-LA logic.
98
-
99
- For LA parcels, first tries ``ZN19_CITY`` zone codes. If no match is found,
100
- falls through to try ``ZN19_SCAG`` codes. Parcels that don't match any code
101
- get ``NaN`` (excluded from downstream calculations).
102
-
103
- Parameters
104
- ----------
105
- scag_parcels:
106
- Must have columns ``ZN19_CITY``, ``ZN19_SCAG``, ``CITY``, and a valid
107
- geometry for area calculations.
108
-
109
- Returns
110
- -------
111
- gpd.GeoDataFrame
112
- Same as input with an added ``current_density_du_per_ac`` column.
113
- """
114
- df = scag_parcels.copy()
115
-
116
- # --- LA density: map ZN19_CITY zone codes → du/ac ---
117
- la_density = df["ZN19_CITY"].case_when(
118
- [
119
- (df["ZN19_CITY"].str.contains("RD1.5", na=False), 43560 / 1500),
120
- (df["ZN19_CITY"].str.contains("RD2", na=False), 43560 / 2000),
121
- (df["ZN19_CITY"].str.contains("RD3", na=False), 43560 / 3000),
122
- (df["ZN19_CITY"].str.contains("RD4", na=False), 43560 / 4000),
123
- (df["ZN19_CITY"].str.contains("RD5", na=False), 43560 / 5000),
124
- (df["ZN19_CITY"].str.contains("RD6", na=False), 43560 / 6000),
125
- (df["ZN19_CITY"].str.contains("RMP", na=False), 43560 / 20000),
126
- (df["ZN19_CITY"].str.contains("R3", na=False), 43560 / 800),
127
- (df["ZN19_CITY"].str.contains("RAS3", na=False), 43560 / 800),
128
- (df["ZN19_CITY"].str.contains("R4", na=False), 43560 / 400),
129
- (df["ZN19_CITY"].str.contains("RAS4", na=False), 43560 / 400),
130
- (df["ZN19_CITY"].str.contains("R5", na=False), 43560 / 200),
131
- (df["ZN19_CITY"].str.contains("RE40", na=False), 43560 / 40000),
132
- (df["ZN19_CITY"].str.contains("RE20", na=False), 43560 / 20000),
133
- (df["ZN19_CITY"].str.contains("RE15", na=False), 43560 / 15000),
134
- (df["ZN19_CITY"].str.contains("RE11", na=False), 43560 / 11000),
135
- (df["ZN19_CITY"].str.contains("RE9", na=False), 43560 / 9000),
136
- (df["ZN19_CITY"].str.contains("RS", na=False), 43560 / 7500),
137
- (df["ZN19_CITY"].str.contains("R1", na=False), 43560 / 5000),
138
- (df["ZN19_CITY"].str.contains("RU", na=False), 43560 / 3500),
139
- (df["ZN19_CITY"].str.contains("RZ2.5", na=False), 43560 / 2500),
140
- (df["ZN19_CITY"].str.contains("RZ3", na=False), 43560 / 3000),
141
- (df["ZN19_CITY"].str.contains("RZ4", na=False), 43560 / 4000),
142
- (df["ZN19_CITY"].str.contains("RW1", na=False), 43560 / 2300),
143
- (df["ZN19_CITY"].str.contains("R2", na=False), 43560 / 2500),
144
- (df["ZN19_CITY"].str.contains("RW2", na=False), 43560 / 1150),
145
- (df["ZN19_CITY"].str.contains("C1", na=False), 100),
146
- (df["ZN19_CITY"].str.contains("C2", na=False), 43560 / 400),
147
- (df["ZN19_CITY"].str.contains("C3", na=False), 110),
148
- (df["ZN19_CITY"].str.contains("C4", na=False), 200),
149
- ]
150
- )
151
-
152
- # --- Non-LA / fallback density: map ZN19_SCAG codes → du/ac ---
153
- zn19_scag = df["ZN19_SCAG"].astype(str)
154
- area_acres = df.to_crs("EPSG:2229").area / 43560
155
- scag_density = zn19_scag.case_when(
156
- [
157
- (zn19_scag == "1110", 1 / area_acres.replace(0, np.nan)),
158
- (zn19_scag == "1111", 1 / area_acres.replace(0, np.nan)),
159
- (zn19_scag == "1112", 1 / area_acres.replace(0, np.nan)),
160
- (zn19_scag == "1113", 1 / area_acres.replace(0, np.nan)),
161
- (zn19_scag == "1121", 3 / area_acres.replace(0, np.nan)),
162
- (zn19_scag == "1122", 3 / area_acres.replace(0, np.nan)),
163
- (zn19_scag == "1140", 3 / area_acres.replace(0, np.nan)),
164
- (zn19_scag == "1123", 18),
165
- (zn19_scag == "1124", 60),
166
- (zn19_scag == "1125", 80),
167
- (zn19_scag == "1131", 6),
168
- (zn19_scag == "1150", 1),
169
- (zn19_scag == "1150", 1),
170
- (zn19_scag == "1600", 40),
171
- (zn19_scag == "1610", 40),
172
- (zn19_scag == "1620", 30),
173
- (zn19_scag.isin(["1220", "1221", "1222"]), 47),
174
- (zn19_scag.isin(["2000", "2100", "2200", "2300", "2400", "2500", "2600", "2700"]), 1 / 5),
175
- (zn19_scag.isin(["1900", "7777", "1500", "1233", "1210", "1211", "1212", "1213", "1247"]), 0),
176
- (zn19_scag == zn19_scag, np.nan),
177
- ]
178
- )
179
-
180
- # For LA parcels: use ZN19_CITY density if matched, otherwise fall through to SCAG
181
- is_la = df["CITY"] == "Los Angeles"
182
-
183
- df["current_density_du_per_ac"] = scag_density
184
- df.loc[is_la, "current_density_du_per_ac"] = la_density
185
- df["current_density_du_per_ac"] = pd.to_numeric(df["current_density_du_per_ac"], errors="coerce")
186
- return df
187
-
188
  def trim_around_stations(
189
  parcels_gdf: gpd.GeoDataFrame,
190
  stops_gdf: gpd.GeoDataFrame,
 
12
 
13
  import marimo
14
 
15
+ from shared.pipelines.sb79 import assign_tier_to_stops_from_gtfs, compute_scag_density
16
 
17
  __generated_with = "0.23.5"
18
  app = marimo.App()
 
93
  parcels = parcels.groupby("PARCEL_APN", as_index=False).first()
94
  return parcels.set_crs("EPSG:4326").to_crs(f"EPSG:{wkid}")
95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
  def trim_around_stations(
97
  parcels_gdf: gpd.GeoDataFrame,
98
  stops_gdf: gpd.GeoDataFrame,
shared/api/gtfs.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gtfs_kit
2
+ import pandas as pd
3
+
4
+
5
+ def parent_stations_from_gtfs(feed: gtfs_kit.Feed) -> pd.DataFrame:
6
+ """Return a DataFrame of parent stations with aggregated route info and trip counts."""
7
+ trip_counts = feed.compute_stop_stats([feed.get_first_week()[0]])[["stop_id", "num_trips"]].assign(
8
+ num_trips=lambda df: df["num_trips"].astype(int)
9
+ )
10
+
11
+ stop_info = (
12
+ feed.stop_times.merge(feed.trips[["trip_id", "route_id"]], on="trip_id")
13
+ .merge(feed.routes[["route_id", "route_type", "agency_id"]], on="route_id")
14
+ .groupby("stop_id")
15
+ .agg(
16
+ route_ids=("route_id", lambda x: set(x)),
17
+ route_types=("route_type", lambda x: set(str(t) for t in x)),
18
+ agencies=("agency_id", lambda x: set(x)),
19
+ )
20
+ .reset_index()
21
+ )
22
+
23
+ stops_df = feed.stops
24
+ parent_stations = stops_df[stops_df["location_type"] == 1].copy()
25
+ boarding_stops = stops_df[stops_df["location_type"] == 0].copy()
26
+
27
+ if parent_stations.empty:
28
+ parent_stations = boarding_stops.copy()
29
+ boarding_stops = pd.DataFrame()
30
+
31
+ self_rows = parent_stations[["stop_id"]].assign(parent_id=parent_stations["stop_id"])
32
+ child_rows = (
33
+ boarding_stops.dropna(subset=["parent_station"])[["stop_id", "parent_station"]].rename(
34
+ columns={"parent_station": "parent_id"}
35
+ )
36
+ if not boarding_stops.empty
37
+ else pd.DataFrame(columns=["stop_id", "parent_id"])
38
+ )
39
+ membership = pd.concat([self_rows, child_rows], ignore_index=True)
40
+
41
+ parent_route_info = (
42
+ membership.merge(stop_info, on="stop_id", how="left")
43
+ .merge(trip_counts, on="stop_id", how="left")
44
+ .dropna(subset=["route_ids"])
45
+ .groupby("parent_id")
46
+ .agg(
47
+ route_ids=("route_ids", lambda x: set().union(*x)),
48
+ route_types=("route_types", lambda x: set().union(*x)),
49
+ agencies=("agencies", lambda x: set().union(*x)),
50
+ n_arrivals=("num_trips", "sum"),
51
+ )
52
+ .reset_index()
53
+ .rename(columns={"parent_id": "stop_id"})
54
+ )
55
+
56
+ return parent_stations.merge(parent_route_info, on="stop_id", how="inner")
shared/pipelines/sb79.py CHANGED
@@ -3,176 +3,57 @@ from typing import Any
3
 
4
  import geopandas as gpd
5
  import gtfs_kit
 
6
  import pandas as pd
7
 
 
 
8
 
9
  def assign_tier_to_stops_from_gtfs(
10
  gtfs_path: str | Path,
11
  tier_overrides: dict[str, int] | None = None,
12
  ) -> gpd.GeoDataFrame:
13
- """Parse a GTFS zip and return a GeoDataFrame of Tier-1/Tier-2 parent stations.
14
-
15
- Uses ``gtfs_kit`` to read the feed and compute stop-level statistics.
16
-
17
- Parameters
18
- ----------
19
- gtfs_path:
20
- Path to a ``.zip`` file containing standard GTFS tables.
21
- tier_overrides:
22
- Optional mapping ``{route_id: tier}`` to force a specific tier for
23
- a route regardless of the automatic logic.
24
-
25
- Returns
26
- -------
27
- gpd.GeoDataFrame
28
- Only stops that qualify as Tier 1 or Tier 2 are returned.
29
- """
30
  feed = gtfs_kit.read_feed(gtfs_path, dist_units="km")
31
 
32
- # --- Pick a representative weekday ---
33
- first_week = feed.get_first_week()
34
- if not first_week:
35
  return _empty_result()
36
- weekday = first_week[0] # Monday
37
-
38
- # --- Stop-level trip counts on that weekday ---
39
- stop_stats = feed.compute_stop_stats([weekday])
40
- # stop_stats columns: date, stop_id, num_trips, num_routes, ...
41
- trip_counts: dict[str, int] = {}
42
- for _, row in stop_stats.iterrows():
43
- trip_counts[row["stop_id"]] = int(row["num_trips"])
44
-
45
- # --- Build a mapping from stop_id → set of (route_id, route_type, agency_id) ---
46
- # Merge stop_times → trips → routes
47
- st = feed.stop_times
48
- trips = feed.trips[["trip_id", "route_id"]]
49
- routes = feed.routes[["route_id", "route_type", "agency_id"]]
50
-
51
- stop_route_info = (
52
- st.merge(trips, on="trip_id")
53
- .merge(routes, on="route_id")
54
- .groupby("stop_id")
55
- .agg(
56
- route_ids=("route_id", lambda x: ",".join(sorted(set(x)))),
57
- route_types=("route_type", lambda x: ",".join(sorted(set(str(t) for t in x)))),
58
- agencies=("agency_id", lambda x: ",".join(sorted(set(x)))),
59
- )
60
- .reset_index()
61
- )
62
 
63
- # --- Identify parent stations and child stops ---
64
- stops_df = feed.stops
65
- parent_stations = stops_df[stops_df["location_type"] == 1].copy()
66
- boarding_stops = stops_df[stops_df["location_type"] == 0].copy()
67
-
68
- # If there are no parent stations (location_type=1), treat all boarding
69
- # stops (location_type=0) as individual stations.
70
- if parent_stations.empty:
71
- parent_stations = boarding_stops.copy()
72
- boarding_stops = pd.DataFrame() # no routes to propagate
73
-
74
- # --- Propagate routes from child stops up to parent stations ---
75
- # Build a lookup: stop_id → route info
76
- stop_info_lookup: dict[str, dict[str, Any]] = {}
77
- for _, row in stop_route_info.iterrows():
78
- stop_info_lookup[row["stop_id"]] = {
79
- "route_ids": row["route_ids"],
80
- "route_types": row["route_types"],
81
- "agencies": row["agencies"],
82
- }
83
-
84
- # For each parent station, collect routes from itself and its children
85
- parent_route_info: dict[str, dict[str, set[str]]] = {}
86
- for _, ps in parent_stations.iterrows():
87
- pid = ps["stop_id"]
88
- parent_route_info[pid] = {"route_ids": set(), "route_types": set(), "agencies": set()}
89
-
90
- # Routes directly serving the parent station
91
- if pid in stop_info_lookup:
92
- info = stop_info_lookup[pid]
93
- parent_route_info[pid]["route_ids"].update(info["route_ids"].split(","))
94
- parent_route_info[pid]["route_types"].update(info["route_types"].split(","))
95
- parent_route_info[pid]["agencies"].update(info["agencies"].split(","))
96
-
97
- # Routes from child stops
98
- if not boarding_stops.empty:
99
- child_stops = boarding_stops[boarding_stops["parent_station"] == pid]
100
- for _, cs in child_stops.iterrows():
101
- cid = cs["stop_id"]
102
- if cid in stop_info_lookup:
103
- info = stop_info_lookup[cid]
104
- parent_route_info[pid]["route_ids"].update(info["route_ids"].split(","))
105
- parent_route_info[pid]["route_types"].update(info["route_types"].split(","))
106
- parent_route_info[pid]["agencies"].update(info["agencies"].split(","))
107
-
108
- # --- Build the output GeoDataFrame ---
109
- records: list[dict[str, Any]] = []
110
- for _, ps in parent_stations.iterrows():
111
- pid = ps["stop_id"]
112
- info = parent_route_info.get(pid)
113
- if not info or not info["route_ids"]:
114
- continue
115
-
116
- served_routes = sorted(info["route_ids"])
117
- types = info["route_types"]
118
- agencies = sorted(info["agencies"])
119
- routetypes_str = ",".join(sorted(types, key=int))
120
-
121
- # Total arrivals for this stop on the representative weekday
122
- total_arrivals = trip_counts.get(pid, 0)
123
-
124
- # Tier assignment
125
- has_type_1 = "1" in types
126
- has_type_0 = "0" in types
127
- has_type_2 = "2" in types
128
-
129
- tier: int | None = None
130
- if has_type_1:
131
- tier = 1
132
- elif (has_type_0 or has_type_2) and total_arrivals >= 72:
133
- tier = 1
134
- elif has_type_2 and 48 <= total_arrivals < 72:
135
- tier = 2
136
- elif has_type_0 and total_arrivals < 72:
137
- tier = 2
138
-
139
- # Apply overrides
140
- if tier_overrides:
141
- for rid in served_routes:
142
- if rid in tier_overrides:
143
- tier = tier_overrides[rid]
144
- break
145
-
146
- if tier is None:
147
- continue # skip stops that don't qualify
148
-
149
- records.append(
150
- {
151
- "stop_id": pid,
152
- "stop_name": ps.get("stop_name", ""),
153
- "stop_lat": float(ps["stop_lat"]),
154
- "stop_lon": float(ps["stop_lon"]),
155
- "Tier": tier,
156
- "agency": ",".join(agencies),
157
- "route_ids_served": ",".join(served_routes),
158
- "routetypes": routetypes_str,
159
- "n_arrivals": total_arrivals,
160
- }
161
  )
 
 
 
 
 
 
 
 
162
 
163
- if not records:
164
  return _empty_result()
165
 
166
- result = gpd.GeoDataFrame(
167
- records,
168
- geometry=gpd.points_from_xy(
169
- [r["stop_lon"] for r in records],
170
- [r["stop_lat"] for r in records],
171
- crs="EPSG:4326",
172
- ),
173
- )
174
- result.drop(columns=["stop_lat", "stop_lon"], inplace=True)
175
- return result
176
 
177
 
178
  def _empty_result() -> gpd.GeoDataFrame:
@@ -190,3 +71,96 @@ def _empty_result() -> gpd.GeoDataFrame:
190
  geometry=pd.Series(dtype=object),
191
  crs="EPSG:4326",
192
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
4
  import geopandas as gpd
5
  import gtfs_kit
6
+ import numpy as np
7
  import pandas as pd
8
 
9
+ from shared.api.gtfs import parent_stations_from_gtfs
10
+
11
 
12
  def assign_tier_to_stops_from_gtfs(
13
  gtfs_path: str | Path,
14
  tier_overrides: dict[str, int] | None = None,
15
  ) -> gpd.GeoDataFrame:
16
+ """Parse a GTFS zip and return a GeoDataFrame of Tier-1/Tier-2 parent stations."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  feed = gtfs_kit.read_feed(gtfs_path, dist_units="km")
18
 
19
+ if not feed.get_first_week():
 
 
20
  return _empty_result()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
+ result_df = (
23
+ parent_stations_from_gtfs(feed)
24
+ .assign(
25
+ n_arrivals=lambda df: df["n_arrivals"].fillna(0).astype(int),
26
+ served_routes=lambda df: df["route_ids"].map(sorted),
27
+ Tier=lambda df: pd.Series(pd.NA, index=df.index).case_when(
28
+ [
29
+ (df["route_types"].map(lambda t: "1" in t), 1),
30
+ (df["route_types"].map(lambda t: "0" in t or "2" in t) & (df["n_arrivals"] >= 72), 1),
31
+ (df["route_types"].map(lambda t: "2" in t) & df["n_arrivals"].between(48, 71), 2),
32
+ (df["route_types"].map(lambda t: "0" in t) & (df["n_arrivals"] < 72), 2),
33
+ ]
34
+ ),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  )
36
+ .dropna(subset=["Tier"])
37
+ .assign(
38
+ Tier=lambda df: df["Tier"].astype(int),
39
+ agency=lambda df: df["agencies"].map(lambda s: ",".join(sorted(s))),
40
+ route_ids_served=lambda df: df["served_routes"].map(",".join),
41
+ routetypes=lambda df: df["route_types"].map(lambda s: ",".join(sorted(s, key=int))),
42
+ )[["stop_id", "stop_name", "stop_lat", "stop_lon", "Tier", "agency", "route_ids_served", "routetypes", "n_arrivals"]]
43
+ )
44
 
45
+ if result_df.empty:
46
  return _empty_result()
47
 
48
+ if tier_overrides:
49
+ for rid, tier in tier_overrides.items():
50
+ mask = result_df["route_ids_served"].str.contains(rid, regex=False)
51
+ result_df.loc[mask, "Tier"] = tier
52
+
53
+ return gpd.GeoDataFrame(
54
+ result_df,
55
+ geometry=gpd.points_from_xy(result_df["stop_lon"], result_df["stop_lat"], crs="EPSG:4326"),
56
+ ).drop(columns=["stop_lat", "stop_lon"])
 
57
 
58
 
59
  def _empty_result() -> gpd.GeoDataFrame:
 
71
  geometry=pd.Series(dtype=object),
72
  crs="EPSG:4326",
73
  )
74
+
75
+
76
+ def compute_scag_density(scag_parcels: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
77
+ """Add ``current_density_du_per_ac`` to SCAG parcels using LA / non-LA logic.
78
+
79
+ For LA parcels, first tries ``ZN19_CITY`` zone codes. If no match is found,
80
+ falls through to try ``ZN19_SCAG`` codes. Parcels that don't match any code
81
+ get ``NaN`` (excluded from downstream calculations).
82
+
83
+ Parameters
84
+ ----------
85
+ scag_parcels:
86
+ Must have columns ``ZN19_CITY``, ``ZN19_SCAG``, ``CITY``, and a valid
87
+ geometry for area calculations.
88
+
89
+ Returns
90
+ -------
91
+ gpd.GeoDataFrame
92
+ Same as input with an added ``current_density_du_per_ac`` column.
93
+ """
94
+ df = scag_parcels.copy()
95
+
96
+ # --- LA density: map ZN19_CITY zone codes → du/ac ---
97
+ la_density = df["ZN19_CITY"].case_when(
98
+ [
99
+ (df["ZN19_CITY"].str.contains("RD1.5", na=False), 43560 / 1500),
100
+ (df["ZN19_CITY"].str.contains("RD2", na=False), 43560 / 2000),
101
+ (df["ZN19_CITY"].str.contains("RD3", na=False), 43560 / 3000),
102
+ (df["ZN19_CITY"].str.contains("RD4", na=False), 43560 / 4000),
103
+ (df["ZN19_CITY"].str.contains("RD5", na=False), 43560 / 5000),
104
+ (df["ZN19_CITY"].str.contains("RD6", na=False), 43560 / 6000),
105
+ (df["ZN19_CITY"].str.contains("RMP", na=False), 43560 / 20000),
106
+ (df["ZN19_CITY"].str.contains("R3", na=False), 43560 / 800),
107
+ (df["ZN19_CITY"].str.contains("RAS3", na=False), 43560 / 800),
108
+ (df["ZN19_CITY"].str.contains("R4", na=False), 43560 / 400),
109
+ (df["ZN19_CITY"].str.contains("RAS4", na=False), 43560 / 400),
110
+ (df["ZN19_CITY"].str.contains("R5", na=False), 43560 / 200),
111
+ (df["ZN19_CITY"].str.contains("RE40", na=False), 43560 / 40000),
112
+ (df["ZN19_CITY"].str.contains("RE20", na=False), 43560 / 20000),
113
+ (df["ZN19_CITY"].str.contains("RE15", na=False), 43560 / 15000),
114
+ (df["ZN19_CITY"].str.contains("RE11", na=False), 43560 / 11000),
115
+ (df["ZN19_CITY"].str.contains("RE9", na=False), 43560 / 9000),
116
+ (df["ZN19_CITY"].str.contains("RS", na=False), 43560 / 7500),
117
+ (df["ZN19_CITY"].str.contains("R1", na=False), 43560 / 5000),
118
+ (df["ZN19_CITY"].str.contains("RU", na=False), 43560 / 3500),
119
+ (df["ZN19_CITY"].str.contains("RZ2.5", na=False), 43560 / 2500),
120
+ (df["ZN19_CITY"].str.contains("RZ3", na=False), 43560 / 3000),
121
+ (df["ZN19_CITY"].str.contains("RZ4", na=False), 43560 / 4000),
122
+ (df["ZN19_CITY"].str.contains("RW1", na=False), 43560 / 2300),
123
+ (df["ZN19_CITY"].str.contains("R2", na=False), 43560 / 2500),
124
+ (df["ZN19_CITY"].str.contains("RW2", na=False), 43560 / 1150),
125
+ (df["ZN19_CITY"].str.contains("C1", na=False), 100),
126
+ (df["ZN19_CITY"].str.contains("C2", na=False), 43560 / 400),
127
+ (df["ZN19_CITY"].str.contains("C3", na=False), 110),
128
+ (df["ZN19_CITY"].str.contains("C4", na=False), 200),
129
+ ]
130
+ )
131
+
132
+ # --- Non-LA / fallback density: map ZN19_SCAG codes → du/ac ---
133
+ zn19_scag = df["ZN19_SCAG"].astype(str)
134
+ area_acres = df.to_crs("EPSG:2229").area / 43560
135
+ scag_density = zn19_scag.case_when(
136
+ [
137
+ (zn19_scag == "1110", 1 / area_acres.replace(0, np.nan)),
138
+ (zn19_scag == "1111", 1 / area_acres.replace(0, np.nan)),
139
+ (zn19_scag == "1112", 1 / area_acres.replace(0, np.nan)),
140
+ (zn19_scag == "1113", 1 / area_acres.replace(0, np.nan)),
141
+ (zn19_scag == "1121", 3 / area_acres.replace(0, np.nan)),
142
+ (zn19_scag == "1122", 3 / area_acres.replace(0, np.nan)),
143
+ (zn19_scag == "1140", 3 / area_acres.replace(0, np.nan)),
144
+ (zn19_scag == "1123", 18),
145
+ (zn19_scag == "1124", 60),
146
+ (zn19_scag == "1125", 80),
147
+ (zn19_scag == "1131", 6),
148
+ (zn19_scag == "1150", 1),
149
+ (zn19_scag == "1150", 1),
150
+ (zn19_scag == "1600", 40),
151
+ (zn19_scag == "1610", 40),
152
+ (zn19_scag == "1620", 30),
153
+ (zn19_scag.isin(["1220", "1221", "1222"]), 47),
154
+ (zn19_scag.isin(["2000", "2100", "2200", "2300", "2400", "2500", "2600", "2700"]), 1 / 5),
155
+ (zn19_scag.isin(["1900", "7777", "1500", "1233", "1210", "1211", "1212", "1213", "1247"]), 0),
156
+ (zn19_scag == zn19_scag, np.nan),
157
+ ]
158
+ )
159
+
160
+ # For LA parcels: use ZN19_CITY density if matched, otherwise fall through to SCAG
161
+ is_la = df["CITY"] == "Los Angeles"
162
+
163
+ df["current_density_du_per_ac"] = scag_density
164
+ df.loc[is_la, "current_density_du_per_ac"] = la_density
165
+ df["current_density_du_per_ac"] = pd.to_numeric(df["current_density_du_per_ac"], errors="coerce")
166
+ return df
tests/test_gtfs.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gtfs_kit
2
+ import pandas as pd
3
+
4
+ from shared.api.gtfs import parent_stations_from_gtfs
5
+
6
+
7
+ def _make_feed(**tables) -> gtfs_kit.Feed:
8
+ """Construct a minimal gtfs_kit Feed from raw table dicts."""
9
+ feed = gtfs_kit.Feed(dist_units="km")
10
+ for attr, rows in tables.items():
11
+ setattr(feed, attr, pd.DataFrame(rows))
12
+ return feed
13
+
14
+
15
+ TRIPS_S1A_S1B = [{"route_id": "801", "trip_id": f"t{i}", "service_id": "wk"} for i in range(6)]
16
+
17
+ STOPS_WITH_PARENT = [
18
+ {
19
+ "stop_id": "S1",
20
+ "stop_name": "Main St",
21
+ "stop_lat": 34.0,
22
+ "stop_lon": -118.0,
23
+ "location_type": 1,
24
+ "parent_station": "",
25
+ },
26
+ {
27
+ "stop_id": "S1A",
28
+ "stop_name": "Main St NB",
29
+ "stop_lat": 34.0,
30
+ "stop_lon": -118.0,
31
+ "location_type": 0,
32
+ "parent_station": "S1",
33
+ },
34
+ {
35
+ "stop_id": "S1B",
36
+ "stop_name": "Main St SB",
37
+ "stop_lat": 34.0,
38
+ "stop_lon": -118.0,
39
+ "location_type": 0,
40
+ "parent_station": "S1",
41
+ },
42
+ ]
43
+
44
+
45
+ class TestParentStationsFromGtfs:
46
+ def test_parent_station_with_children(self):
47
+ """Child stop route info and trip counts are aggregated up to the parent."""
48
+ # Arrange
49
+ feed = _make_feed(
50
+ stops=STOPS_WITH_PARENT,
51
+ routes=[{"route_id": "801", "route_type": 1, "agency_id": "metro"}],
52
+ trips=[
53
+ {"route_id": "801", "trip_id": "t1", "service_id": "wk"},
54
+ {"route_id": "801", "trip_id": "t2", "service_id": "wk"},
55
+ ],
56
+ stop_times=[
57
+ {"trip_id": "t1", "stop_id": "S1A", "stop_sequence": 1},
58
+ {"trip_id": "t2", "stop_id": "S1B", "stop_sequence": 1},
59
+ ],
60
+ )
61
+
62
+ # Act
63
+ result = parent_stations_from_gtfs(feed)
64
+
65
+ # Assert
66
+ assert len(result) == 1
67
+ assert result.iloc[0]["stop_id"] == "S1"
68
+ assert "801" in result.iloc[0]["route_ids"]
69
+ assert result.iloc[0]["n_arrivals"] == 2
70
+
71
+ def test_no_parent_stations_falls_back_to_boarding_stops(self):
72
+ """When no location_type=1 stops exist, boarding stops are treated as parents."""
73
+ # Arrange
74
+ feed = _make_feed(
75
+ stops=[
76
+ {
77
+ "stop_id": "S1",
78
+ "stop_name": "Stop 1",
79
+ "stop_lat": 34.0,
80
+ "stop_lon": -118.0,
81
+ "location_type": 0,
82
+ "parent_station": "",
83
+ },
84
+ ],
85
+ routes=[{"route_id": "801", "route_type": 1, "agency_id": "metro"}],
86
+ trips=[{"route_id": "801", "trip_id": "t1", "service_id": "wk"}],
87
+ stop_times=[{"trip_id": "t1", "stop_id": "S1", "stop_sequence": 1}],
88
+ )
89
+
90
+ # Act
91
+ result = parent_stations_from_gtfs(feed)
92
+
93
+ # Assert
94
+ assert len(result) == 1
95
+ assert result.iloc[0]["stop_id"] == "S1"
96
+
97
+ def test_trip_counts_summed_across_children(self):
98
+ """n_arrivals reflects the sum of trips across all child stops, not just the parent."""
99
+ # Arrange
100
+ feed = _make_feed(
101
+ stops=STOPS_WITH_PARENT,
102
+ routes=[{"route_id": "801", "route_type": 1, "agency_id": "metro"}],
103
+ trips=TRIPS_S1A_S1B,
104
+ stop_times=[
105
+ *[{"trip_id": f"t{i}", "stop_id": "S1A", "stop_sequence": 1} for i in range(3)],
106
+ *[{"trip_id": f"t{i}", "stop_id": "S1B", "stop_sequence": 1} for i in range(3, 6)],
107
+ ],
108
+ )
109
+
110
+ # Act
111
+ result = parent_stations_from_gtfs(feed)
112
+
113
+ # Assert
114
+ assert len(result) == 1
115
+ assert result.iloc[0]["n_arrivals"] == 6
116
+
117
+ def test_routes_merged_across_children(self):
118
+ """route_ids, route_types, and agencies are unioned across all child stops."""
119
+ # Arrange
120
+ feed = _make_feed(
121
+ stops=STOPS_WITH_PARENT,
122
+ routes=[
123
+ {"route_id": "801", "route_type": 1, "agency_id": "metro"},
124
+ {"route_id": "901", "route_type": 2, "agency_id": "metrolink"},
125
+ ],
126
+ trips=[
127
+ {"route_id": "801", "trip_id": "t1", "service_id": "wk"},
128
+ {"route_id": "901", "trip_id": "t2", "service_id": "wk"},
129
+ ],
130
+ stop_times=[
131
+ {"trip_id": "t1", "stop_id": "S1A", "stop_sequence": 1},
132
+ {"trip_id": "t2", "stop_id": "S1B", "stop_sequence": 1},
133
+ ],
134
+ )
135
+
136
+ # Act
137
+ result = parent_stations_from_gtfs(feed)
138
+
139
+ # Assert
140
+ assert len(result) == 1
141
+ assert result.iloc[0]["route_ids"] == {"801", "901"}
142
+ assert result.iloc[0]["route_types"] == {"1", "2"}
143
+ assert result.iloc[0]["agencies"] == {"metro", "metrolink"}
144
+
145
+ def test_stop_with_no_trips_excluded(self):
146
+ """Parent stations with no associated trips are excluded from the result."""
147
+ # Arrange
148
+ feed = _make_feed(
149
+ stops=[
150
+ {
151
+ "stop_id": "S1",
152
+ "stop_name": "Served",
153
+ "stop_lat": 34.0,
154
+ "stop_lon": -118.0,
155
+ "location_type": 1,
156
+ "parent_station": "",
157
+ },
158
+ {
159
+ "stop_id": "S2",
160
+ "stop_name": "Unserved",
161
+ "stop_lat": 34.1,
162
+ "stop_lon": -118.1,
163
+ "location_type": 1,
164
+ "parent_station": "",
165
+ },
166
+ ],
167
+ routes=[{"route_id": "801", "route_type": 1, "agency_id": "metro"}],
168
+ trips=[{"route_id": "801", "trip_id": "t1", "service_id": "wk"}],
169
+ stop_times=[{"trip_id": "t1", "stop_id": "S1", "stop_sequence": 1}],
170
+ )
171
+
172
+ # Act
173
+ result = parent_stations_from_gtfs(feed)
174
+
175
+ # Assert
176
+ assert len(result) == 1
177
+ assert result.iloc[0]["stop_id"] == "S1"
178
+
179
+ def test_multiple_parent_stations(self):
180
+ """Each parent station is returned as a separate row with its own aggregated info."""
181
+ # Arrange
182
+ feed = _make_feed(
183
+ stops=[
184
+ {
185
+ "stop_id": "S1",
186
+ "stop_name": "Station 1",
187
+ "stop_lat": 34.0,
188
+ "stop_lon": -118.0,
189
+ "location_type": 1,
190
+ "parent_station": "",
191
+ },
192
+ {
193
+ "stop_id": "S2",
194
+ "stop_name": "Station 2",
195
+ "stop_lat": 34.1,
196
+ "stop_lon": -118.1,
197
+ "location_type": 1,
198
+ "parent_station": "",
199
+ },
200
+ ],
201
+ routes=[{"route_id": "801", "route_type": 1, "agency_id": "metro"}],
202
+ trips=[
203
+ {"route_id": "801", "trip_id": "t1", "service_id": "wk"},
204
+ {"route_id": "801", "trip_id": "t2", "service_id": "wk"},
205
+ ],
206
+ stop_times=[
207
+ {"trip_id": "t1", "stop_id": "S1", "stop_sequence": 1},
208
+ {"trip_id": "t2", "stop_id": "S2", "stop_sequence": 1},
209
+ ],
210
+ )
211
+
212
+ # Act
213
+ result = parent_stations_from_gtfs(feed)
214
+
215
+ # Assert
216
+ assert len(result) == 2
217
+ assert set(result["stop_id"]) == {"S1", "S2"}
218
+
219
+ def test_parent_served_directly_and_via_children(self):
220
+ """Trips at the parent stop_id itself are counted alongside child trips."""
221
+ # Arrange
222
+ feed = _make_feed(
223
+ stops=STOPS_WITH_PARENT,
224
+ routes=[{"route_id": "801", "route_type": 1, "agency_id": "metro"}],
225
+ trips=[
226
+ {"route_id": "801", "trip_id": "t1", "service_id": "wk"},
227
+ {"route_id": "801", "trip_id": "t2", "service_id": "wk"},
228
+ ],
229
+ stop_times=[
230
+ {"trip_id": "t1", "stop_id": "S1", "stop_sequence": 1}, # direct on parent
231
+ {"trip_id": "t2", "stop_id": "S1A", "stop_sequence": 1}, # via child
232
+ ],
233
+ )
234
+
235
+ # Act
236
+ result = parent_stations_from_gtfs(feed)
237
+
238
+ # Assert
239
+ assert len(result) == 1
240
+ assert result.iloc[0]["n_arrivals"] == 2
tests/test_gtfs_to_parcels.py CHANGED
@@ -1,10 +1,5 @@
1
  from __future__ import annotations
2
 
3
- import io
4
- import tempfile
5
- import zipfile
6
- from pathlib import Path
7
-
8
  import geopandas as gpd
9
  import numpy as np
10
  import pytest
@@ -13,58 +8,14 @@ from shapely.geometry import Point, box
13
  from notebooks.sb79map import (
14
  aggregate_parcels_to_stops,
15
  assign_nearest_stop,
16
- compute_scag_density,
17
  create_buffer_donuts,
18
  join_scag_ca_parcels,
19
  trim_around_stations,
20
  )
21
- from shared.pipelines.sb79 import assign_tier_to_stops_from_gtfs
22
  from shared.utils.constants import HALF_MI_M
23
 
24
 
25
- def _make_gtfs_zip(
26
- routes: list[dict],
27
- trips: list[dict],
28
- stop_times: list[dict],
29
- stops: list[dict],
30
- calendar: list[dict] | None = None,
31
- ) -> bytes:
32
- """Create an in-memory GTFS zip file for testing."""
33
- buf = io.BytesIO()
34
- with zipfile.ZipFile(buf, "w") as z:
35
- if routes:
36
- cols = list(routes[0].keys())
37
- z.writestr(
38
- "routes.txt",
39
- ",".join(cols) + "\n" + "\n".join(",".join(str(r[c]) for c in cols) for r in routes),
40
- )
41
- if trips:
42
- cols = list(trips[0].keys())
43
- z.writestr(
44
- "trips.txt",
45
- ",".join(cols) + "\n" + "\n".join(",".join(str(t[c]) for c in cols) for t in trips),
46
- )
47
- if stop_times:
48
- cols = list(stop_times[0].keys())
49
- z.writestr(
50
- "stop_times.txt",
51
- ",".join(cols) + "\n" + "\n".join(",".join(str(s[c]) for c in cols) for s in stop_times),
52
- )
53
- if stops:
54
- cols = list(stops[0].keys())
55
- z.writestr(
56
- "stops.txt",
57
- ",".join(cols) + "\n" + "\n".join(",".join(str(s[c]) for c in cols) for s in stops),
58
- )
59
- if calendar:
60
- cols = list(calendar[0].keys())
61
- z.writestr(
62
- "calendar.txt",
63
- ",".join(cols) + "\n" + "\n".join(",".join(str(c[col]) for col in cols) for c in calendar),
64
- )
65
- return buf.getvalue()
66
-
67
-
68
  def _make_stops_gdf(stops_data: list[dict]) -> gpd.GeoDataFrame:
69
  """Create a stops GeoDataFrame from a list of dicts."""
70
  records = []
@@ -111,381 +62,6 @@ def _make_parcels_gdf(parcels_data: list[dict]) -> gpd.GeoDataFrame:
111
  return gpd.GeoDataFrame(records, crs="EPSG:4326")
112
 
113
 
114
- class TestParseGtfsZip:
115
- def test_basic_parse(self):
116
- """Parse a minimal GTFS zip with one subway route."""
117
- gtfs_bytes = _make_gtfs_zip(
118
- routes=[{"route_id": "801", "route_type": "1", "agency_id": "metro"}],
119
- trips=[
120
- {"route_id": "801", "trip_id": "t1", "service_id": "wk", "direction_id": "0"},
121
- {"route_id": "801", "trip_id": "t2", "service_id": "wk", "direction_id": "1"},
122
- ],
123
- stop_times=[
124
- {"trip_id": "t1", "stop_id": "801S", "arrival_time": "08:00:00", "departure_time": "08:01:00"},
125
- {"trip_id": "t2", "stop_id": "801S", "arrival_time": "08:05:00", "departure_time": "08:06:00"},
126
- ],
127
- stops=[
128
- {
129
- "stop_id": "801S",
130
- "stop_name": "Test Station",
131
- "stop_lat": "34.0",
132
- "stop_lon": "-118.0",
133
- "location_type": "1",
134
- },
135
- ],
136
- calendar=[
137
- {
138
- "service_id": "wk",
139
- "monday": "1",
140
- "tuesday": "1",
141
- "wednesday": "1",
142
- "thursday": "1",
143
- "friday": "1",
144
- "saturday": "0",
145
- "sunday": "0",
146
- "start_date": "20250101",
147
- "end_date": "20251231",
148
- }
149
- ],
150
- )
151
- path = Path(tempfile.gettempdir()) / "_test_gtfs.zip"
152
-
153
- path.write_bytes(gtfs_bytes)
154
- try:
155
- result = assign_tier_to_stops_from_gtfs(path)
156
- assert len(result) == 1
157
- assert result.iloc[0]["stop_id"] == "801S"
158
- assert result.iloc[0]["Tier"] == 1 # subway → Tier 1
159
- assert result.iloc[0]["routetypes"] == "1"
160
- finally:
161
- path.unlink(missing_ok=True)
162
-
163
- def test_tier1_light_rail_high_freq(self):
164
- """route_type=0 with n_arrivals >= 72 → Tier 1."""
165
- gtfs_bytes = _make_gtfs_zip(
166
- routes=[{"route_id": "801", "route_type": "0", "agency_id": "metro"}],
167
- trips=[{"route_id": "801", "trip_id": f"t{i}", "service_id": "wk", "direction_id": "0"} for i in range(40)]
168
- + [{"route_id": "801", "trip_id": f"t{i}", "service_id": "wk", "direction_id": "1"} for i in range(40, 80)],
169
- stop_times=[
170
- {"trip_id": f"t{i}", "stop_id": "801S", "arrival_time": "08:00:00", "departure_time": "08:01:00"}
171
- for i in range(80)
172
- ],
173
- stops=[
174
- {"stop_id": "801S", "stop_name": "Test", "stop_lat": "34.0", "stop_lon": "-118.0", "location_type": "1"},
175
- ],
176
- calendar=[
177
- {
178
- "service_id": "wk",
179
- "monday": "1",
180
- "tuesday": "1",
181
- "wednesday": "1",
182
- "thursday": "1",
183
- "friday": "1",
184
- "saturday": "0",
185
- "sunday": "0",
186
- "start_date": "20250101",
187
- "end_date": "20251231",
188
- }
189
- ],
190
- )
191
- path = Path(tempfile.gettempdir()) / "_test_gtfs2.zip"
192
-
193
- path.write_bytes(gtfs_bytes)
194
- try:
195
- result = assign_tier_to_stops_from_gtfs(path)
196
- assert len(result) == 1
197
- # 80 trips / 1 weekday service = 80/day >= 72 → Tier 1
198
- assert result.iloc[0]["Tier"] == 1
199
- finally:
200
- path.unlink(missing_ok=True)
201
-
202
- def test_tier1_light_rail_high_freq_72plus(self):
203
- """route_type=0 with n_arrivals >= 72 → Tier 1."""
204
- gtfs_bytes = _make_gtfs_zip(
205
- routes=[{"route_id": "801", "route_type": "0", "agency_id": "metro"}],
206
- trips=[{"route_id": "801", "trip_id": f"t{i}", "service_id": "wk", "direction_id": "0"} for i in range(200)]
207
- + [{"route_id": "801", "trip_id": f"t{i}", "service_id": "wk", "direction_id": "1"} for i in range(200, 400)],
208
- stop_times=[
209
- {"trip_id": f"t{i}", "stop_id": "801S", "arrival_time": "08:00:00", "departure_time": "08:01:00"}
210
- for i in range(400)
211
- ],
212
- stops=[
213
- {"stop_id": "801S", "stop_name": "Test", "stop_lat": "34.0", "stop_lon": "-118.0", "location_type": "1"},
214
- ],
215
- calendar=[
216
- {
217
- "service_id": "wk",
218
- "monday": "1",
219
- "tuesday": "1",
220
- "wednesday": "1",
221
- "thursday": "1",
222
- "friday": "1",
223
- "saturday": "0",
224
- "sunday": "0",
225
- "start_date": "20250101",
226
- "end_date": "20251231",
227
- }
228
- ],
229
- )
230
- path = Path(tempfile.gettempdir()) / "_test_gtfs3.zip"
231
-
232
- path.write_bytes(gtfs_bytes)
233
- try:
234
- result = assign_tier_to_stops_from_gtfs(path)
235
- assert len(result) == 1
236
- # 400 trips / 5 days = 80/day >= 72 → Tier 1
237
- assert result.iloc[0]["Tier"] == 1
238
- finally:
239
- path.unlink(missing_ok=True)
240
-
241
- def test_tier2_light_rail_low_freq(self):
242
- """route_type=0 with n_arrivals < 72 → Tier 2."""
243
- gtfs_bytes = _make_gtfs_zip(
244
- routes=[{"route_id": "801", "route_type": "0", "agency_id": "metro"}],
245
- trips=[{"route_id": "801", "trip_id": f"t{i}", "service_id": "wk", "direction_id": "0"} for i in range(10)]
246
- + [{"route_id": "801", "trip_id": f"t{i}", "service_id": "wk", "direction_id": "1"} for i in range(10, 20)],
247
- stop_times=[
248
- {"trip_id": f"t{i}", "stop_id": "801S", "arrival_time": "08:00:00", "departure_time": "08:01:00"}
249
- for i in range(20)
250
- ],
251
- stops=[
252
- {"stop_id": "801S", "stop_name": "Test", "stop_lat": "34.0", "stop_lon": "-118.0", "location_type": "1"},
253
- ],
254
- calendar=[
255
- {
256
- "service_id": "wk",
257
- "monday": "1",
258
- "tuesday": "1",
259
- "wednesday": "1",
260
- "thursday": "1",
261
- "friday": "1",
262
- "saturday": "0",
263
- "sunday": "0",
264
- "start_date": "20250101",
265
- "end_date": "20251231",
266
- }
267
- ],
268
- )
269
- path = Path(tempfile.gettempdir()) / "_test_gtfs4.zip"
270
-
271
- path.write_bytes(gtfs_bytes)
272
- try:
273
- result = assign_tier_to_stops_from_gtfs(path)
274
- assert len(result) == 1
275
- # 20 trips / 5 = 4/day < 72 → Tier 2
276
- assert result.iloc[0]["Tier"] == 2
277
- finally:
278
- path.unlink(missing_ok=True)
279
-
280
- def test_tier2_commuter_rail_medium(self):
281
- """route_type=2 with 48 <= n_arrivals < 72 → Tier 2."""
282
- # gtfs_kit counts all trips across all services active on the weekday.
283
- # Use 60 trips with a single service: 48 <= 60 < 72 → Tier 2
284
- gtfs_bytes = _make_gtfs_zip(
285
- routes=[{"route_id": "701", "route_type": "2", "agency_id": "metrolink"}],
286
- trips=[{"route_id": "701", "trip_id": f"t{i}", "service_id": "wk", "direction_id": "0"} for i in range(30)]
287
- + [{"route_id": "701", "trip_id": f"t{i}", "service_id": "wk", "direction_id": "1"} for i in range(30, 60)],
288
- stop_times=[
289
- {"trip_id": f"t{i}", "stop_id": "701S", "arrival_time": "08:00:00", "departure_time": "08:01:00"}
290
- for i in range(60)
291
- ],
292
- stops=[
293
- {"stop_id": "701S", "stop_name": "Test", "stop_lat": "34.0", "stop_lon": "-118.0", "location_type": "1"},
294
- ],
295
- calendar=[
296
- {
297
- "service_id": "wk",
298
- "monday": "1",
299
- "tuesday": "1",
300
- "wednesday": "1",
301
- "thursday": "1",
302
- "friday": "1",
303
- "saturday": "0",
304
- "sunday": "0",
305
- "start_date": "20250101",
306
- "end_date": "20251231",
307
- },
308
- ],
309
- )
310
- path = Path(tempfile.gettempdir()) / "_test_gtfs5.zip"
311
-
312
- path.write_bytes(gtfs_bytes)
313
- try:
314
- result = assign_tier_to_stops_from_gtfs(path)
315
- assert len(result) == 1
316
- # 60 trips, 48 <= 60 < 72 → Tier 2
317
- assert result.iloc[0]["Tier"] == 2
318
- finally:
319
- path.unlink(missing_ok=True)
320
-
321
- def test_tier_override(self):
322
- """Override a Tier 1 route to Tier 2."""
323
- gtfs_bytes = _make_gtfs_zip(
324
- routes=[{"route_id": "801", "route_type": "1", "agency_id": "metro"}],
325
- trips=[
326
- {"route_id": "801", "trip_id": "t1", "service_id": "wk", "direction_id": "0"},
327
- ],
328
- stop_times=[{"trip_id": "t1", "stop_id": "801S", "arrival_time": "08:00:00", "departure_time": "08:01:00"}],
329
- stops=[
330
- {"stop_id": "801S", "stop_name": "Test", "stop_lat": "34.0", "stop_lon": "-118.0", "location_type": "1"},
331
- ],
332
- calendar=[
333
- {
334
- "service_id": "wk",
335
- "monday": "1",
336
- "tuesday": "1",
337
- "wednesday": "1",
338
- "thursday": "1",
339
- "friday": "1",
340
- "saturday": "0",
341
- "sunday": "0",
342
- "start_date": "20250101",
343
- "end_date": "20251231",
344
- }
345
- ],
346
- )
347
- path = Path(tempfile.gettempdir()) / "_test_gtfs6.zip"
348
-
349
- path.write_bytes(gtfs_bytes)
350
- try:
351
- result = assign_tier_to_stops_from_gtfs(path, tier_overrides={"801": 2})
352
- assert len(result) == 1
353
- assert result.iloc[0]["Tier"] == 2 # overridden
354
- finally:
355
- path.unlink(missing_ok=True)
356
-
357
- def test_skip_non_tier_stops(self):
358
- """Stops with route_type > 2 (e.g. bus) should be excluded."""
359
- gtfs_bytes = _make_gtfs_zip(
360
- routes=[{"route_id": "901", "route_type": "3", "agency_id": "metro"}],
361
- trips=[
362
- {"route_id": "901", "trip_id": "t1", "service_id": "wk", "direction_id": "0"},
363
- ],
364
- stop_times=[{"trip_id": "t1", "stop_id": "901S", "arrival_time": "08:00:00", "departure_time": "08:01:00"}],
365
- stops=[
366
- {"stop_id": "901S", "stop_name": "Bus Stop", "stop_lat": "34.0", "stop_lon": "-118.0", "location_type": "1"},
367
- ],
368
- calendar=[
369
- {
370
- "service_id": "wk",
371
- "monday": "1",
372
- "tuesday": "1",
373
- "wednesday": "1",
374
- "thursday": "1",
375
- "friday": "1",
376
- "saturday": "0",
377
- "sunday": "0",
378
- "start_date": "20250101",
379
- "end_date": "20251231",
380
- }
381
- ],
382
- )
383
- path = Path(tempfile.gettempdir()) / "_test_gtfs7.zip"
384
-
385
- path.write_bytes(gtfs_bytes)
386
- try:
387
- result = assign_tier_to_stops_from_gtfs(path)
388
- assert len(result) == 0 # no Tier 1 or 2 stops
389
- finally:
390
- path.unlink(missing_ok=True)
391
-
392
- def test_no_parent_stations(self):
393
- """Feed with only location_type=0 stops (no parent stations) should still work.
394
-
395
- Some GTFS feeds (e.g. OC Streetcar) have no location_type=1 entries.
396
- Each boarding stop should be treated as its own station.
397
- """
398
- gtfs_bytes = _make_gtfs_zip(
399
- routes=[{"route_id": "801", "route_type": "0", "agency_id": "metro"}],
400
- trips=[
401
- {"route_id": "801", "trip_id": "t1", "service_id": "wk", "direction_id": "0"},
402
- {"route_id": "801", "trip_id": "t2", "service_id": "wk", "direction_id": "1"},
403
- ],
404
- stop_times=[
405
- {"trip_id": "t1", "stop_id": "S1", "arrival_time": "08:00:00", "departure_time": "08:01:00"},
406
- {"trip_id": "t2", "stop_id": "S1", "arrival_time": "08:05:00", "departure_time": "08:06:00"},
407
- ],
408
- stops=[
409
- {
410
- "stop_id": "S1",
411
- "stop_name": "Stop 1",
412
- "stop_lat": "34.0",
413
- "stop_lon": "-118.0",
414
- "location_type": "0",
415
- },
416
- ],
417
- calendar=[
418
- {
419
- "service_id": "wk",
420
- "monday": "1",
421
- "tuesday": "1",
422
- "wednesday": "1",
423
- "thursday": "1",
424
- "friday": "1",
425
- "saturday": "0",
426
- "sunday": "0",
427
- "start_date": "20250101",
428
- "end_date": "20251231",
429
- }
430
- ],
431
- )
432
- path = Path(tempfile.gettempdir()) / "_test_gtfs_no_parent.zip"
433
-
434
- path.write_bytes(gtfs_bytes)
435
- try:
436
- result = assign_tier_to_stops_from_gtfs(path)
437
- assert len(result) == 1
438
- assert result.iloc[0]["stop_id"] == "S1"
439
- assert result.iloc[0]["Tier"] == 2 # route_type=0, 2 trips/5=0.4/day < 72
440
- finally:
441
- path.unlink(missing_ok=True)
442
-
443
- def test_mixed_route_types(self):
444
- """Station with route_types '0,1' should be Tier 1 (has subway)."""
445
-
446
- gtfs_bytes = _make_gtfs_zip(
447
- routes=[
448
- {"route_id": "801", "route_type": "1", "agency_id": "metro"},
449
- {"route_id": "802", "route_type": "0", "agency_id": "metro"},
450
- ],
451
- trips=[
452
- {"route_id": "801", "trip_id": "t1", "service_id": "wk", "direction_id": "0"},
453
- {"route_id": "802", "trip_id": "t2", "service_id": "wk", "direction_id": "0"},
454
- ],
455
- stop_times=[
456
- {"trip_id": "t1", "stop_id": "801S", "arrival_time": "08:00:00", "departure_time": "08:01:00"},
457
- {"trip_id": "t2", "stop_id": "801S", "arrival_time": "08:05:00", "departure_time": "08:06:00"},
458
- ],
459
- stops=[
460
- {"stop_id": "801S", "stop_name": "Mixed", "stop_lat": "34.0", "stop_lon": "-118.0", "location_type": "1"},
461
- ],
462
- calendar=[
463
- {
464
- "service_id": "wk",
465
- "monday": "1",
466
- "tuesday": "1",
467
- "wednesday": "1",
468
- "thursday": "1",
469
- "friday": "1",
470
- "saturday": "0",
471
- "sunday": "0",
472
- "start_date": "20250101",
473
- "end_date": "20251231",
474
- }
475
- ],
476
- )
477
- path = Path(tempfile.gettempdir()) / "_test_gtfs8.zip"
478
-
479
- path.write_bytes(gtfs_bytes)
480
- try:
481
- result = assign_tier_to_stops_from_gtfs(path)
482
- assert len(result) == 1
483
- assert result.iloc[0]["Tier"] == 1 # has route_type 1
484
- assert "1" in result.iloc[0]["routetypes"]
485
- finally:
486
- path.unlink(missing_ok=True)
487
-
488
-
489
  # ---------------------------------------------------------------------------
490
  # Tests: compute_scag_density
491
  # ---------------------------------------------------------------------------
 
1
  from __future__ import annotations
2
 
 
 
 
 
 
3
  import geopandas as gpd
4
  import numpy as np
5
  import pytest
 
8
  from notebooks.sb79map import (
9
  aggregate_parcels_to_stops,
10
  assign_nearest_stop,
 
11
  create_buffer_donuts,
12
  join_scag_ca_parcels,
13
  trim_around_stations,
14
  )
15
+ from shared.pipelines.sb79 import compute_scag_density
16
  from shared.utils.constants import HALF_MI_M
17
 
18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  def _make_stops_gdf(stops_data: list[dict]) -> gpd.GeoDataFrame:
20
  """Create a stops GeoDataFrame from a list of dicts."""
21
  records = []
 
62
  return gpd.GeoDataFrame(records, crs="EPSG:4326")
63
 
64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  # ---------------------------------------------------------------------------
66
  # Tests: compute_scag_density
67
  # ---------------------------------------------------------------------------
tests/test_sb79.py ADDED
@@ -0,0 +1,442 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import tempfile
3
+ import zipfile
4
+ from pathlib import Path
5
+
6
+ from shared.pipelines.sb79 import assign_tier_to_stops_from_gtfs
7
+
8
+
9
+ def _make_gtfs_zip(
10
+ gtfs_data: dict[str, list[dict]],
11
+ ) -> bytes:
12
+ """Create an in-memory GTFS zip file for testing."""
13
+ buf = io.BytesIO()
14
+ with zipfile.ZipFile(buf, "w") as z:
15
+ for filename, rows in gtfs_data.items():
16
+ if not rows:
17
+ continue
18
+ cols = list(rows[0].keys())
19
+ z.writestr(
20
+ f"{filename}.txt",
21
+ ",".join(cols) + "\n" + "\n".join(",".join(str(r[c]) for c in cols) for r in rows),
22
+ )
23
+ return buf.getvalue()
24
+
25
+
26
+ class TestParseGtfsZip:
27
+ def test_basic_parse(self):
28
+ """Parse a minimal GTFS zip with one subway route."""
29
+ gtfs_bytes = _make_gtfs_zip(
30
+ {
31
+ "routes": [{"route_id": "801", "route_type": "1", "agency_id": "metro"}],
32
+ "trips": [
33
+ {"route_id": "801", "trip_id": "t1", "service_id": "wk", "direction_id": "0"},
34
+ {"route_id": "801", "trip_id": "t2", "service_id": "wk", "direction_id": "1"},
35
+ ],
36
+ "stop_times": [
37
+ {"trip_id": "t1", "stop_id": "801S", "arrival_time": "08:00:00", "departure_time": "08:01:00"},
38
+ {"trip_id": "t2", "stop_id": "801S", "arrival_time": "08:05:00", "departure_time": "08:06:00"},
39
+ ],
40
+ "stops": [
41
+ {
42
+ "stop_id": "801S",
43
+ "stop_name": "Test Station",
44
+ "stop_lat": "34.0",
45
+ "stop_lon": "-118.0",
46
+ "location_type": "1",
47
+ },
48
+ ],
49
+ "calendar": [
50
+ {
51
+ "service_id": "wk",
52
+ "monday": "1",
53
+ "tuesday": "1",
54
+ "wednesday": "1",
55
+ "thursday": "1",
56
+ "friday": "1",
57
+ "saturday": "0",
58
+ "sunday": "0",
59
+ "start_date": "20250101",
60
+ "end_date": "20251231",
61
+ }
62
+ ],
63
+ }
64
+ )
65
+ path = Path(tempfile.gettempdir()) / "_test_gtfs.zip"
66
+
67
+ path.write_bytes(gtfs_bytes)
68
+ try:
69
+ result = assign_tier_to_stops_from_gtfs(path)
70
+ assert len(result) == 1
71
+ assert result.iloc[0]["stop_id"] == "801S"
72
+ assert result.iloc[0]["Tier"] == 1 # subway → Tier 1
73
+ assert result.iloc[0]["routetypes"] == "1"
74
+ finally:
75
+ path.unlink(missing_ok=True)
76
+
77
+ def test_tier1_light_rail_high_freq(self):
78
+ """route_type=0 with n_arrivals >= 72 → Tier 1."""
79
+ gtfs_bytes = _make_gtfs_zip(
80
+ {
81
+ "routes": [{"route_id": "801", "route_type": "0", "agency_id": "metro"}],
82
+ "trips": [
83
+ {"route_id": "801", "trip_id": f"t{i}", "service_id": "wk", "direction_id": "0"} for i in range(40)
84
+ ]
85
+ + [{"route_id": "801", "trip_id": f"t{i}", "service_id": "wk", "direction_id": "1"} for i in range(40, 80)],
86
+ "stop_times": [
87
+ {"trip_id": f"t{i}", "stop_id": "801S", "arrival_time": "08:00:00", "departure_time": "08:01:00"}
88
+ for i in range(80)
89
+ ],
90
+ "stops": [
91
+ {"stop_id": "801S", "stop_name": "Test", "stop_lat": "34.0", "stop_lon": "-118.0", "location_type": "1"},
92
+ ],
93
+ "calendar": [
94
+ {
95
+ "service_id": "wk",
96
+ "monday": "1",
97
+ "tuesday": "1",
98
+ "wednesday": "1",
99
+ "thursday": "1",
100
+ "friday": "1",
101
+ "saturday": "0",
102
+ "sunday": "0",
103
+ "start_date": "20250101",
104
+ "end_date": "20251231",
105
+ }
106
+ ],
107
+ }
108
+ )
109
+ path = Path(tempfile.gettempdir()) / "_test_gtfs2.zip"
110
+
111
+ path.write_bytes(gtfs_bytes)
112
+ try:
113
+ result = assign_tier_to_stops_from_gtfs(path)
114
+ assert len(result) == 1
115
+ # 80 trips / 1 weekday service = 80/day >= 72 → Tier 1
116
+ assert result.iloc[0]["Tier"] == 1
117
+ finally:
118
+ path.unlink(missing_ok=True)
119
+
120
+ def test_tier1_light_rail_high_freq_72plus(self):
121
+ """route_type=0 with n_arrivals >= 72 → Tier 1."""
122
+ gtfs_bytes = _make_gtfs_zip(
123
+ {
124
+ "routes": [{"route_id": "801", "route_type": "0", "agency_id": "metro"}],
125
+ "trips": [
126
+ {"route_id": "801", "trip_id": f"t{i}", "service_id": "wk", "direction_id": "0"} for i in range(200)
127
+ ]
128
+ + [
129
+ {"route_id": "801", "trip_id": f"t{i}", "service_id": "wk", "direction_id": "1"} for i in range(200, 400)
130
+ ],
131
+ "stop_times": [
132
+ {"trip_id": f"t{i}", "stop_id": "801S", "arrival_time": "08:00:00", "departure_time": "08:01:00"}
133
+ for i in range(400)
134
+ ],
135
+ "stops": [
136
+ {"stop_id": "801S", "stop_name": "Test", "stop_lat": "34.0", "stop_lon": "-118.0", "location_type": "1"},
137
+ ],
138
+ "calendar": [
139
+ {
140
+ "service_id": "wk",
141
+ "monday": "1",
142
+ "tuesday": "1",
143
+ "wednesday": "1",
144
+ "thursday": "1",
145
+ "friday": "1",
146
+ "saturday": "0",
147
+ "sunday": "0",
148
+ "start_date": "20250101",
149
+ "end_date": "20251231",
150
+ }
151
+ ],
152
+ }
153
+ )
154
+ path = Path(tempfile.gettempdir()) / "_test_gtfs3.zip"
155
+
156
+ path.write_bytes(gtfs_bytes)
157
+ try:
158
+ result = assign_tier_to_stops_from_gtfs(path)
159
+ assert len(result) == 1
160
+ # 400 trips / 5 days = 80/day >= 72 → Tier 1
161
+ assert result.iloc[0]["Tier"] == 1
162
+ finally:
163
+ path.unlink(missing_ok=True)
164
+
165
+ def test_tier2_light_rail_low_freq(self):
166
+ """route_type=0 with n_arrivals < 72 → Tier 2."""
167
+ gtfs_bytes = _make_gtfs_zip(
168
+ {
169
+ "routes": [{"route_id": "801", "route_type": "0", "agency_id": "metro"}],
170
+ "trips": [
171
+ {"route_id": "801", "trip_id": f"t{i}", "service_id": "wk", "direction_id": "0"} for i in range(10)
172
+ ]
173
+ + [{"route_id": "801", "trip_id": f"t{i}", "service_id": "wk", "direction_id": "1"} for i in range(10, 20)],
174
+ "stop_times": [
175
+ {"trip_id": f"t{i}", "stop_id": "801S", "arrival_time": "08:00:00", "departure_time": "08:01:00"}
176
+ for i in range(20)
177
+ ],
178
+ "stops": [
179
+ {"stop_id": "801S", "stop_name": "Test", "stop_lat": "34.0", "stop_lon": "-118.0", "location_type": "1"},
180
+ ],
181
+ "calendar": [
182
+ {
183
+ "service_id": "wk",
184
+ "monday": "1",
185
+ "tuesday": "1",
186
+ "wednesday": "1",
187
+ "thursday": "1",
188
+ "friday": "1",
189
+ "saturday": "0",
190
+ "sunday": "0",
191
+ "start_date": "20250101",
192
+ "end_date": "20251231",
193
+ }
194
+ ],
195
+ }
196
+ )
197
+ path = Path(tempfile.gettempdir()) / "_test_gtfs4.zip"
198
+
199
+ path.write_bytes(gtfs_bytes)
200
+ try:
201
+ result = assign_tier_to_stops_from_gtfs(path)
202
+ assert len(result) == 1
203
+ # 20 trips / 5 = 4/day < 72 → Tier 2
204
+ assert result.iloc[0]["Tier"] == 2
205
+ finally:
206
+ path.unlink(missing_ok=True)
207
+
208
+ def test_tier2_commuter_rail_medium(self):
209
+ """route_type=2 with 48 <= n_arrivals < 72 → Tier 2."""
210
+ # gtfs_kit counts all trips across all services active on the weekday.
211
+ # Use 60 trips with a single service: 48 <= 60 < 72 → Tier 2
212
+ gtfs_bytes = _make_gtfs_zip(
213
+ {
214
+ "routes": [{"route_id": "701", "route_type": "2", "agency_id": "metrolink"}],
215
+ "trips": [
216
+ {"route_id": "701", "trip_id": f"t{i}", "service_id": "wk", "direction_id": "0"} for i in range(30)
217
+ ]
218
+ + [{"route_id": "701", "trip_id": f"t{i}", "service_id": "wk", "direction_id": "1"} for i in range(30, 60)],
219
+ "stop_times": [
220
+ {"trip_id": f"t{i}", "stop_id": "701S", "arrival_time": "08:00:00", "departure_time": "08:01:00"}
221
+ for i in range(60)
222
+ ],
223
+ "stops": [
224
+ {"stop_id": "701S", "stop_name": "Test", "stop_lat": "34.0", "stop_lon": "-118.0", "location_type": "1"},
225
+ ],
226
+ "calendar": [
227
+ {
228
+ "service_id": "wk",
229
+ "monday": "1",
230
+ "tuesday": "1",
231
+ "wednesday": "1",
232
+ "thursday": "1",
233
+ "friday": "1",
234
+ "saturday": "0",
235
+ "sunday": "0",
236
+ "start_date": "20250101",
237
+ "end_date": "20251231",
238
+ },
239
+ ],
240
+ }
241
+ )
242
+ path = Path(tempfile.gettempdir()) / "_test_gtfs5.zip"
243
+
244
+ path.write_bytes(gtfs_bytes)
245
+ try:
246
+ result = assign_tier_to_stops_from_gtfs(path)
247
+ assert len(result) == 1
248
+ # 60 trips, 48 <= 60 < 72 → Tier 2
249
+ assert result.iloc[0]["Tier"] == 2
250
+ finally:
251
+ path.unlink(missing_ok=True)
252
+
253
+ def test_tier_override(self):
254
+ """Override a Tier 1 route to Tier 2."""
255
+ gtfs_bytes = _make_gtfs_zip(
256
+ {
257
+ "routes": [{"route_id": "801", "route_type": "1", "agency_id": "metro"}],
258
+ "trips": [
259
+ {"route_id": "801", "trip_id": "t1", "service_id": "wk", "direction_id": "0"},
260
+ ],
261
+ "stop_times": [
262
+ {"trip_id": "t1", "stop_id": "801S", "arrival_time": "08:00:00", "departure_time": "08:01:00"}
263
+ ],
264
+ "stops": [
265
+ {"stop_id": "801S", "stop_name": "Test", "stop_lat": "34.0", "stop_lon": "-118.0", "location_type": "1"},
266
+ ],
267
+ "calendar": [
268
+ {
269
+ "service_id": "wk",
270
+ "monday": "1",
271
+ "tuesday": "1",
272
+ "wednesday": "1",
273
+ "thursday": "1",
274
+ "friday": "1",
275
+ "saturday": "0",
276
+ "sunday": "0",
277
+ "start_date": "20250101",
278
+ "end_date": "20251231",
279
+ }
280
+ ],
281
+ }
282
+ )
283
+ path = Path(tempfile.gettempdir()) / "_test_gtfs6.zip"
284
+
285
+ path.write_bytes(gtfs_bytes)
286
+ try:
287
+ result = assign_tier_to_stops_from_gtfs(path, tier_overrides={"801": 2})
288
+ assert len(result) == 1
289
+ assert result.iloc[0]["Tier"] == 2 # overridden
290
+ finally:
291
+ path.unlink(missing_ok=True)
292
+
293
+ def test_skip_non_tier_stops(self):
294
+ """Stops with route_type > 2 (e.g. bus) should be excluded."""
295
+ gtfs_bytes = _make_gtfs_zip(
296
+ {
297
+ "routes": [{"route_id": "901", "route_type": "3", "agency_id": "metro"}],
298
+ "trips": [
299
+ {"route_id": "901", "trip_id": "t1", "service_id": "wk", "direction_id": "0"},
300
+ ],
301
+ "stop_times": [
302
+ {"trip_id": "t1", "stop_id": "901S", "arrival_time": "08:00:00", "departure_time": "08:01:00"}
303
+ ],
304
+ "stops": [
305
+ {
306
+ "stop_id": "901S",
307
+ "stop_name": "Bus Stop",
308
+ "stop_lat": "34.0",
309
+ "stop_lon": "-118.0",
310
+ "location_type": "1",
311
+ },
312
+ ],
313
+ "calendar": [
314
+ {
315
+ "service_id": "wk",
316
+ "monday": "1",
317
+ "tuesday": "1",
318
+ "wednesday": "1",
319
+ "thursday": "1",
320
+ "friday": "1",
321
+ "saturday": "0",
322
+ "sunday": "0",
323
+ "start_date": "20250101",
324
+ "end_date": "20251231",
325
+ }
326
+ ],
327
+ }
328
+ )
329
+ path = Path(tempfile.gettempdir()) / "_test_gtfs7.zip"
330
+
331
+ path.write_bytes(gtfs_bytes)
332
+ try:
333
+ result = assign_tier_to_stops_from_gtfs(path)
334
+ assert len(result) == 0 # no Tier 1 or 2 stops
335
+ finally:
336
+ path.unlink(missing_ok=True)
337
+
338
+ def test_no_parent_stations(self):
339
+ """Feed with only location_type=0 stops (no parent stations) should still work.
340
+
341
+ Some GTFS feeds (e.g. OC Streetcar) have no location_type=1 entries.
342
+ Each boarding stop should be treated as its own station.
343
+ """
344
+ gtfs_bytes = _make_gtfs_zip(
345
+ {
346
+ "routes": [{"route_id": "801", "route_type": "0", "agency_id": "metro"}],
347
+ "trips": [
348
+ {"route_id": "801", "trip_id": "t1", "service_id": "wk", "direction_id": "0"},
349
+ {"route_id": "801", "trip_id": "t2", "service_id": "wk", "direction_id": "1"},
350
+ ],
351
+ "stop_times": [
352
+ {"trip_id": "t1", "stop_id": "S1", "arrival_time": "08:00:00", "departure_time": "08:01:00"},
353
+ {"trip_id": "t2", "stop_id": "S1", "arrival_time": "08:05:00", "departure_time": "08:06:00"},
354
+ ],
355
+ "stops": [
356
+ {
357
+ "stop_id": "S1",
358
+ "stop_name": "Stop 1",
359
+ "stop_lat": "34.0",
360
+ "stop_lon": "-118.0",
361
+ "location_type": "0",
362
+ },
363
+ ],
364
+ "calendar": [
365
+ {
366
+ "service_id": "wk",
367
+ "monday": "1",
368
+ "tuesday": "1",
369
+ "wednesday": "1",
370
+ "thursday": "1",
371
+ "friday": "1",
372
+ "saturday": "0",
373
+ "sunday": "0",
374
+ "start_date": "20250101",
375
+ "end_date": "20251231",
376
+ }
377
+ ],
378
+ }
379
+ )
380
+ path = Path(tempfile.gettempdir()) / "_test_gtfs_no_parent.zip"
381
+
382
+ path.write_bytes(gtfs_bytes)
383
+ try:
384
+ result = assign_tier_to_stops_from_gtfs(path)
385
+ assert len(result) == 1
386
+ assert result.iloc[0]["stop_id"] == "S1"
387
+ assert result.iloc[0]["Tier"] == 2 # route_type=0, 2 trips/5=0.4/day < 72
388
+ finally:
389
+ path.unlink(missing_ok=True)
390
+
391
+ def test_mixed_route_types(self):
392
+ """Station with route_types '0,1' should be Tier 1 (has subway)."""
393
+
394
+ gtfs_bytes = _make_gtfs_zip(
395
+ {
396
+ "routes": [
397
+ {"route_id": "801", "route_type": "1", "agency_id": "metro"},
398
+ {"route_id": "802", "route_type": "0", "agency_id": "metro"},
399
+ ],
400
+ "trips": [
401
+ {"route_id": "801", "trip_id": "t1", "service_id": "wk", "direction_id": "0"},
402
+ {"route_id": "802", "trip_id": "t2", "service_id": "wk", "direction_id": "0"},
403
+ ],
404
+ "stop_times": [
405
+ {"trip_id": "t1", "stop_id": "801S", "arrival_time": "08:00:00", "departure_time": "08:01:00"},
406
+ {"trip_id": "t2", "stop_id": "801S", "arrival_time": "08:05:00", "departure_time": "08:06:00"},
407
+ ],
408
+ "stops": [
409
+ {
410
+ "stop_id": "801S",
411
+ "stop_name": "Mixed",
412
+ "stop_lat": "34.0",
413
+ "stop_lon": "-118.0",
414
+ "location_type": "1",
415
+ },
416
+ ],
417
+ "calendar": [
418
+ {
419
+ "service_id": "wk",
420
+ "monday": "1",
421
+ "tuesday": "1",
422
+ "wednesday": "1",
423
+ "thursday": "1",
424
+ "friday": "1",
425
+ "saturday": "0",
426
+ "sunday": "0",
427
+ "start_date": "20250101",
428
+ "end_date": "20251231",
429
+ }
430
+ ],
431
+ }
432
+ )
433
+ path = Path(tempfile.gettempdir()) / "_test_gtfs8.zip"
434
+
435
+ path.write_bytes(gtfs_bytes)
436
+ try:
437
+ result = assign_tier_to_stops_from_gtfs(path)
438
+ assert len(result) == 1
439
+ assert result.iloc[0]["Tier"] == 1 # has route_type 1
440
+ assert "1" in result.iloc[0]["routetypes"]
441
+ finally:
442
+ path.unlink(missing_ok=True)