Spaces:
Sleeping

dn commited on
Commit
c702e19
·
1 Parent(s): a5376c5

cleaning up notebook

Browse files
.gitignore CHANGED
@@ -1,6 +1,7 @@
1
  _site/
2
  __marimo__
3
  test_output
 
4
 
5
  .vscode/
6
  data/
 
1
  _site/
2
  __marimo__
3
  test_output
4
+ .ruff_cache/
5
 
6
  .vscode/
7
  data/
{src → notebooks}/__init__.py RENAMED
File without changes
notebooks/gtfs.py CHANGED
@@ -10,7 +10,7 @@
10
 
11
  import marimo
12
 
13
- __generated_with = "0.23.3"
14
  app = marimo.App(width="medium")
15
 
16
  with app.setup:
@@ -93,7 +93,7 @@ def _(stops_df):
93
 
94
  parcels = parcels.set_crs("EPSG:4326").to_crs("EPSG:3310")
95
  parcels
96
- return
97
 
98
 
99
  @app.cell
@@ -331,7 +331,7 @@ def _(halfmile_donut, qtrmile_donut, trim_200ft_df):
331
  print(f"Total dwelling units: {residential_by_apn['dwelling_units_new'].sum():.0f}")
332
 
333
  residential_by_apn.to_file(OUT_PATH + r"\zoning_around_metro.json", driver="GeoJSON")
334
- return (residential_by_apn,)
335
 
336
 
337
  @app.cell
@@ -474,11 +474,11 @@ def _(stops_df):
474
  # parcels = gpd.GeoDataFrame(pd.concat([parcels, _parcels], ignore_index=True))
475
  # time.sleep(delay)
476
  # parcels
477
- return (buffer,)
478
 
479
 
480
  @app.cell
481
- def _(gpd):
482
  parcel_file = gpd.read_file(r"C:\Users\dknom\code\missing_metro\data\parcels.geojson")
483
  parcel_file
484
  return (parcel_file,)
@@ -503,14 +503,14 @@ def _(stops_df):
503
 
504
 
505
  @app.cell
506
- def _(gpd):
507
  parcels_clipped = gpd.read_file(r"C:\Users\dknom\code\missing_metro\data\parcels_clipped.geojson", driver="GeoJSON")
508
  parcels_clipped
509
  return (parcels_clipped,)
510
 
511
 
512
  @app.cell
513
- def _(buffer, gpd, parcels_clipped):
514
  parcels_with_stops = gpd.sjoin(
515
  parcels_clipped.to_crs("EPSG:3310"),
516
  buffer[["stop_id", "geometry"]],
@@ -614,7 +614,7 @@ def _(parcels_deduped):
614
 
615
 
616
  @app.cell
617
- def _(gpd):
618
  scag_parcels = gpd.read_file(r"C:\Users\dknom\code\missing_metro\data\zoning_around_metro.json", driver="GeoJSON")
619
  scag_parcels
620
  return
@@ -622,6 +622,3 @@ def _(gpd):
622
 
623
  if __name__ == "__main__":
624
  app.run()
625
-
626
- if __name__ == "__main__":
627
- app.run()
 
10
 
11
  import marimo
12
 
13
+ __generated_with = "0.23.5"
14
  app = marimo.App(width="medium")
15
 
16
  with app.setup:
 
93
 
94
  parcels = parcels.set_crs("EPSG:4326").to_crs("EPSG:3310")
95
  parcels
96
+ return (buffer,)
97
 
98
 
99
  @app.cell
 
331
  print(f"Total dwelling units: {residential_by_apn['dwelling_units_new'].sum():.0f}")
332
 
333
  residential_by_apn.to_file(OUT_PATH + r"\zoning_around_metro.json", driver="GeoJSON")
334
+ return residential_by_apn, unary_union
335
 
336
 
337
  @app.cell
 
474
  # parcels = gpd.GeoDataFrame(pd.concat([parcels, _parcels], ignore_index=True))
475
  # time.sleep(delay)
476
  # parcels
477
+ return HALF_MI_M, buffer
478
 
479
 
480
  @app.cell
481
+ def _():
482
  parcel_file = gpd.read_file(r"C:\Users\dknom\code\missing_metro\data\parcels.geojson")
483
  parcel_file
484
  return (parcel_file,)
 
503
 
504
 
505
  @app.cell
506
+ def _():
507
  parcels_clipped = gpd.read_file(r"C:\Users\dknom\code\missing_metro\data\parcels_clipped.geojson", driver="GeoJSON")
508
  parcels_clipped
509
  return (parcels_clipped,)
510
 
511
 
512
  @app.cell
513
+ def _(buffer, parcels_clipped):
514
  parcels_with_stops = gpd.sjoin(
515
  parcels_clipped.to_crs("EPSG:3310"),
516
  buffer[["stop_id", "geometry"]],
 
614
 
615
 
616
  @app.cell
617
+ def _():
618
  scag_parcels = gpd.read_file(r"C:\Users\dknom\code\missing_metro\data\zoning_around_metro.json", driver="GeoJSON")
619
  scag_parcels
620
  return
 
622
 
623
  if __name__ == "__main__":
624
  app.run()
 
 
 
notebooks/sb79-map.py DELETED
@@ -1,77 +0,0 @@
1
- # /// script
2
- # requires-python = ">=3.13"
3
- # dependencies = [
4
- # "auto-mix-prep>=0.2.0",
5
- # "folium>=0.20.0",
6
- # "geopandas>=1.1.3",
7
- # "marimo>=0.23.3",
8
- # ]
9
- # ///
10
-
11
- import marimo
12
-
13
- __generated_with = "0.23.5"
14
- app = marimo.App()
15
-
16
-
17
- @app.cell
18
- def _():
19
- import folium
20
- from folium.plugins import MarkerCluster, VectorGridProtobuf
21
-
22
- from arcgis_paginate import (
23
- fetch_from_arcgis,
24
- )
25
-
26
- PARCELS_URL = "https://vectortileservices3.arcgis.com/NaFf4UaPo3IgQXqn/arcgis/rest/services/sb79_transit_parcels/VectorTileServer/tile/{z}/{y}/{x}.pbf"
27
- STOPS_URL = (
28
- "https://services3.arcgis.com/NaFf4UaPo3IgQXqn/ArcGIS/rest/services/sb79_transit_stations/FeatureServer/0/query"
29
- )
30
- return (
31
- MarkerCluster,
32
- PARCELS_URL,
33
- STOPS_URL,
34
- VectorGridProtobuf,
35
- fetch_from_arcgis,
36
- folium,
37
- )
38
-
39
-
40
- @app.cell
41
- def _(STOPS_URL, fetch_from_arcgis):
42
- stops = fetch_from_arcgis(url=STOPS_URL)
43
- stops
44
- return (stops,)
45
-
46
-
47
- @app.cell
48
- def _(MarkerCluster, PARCELS_URL, VectorGridProtobuf, folium, stops):
49
- m = folium.Map(location=[34.0617140033952, -118.314146442073], tiles="CartoDB Positron", zoom_start=10)
50
-
51
- VectorGridProtobuf(PARCELS_URL, "folium_layer_name").add_to(m)
52
- cluster = MarkerCluster(disable_clustering_at_zoom=10).add_to(m)
53
- for _, _row in stops.iterrows():
54
- color = "blue" if _row["Tier"] == 2 else "red"
55
- cluster.add_child(
56
- folium.CircleMarker(
57
- location=[_row.geometry.y, _row.geometry.x],
58
- radius=5,
59
- tooltip=folium.Tooltip(
60
- f"""
61
- Stop Name: {_row["stop_name"]}<br>
62
- Tier: {_row["Tier"]}<br>
63
- Routes: {_row["route_ids_served"]}<br>
64
- City: {_row["city"]}<br>
65
- County: {_row["county"]}<br>
66
- Route type: {_row["routetypes"]}"""
67
- ),
68
- color=color,
69
- fill_color=color,
70
- ).add_to(m)
71
- )
72
- m
73
- return
74
-
75
-
76
- if __name__ == "__main__":
77
- app.run()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
notebooks/sb79map.py ADDED
@@ -0,0 +1,995 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.13"
3
+ # dependencies = [
4
+ # "auto-mix-prep>=0.2.0",
5
+ # "folium>=0.20.0",
6
+ # "geopandas>=1.1.3",
7
+ # "marimo>=0.23.3",
8
+ # ]
9
+ # ///
10
+
11
+ import marimo
12
+
13
+ __generated_with = "0.23.5"
14
+ app = marimo.App()
15
+
16
+ with app.setup(hide_code=True):
17
+ import csv
18
+ import io
19
+ import json
20
+ import time
21
+ import zipfile
22
+ from collections import defaultdict
23
+ from collections.abc import Generator
24
+ from pathlib import Path
25
+ from typing import Any
26
+
27
+ import geopandas as gpd
28
+ import numpy as np
29
+ import pandas as pd
30
+ import requests
31
+ from shapely import unary_union
32
+ from shapely.geometry import Polygon
33
+
34
+ __generated_with = "0.23.5"
35
+ SCAG_PARCELS_URL = "https://rdp.scag.ca.gov/mapping/rest/services/Housing/2020_Annual_Land_Use/MapServer/0/query"
36
+ CA_PARCELS_URL = (
37
+ "https://services1.arcgis.com/jUJYIo9tSA7EHvfZ/ArcGIS/rest/services/"
38
+ "CA_Statewide_Parcels_Public_view/FeatureServer/0/query"
39
+ )
40
+
41
+ SCAG_OUT_FIELDS = (
42
+ "APN20,COUNTY,CITY,IL_RATIO,ZN19_CITY,ZN19_SCAG,TCAC_2024,"
43
+ "APPAREL1MI,EDUC1MI,GROCERY1MI,HOSPIT1MI,RESTAUR1MI,JOBS_30MIN,YEAR"
44
+ )
45
+
46
+ HALF_MI_M = 804.7 # 0.5 mile in metres
47
+
48
+ # Zone densities (du/ac) by buffer zone and Tier
49
+ ZONE_DENSITIES: dict[tuple[str, int], float] = {
50
+ ("200ft", 1): 160,
51
+ ("200ft", 2): 140,
52
+ ("qtr_mi", 1): 120,
53
+ ("qtr_mi", 2): 100,
54
+ ("half_mi", 1): 100,
55
+ ("half_mi", 2): 80,
56
+ }
57
+
58
+ def shapely_to_esri_json(polygon: Polygon, wkid: int = 3857) -> dict | None:
59
+ """Convert a Shapely polygon to an ESRI JSON geometry object."""
60
+ if not polygon or polygon.is_empty:
61
+ return None
62
+ coords = list(polygon.exterior.coords)
63
+ rings = [[[x, y] for x, y in coords]]
64
+ return {"rings": rings, "spatialReference": {"wkid": wkid}}
65
+
66
+ def paginate_arcgis(
67
+ url: str,
68
+ geometry: str = None,
69
+ geometry_type: str = "esriGeometryPolygon",
70
+ spatial_rel: str = "esriSpatialRelIntersects",
71
+ in_sr: int = 3310,
72
+ out_fields: str = "*",
73
+ return_geometry: str = "true",
74
+ f: str = "geojson",
75
+ where: str = "1=1",
76
+ max_record_count: int = 2000,
77
+ delay: float = 0,
78
+ ) -> Generator[gpd.GeoDataFrame, None, None]:
79
+ """Paginate through an ArcGIS REST API query and yield GeoDataFrames."""
80
+ offset = 0
81
+ while True:
82
+ params = {
83
+ "geometry": geometry,
84
+ "geometryType": geometry_type,
85
+ "spatialRel": spatial_rel,
86
+ "inSR": str(in_sr),
87
+ "outFields": out_fields,
88
+ "returnGeometry": return_geometry,
89
+ "f": f,
90
+ "where": where,
91
+ "resultOffset": str(offset),
92
+ "resultRecordCount": str(max_record_count),
93
+ }
94
+ resp = requests.get(url, params=params)
95
+ resp.raise_for_status()
96
+ data = resp.json()
97
+ features = data.get("features", [])
98
+ if not features:
99
+ break
100
+ page = gpd.GeoDataFrame.from_features(features)
101
+ yield page
102
+ offset += max_record_count
103
+ time.sleep(delay)
104
+ if not data.get("properties", {}).get("exceededTransferLimit", False):
105
+ break
106
+
107
+ def fetch_from_arcgis(
108
+ url: str,
109
+ geometries: list[Polygon] = None,
110
+ out_fields: str = "*",
111
+ wkid: int = 3310,
112
+ max_record_count: int = 2000,
113
+ delay: float = 0,
114
+ ) -> gpd.GeoDataFrame:
115
+ """Query an ArcGIS parcel endpoint for multiple geometries and concatenate results."""
116
+ if geometries is None:
117
+ geometries = [None]
118
+ all_geometries: list[gpd.GeoDataFrame] = []
119
+ for geom in geometries:
120
+ esri_geom = shapely_to_esri_json(geom, wkid=wkid)
121
+ geometry_json = json.dumps(esri_geom) if esri_geom else None
122
+ for page in paginate_arcgis(
123
+ url=url,
124
+ geometry=geometry_json,
125
+ geometry_type="esriGeometryPolygon",
126
+ spatial_rel="esriSpatialRelIntersects",
127
+ in_sr=wkid,
128
+ out_fields=out_fields,
129
+ return_geometry="true",
130
+ f="geojson",
131
+ where="1=1",
132
+ max_record_count=max_record_count,
133
+ delay=delay,
134
+ ):
135
+ all_geometries.append(page)
136
+ if not all_geometries:
137
+ return gpd.GeoDataFrame()
138
+ return gpd.GeoDataFrame(pd.concat(all_geometries, ignore_index=True))
139
+
140
+ def parse_gtfs_zip(
141
+ gtfs_path: str | Path,
142
+ tier_overrides: dict[str, int] | None = None,
143
+ ) -> gpd.GeoDataFrame:
144
+ """Parse a GTFS zip and return a GeoDataFrame of Tier-1/Tier-2 parent stations.
145
+
146
+ Parameters
147
+ ----------
148
+ gtfs_path:
149
+ Path to a ``.zip`` file containing standard GTFS tables.
150
+ tier_overrides:
151
+ Optional mapping ``{route_id: tier}`` to force a specific tier for
152
+ a route regardless of the automatic logic.
153
+
154
+ Returns
155
+ -------
156
+ gpd.GeoDataFrame
157
+ Only stops that qualify as Tier 1 or Tier 2 are returned.
158
+ """
159
+ z = zipfile.ZipFile(gtfs_path)
160
+
161
+ routes = list(csv.DictReader(io.StringIO(z.read("routes.txt").decode("utf-8"))))
162
+ route_info: dict[str, dict[str, Any]] = {}
163
+ for r in routes:
164
+ route_info[r["route_id"]] = r
165
+
166
+ cal = list(csv.DictReader(io.StringIO(z.read("calendar.txt").decode("utf-8"))))
167
+ weekday_services = {c["service_id"] for c in cal if c["monday"] == "1"}
168
+
169
+ trips = list(csv.DictReader(io.StringIO(z.read("trips.txt").decode("utf-8"))))
170
+ trip_to_route: dict[str, str] = {}
171
+ route_dir_counts: dict[str, dict[str, int]] = defaultdict(lambda: {"0": 0, "1": 0})
172
+ for t in trips:
173
+ trip_to_route[t["trip_id"]] = t["route_id"]
174
+ if t["service_id"] in weekday_services:
175
+ route_dir_counts[t["route_id"]][t["direction_id"]] += 1
176
+
177
+ num_wkday = len(weekday_services)
178
+
179
+ route_trains_per_day: dict[str, int] = {}
180
+ for rid, dirs in route_dir_counts.items():
181
+ route_trains_per_day[rid] = round((dirs.get("0", 0) + dirs.get("1", 0)) / num_wkday)
182
+
183
+ stops = list(csv.DictReader(io.StringIO(z.read("stops.txt").decode("utf-8"))))
184
+ stops_df = pd.DataFrame(stops)
185
+
186
+ parent_stations = stops_df[stops_df["location_type"] == "1"].copy()
187
+ boarding_stops = stops_df[stops_df["location_type"] == "0"].copy()
188
+
189
+ stop_times = list(csv.DictReader(io.StringIO(z.read("stop_times.txt").decode("utf-8"))))
190
+ stop_to_routes: dict[str, set[str]] = defaultdict(set)
191
+ for st in stop_times:
192
+ rid = trip_to_route.get(st["trip_id"])
193
+ if rid:
194
+ stop_to_routes[st["stop_id"]].add(rid)
195
+
196
+ parent_to_routes: dict[str, set[str]] = defaultdict(set)
197
+ for _, bs in boarding_stops.iterrows():
198
+ parent = bs["parent_station"]
199
+ if parent and parent in set(parent_stations["stop_id"]):
200
+ parent_to_routes[parent].update(stop_to_routes.get(bs["stop_id"], set()))
201
+
202
+ for _, ps in parent_stations.iterrows():
203
+ parent_to_routes[ps["stop_id"]].update(stop_to_routes.get(ps["stop_id"], set()))
204
+
205
+ # --- Build the output GeoDataFrame ---
206
+ records: list[dict[str, Any]] = []
207
+ for _, ps in parent_stations.iterrows():
208
+ pid = ps["stop_id"]
209
+ served_routes = sorted(parent_to_routes.get(pid, set()))
210
+ if not served_routes:
211
+ continue
212
+
213
+ # Collect route types and count arrivals
214
+ types: set[str] = set()
215
+ total_arrivals = 0
216
+ agencies: set[str] = set()
217
+ for rid in served_routes:
218
+ ri = route_info.get(rid, {})
219
+ types.add(ri.get("route_type", ""))
220
+ total_arrivals += route_trains_per_day.get(rid, 0)
221
+ agencies.add(ri.get("agency_id", ""))
222
+
223
+ routetypes_str = ",".join(sorted(types, key=int))
224
+
225
+ # Tier assignment
226
+ has_type_1 = "1" in types
227
+ has_type_0 = "0" in types
228
+ has_type_2 = "2" in types
229
+
230
+ tier: int | None = None
231
+ if has_type_1:
232
+ tier = 1
233
+ elif (has_type_0 or has_type_2) and total_arrivals >= 72:
234
+ tier = 1
235
+ elif has_type_2 and 48 <= total_arrivals < 72:
236
+ tier = 2
237
+ elif has_type_0 and total_arrivals < 72:
238
+ tier = 2
239
+
240
+ # Apply overrides
241
+ if tier_overrides:
242
+ for rid in served_routes:
243
+ if rid in tier_overrides:
244
+ tier = tier_overrides[rid]
245
+ break
246
+
247
+ if tier is None:
248
+ continue # skip stops that don't qualify
249
+
250
+ records.append(
251
+ {
252
+ "stop_id": pid,
253
+ "stop_name": ps.get("stop_name", ""),
254
+ "stop_lat": float(ps["stop_lat"]),
255
+ "stop_lon": float(ps["stop_lon"]),
256
+ "Tier": tier,
257
+ "agency": ",".join(sorted(agencies)),
258
+ "route_ids_served": ",".join(served_routes),
259
+ "routetypes": routetypes_str,
260
+ "n_arrivals": total_arrivals,
261
+ }
262
+ )
263
+
264
+ if not records:
265
+ return gpd.GeoDataFrame(
266
+ {
267
+ "stop_id": pd.Series(dtype=str),
268
+ "stop_name": pd.Series(dtype=str),
269
+ "Tier": pd.Series(dtype=int),
270
+ "agency": pd.Series(dtype=str),
271
+ "route_ids_served": pd.Series(dtype=str),
272
+ "routetypes": pd.Series(dtype=str),
273
+ "n_arrivals": pd.Series(dtype=int),
274
+ },
275
+ geometry=pd.Series(dtype=object),
276
+ crs="EPSG:4326",
277
+ )
278
+
279
+ result = gpd.GeoDataFrame(
280
+ records,
281
+ geometry=gpd.points_from_xy(
282
+ [r["stop_lon"] for r in records],
283
+ [r["stop_lat"] for r in records],
284
+ crs="EPSG:4326",
285
+ ),
286
+ )
287
+ result.drop(columns=["stop_lat", "stop_lon"], inplace=True)
288
+ return result
289
+
290
+ def create_half_mi_buffers(stops_gdf: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
291
+ """Create 0.5-mile (804.7 m) circular buffers around each stop.
292
+
293
+ Returns a GeoDataFrame in EPSG:3310 with the same ``stop_id`` index.
294
+ """
295
+ buffers = gpd.GeoDataFrame(
296
+ {"stop_id": stops_gdf["stop_id"].values},
297
+ geometry=stops_gdf.to_crs("EPSG:3310").geometry.buffer(HALF_MI_M, resolution=8),
298
+ crs="EPSG:3310",
299
+ )
300
+ return buffers
301
+
302
+ def fetch_scag_parcels(
303
+ buffers_gdf: gpd.GeoDataFrame,
304
+ url: str = SCAG_PARCELS_URL,
305
+ out_fields: str = SCAG_OUT_FIELDS,
306
+ wkid: int = 3310,
307
+ max_record_count: int = 2000,
308
+ delay: float = 0.1,
309
+ ) -> gpd.GeoDataFrame:
310
+ """Query the SCAG parcel endpoint for all parcels intersecting the buffers.
311
+
312
+ Returns a GeoDataFrame in EPSG:3310.
313
+ """
314
+ parcels = fetch_from_arcgis(
315
+ url=url,
316
+ geometries=buffers_gdf.geometry.tolist(),
317
+ out_fields=out_fields,
318
+ wkid=wkid,
319
+ max_record_count=max_record_count,
320
+ delay=delay,
321
+ )
322
+ if parcels.empty:
323
+ return parcels
324
+ return parcels.set_crs("EPSG:4326").to_crs(f"EPSG:{wkid}")
325
+
326
+ def fetch_ca_parcels(
327
+ buffers_gdf: gpd.GeoDataFrame,
328
+ url: str = CA_PARCELS_URL,
329
+ wkid: int = 3310,
330
+ max_record_count: int = 2000,
331
+ delay: float = 0.1,
332
+ ) -> gpd.GeoDataFrame:
333
+ """Query the CA statewide parcel endpoint for all parcels intersecting the buffers.
334
+
335
+ Returns a GeoDataFrame in EPSG:3310, deduplicated by ``PARCEL_APN``.
336
+ """
337
+ parcels = fetch_from_arcgis(
338
+ url=url,
339
+ geometries=buffers_gdf.geometry.tolist(),
340
+ out_fields="*",
341
+ wkid=wkid,
342
+ max_record_count=max_record_count,
343
+ delay=delay,
344
+ )
345
+ if parcels.empty:
346
+ return parcels
347
+ parcels = parcels.set_crs("EPSG:4326").to_crs(f"EPSG:{wkid}")
348
+
349
+ # Deduplicate by APN
350
+ if "PARCEL_APN" in parcels.columns:
351
+ before = len(parcels)
352
+ parcels = parcels.groupby("PARCEL_APN", as_index=False).first()
353
+ print(f"CA parcels: {before} → {len(parcels)} after APN dedup")
354
+ return parcels
355
+
356
+ def compute_scag_density(scag_parcels: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
357
+ """Add ``current_density_du_per_ac`` to SCAG parcels using LA / non-LA logic.
358
+
359
+ Parameters
360
+ ----------
361
+ scag_parcels:
362
+ Must have columns ``ZN19_CITY``, ``ZN19_SCAG``, ``CITY``, and a valid
363
+ geometry for area calculations.
364
+
365
+ Returns
366
+ -------
367
+ gpd.GeoDataFrame
368
+ Same as input with an added ``current_density_du_per_ac`` column.
369
+ """
370
+ df = scag_parcels.copy()
371
+
372
+ # LA density: map ZN19_CITY zone codes → du/ac
373
+ la_density = df["ZN19_CITY"].case_when(
374
+ [
375
+ (df["ZN19_CITY"].str.contains("RD1.5", na=False), 43560 / 1500),
376
+ (df["ZN19_CITY"].str.contains("RD2", na=False), 43560 / 2000),
377
+ (df["ZN19_CITY"].str.contains("RD3", na=False), 43560 / 3000),
378
+ (df["ZN19_CITY"].str.contains("RD4", na=False), 43560 / 4000),
379
+ (df["ZN19_CITY"].str.contains("RD5", na=False), 43560 / 5000),
380
+ (df["ZN19_CITY"].str.contains("RD6", na=False), 43560 / 6000),
381
+ (df["ZN19_CITY"].str.contains("RMP", na=False), 43560 / 20000),
382
+ (df["ZN19_CITY"].str.contains("R3", na=False), 43560 / 800),
383
+ (df["ZN19_CITY"].str.contains("RAS3", na=False), 43560 / 800),
384
+ (df["ZN19_CITY"].str.contains("R4", na=False), 43560 / 400),
385
+ (df["ZN19_CITY"].str.contains("RAS4", na=False), 43560 / 400),
386
+ (df["ZN19_CITY"].str.contains("R5", na=False), 43560 / 200),
387
+ (df["ZN19_CITY"].str.contains("RE40", na=False), 43560 / 40000),
388
+ (df["ZN19_CITY"].str.contains("RE20", na=False), 43560 / 20000),
389
+ (df["ZN19_CITY"].str.contains("RE15", na=False), 43560 / 15000),
390
+ (df["ZN19_CITY"].str.contains("RE11", na=False), 43560 / 11000),
391
+ (df["ZN19_CITY"].str.contains("RE9", na=False), 43560 / 9000),
392
+ (df["ZN19_CITY"].str.contains("RS", na=False), 43560 / 7500),
393
+ (df["ZN19_CITY"].str.contains("R1", na=False), 43560 / 5000),
394
+ (df["ZN19_CITY"].str.contains("RU", na=False), 43560 / 3500),
395
+ (df["ZN19_CITY"].str.contains("RZ2.5", na=False), 43560 / 2500),
396
+ (df["ZN19_CITY"].str.contains("RZ3", na=False), 43560 / 3000),
397
+ (df["ZN19_CITY"].str.contains("RZ4", na=False), 43560 / 4000),
398
+ (df["ZN19_CITY"].str.contains("RW1", na=False), 43560 / 2300),
399
+ (df["ZN19_CITY"].str.contains("R2", na=False), 43560 / 2500),
400
+ (df["ZN19_CITY"].str.contains("RW2", na=False), 43560 / 1150),
401
+ (df["ZN19_CITY"] != "Los Angeles", 0),
402
+ ]
403
+ )
404
+
405
+ # Non-LA density: map ZN19_SCAG codes → du/ac
406
+ area_acres = df.to_crs("EPSG:2229").area / 43560
407
+ non_la_density = df["ZN19_SCAG"].case_when(
408
+ [
409
+ (df["ZN19_SCAG"] == 1111, 10),
410
+ (df["ZN19_SCAG"] == 1112, 8),
411
+ (df["ZN19_SCAG"] == 1113, 2),
412
+ (df["ZN19_SCAG"] == 1121, 3 / area_acres.replace(0, np.nan)),
413
+ (df["ZN19_SCAG"] == 1122, 3 / area_acres.replace(0, np.nan)),
414
+ (df["ZN19_SCAG"] == 1140, 3 / area_acres.replace(0, np.nan)),
415
+ (df["ZN19_SCAG"] == 1123, 18),
416
+ (df["ZN19_SCAG"] == 1124, 60),
417
+ (df["ZN19_SCAG"] == 1125, 80),
418
+ (df["ZN19_SCAG"] == 1131, 6),
419
+ (df["ZN19_SCAG"] == 1150, 1),
420
+ (df["ZN19_SCAG"] != 0, 0),
421
+ ]
422
+ )
423
+
424
+ df["current_density_du_per_ac"] = np.where(
425
+ df["CITY"] == "Los Angeles",
426
+ la_density,
427
+ non_la_density,
428
+ )
429
+ return df
430
+
431
+ def trim_around_stations(
432
+ parcels_gdf: gpd.GeoDataFrame,
433
+ stops_gdf: gpd.GeoDataFrame,
434
+ buffer_dist_ft: int,
435
+ ) -> gpd.GeoDataFrame:
436
+ """Buffer stops by ``buffer_dist_ft`` and trim parcels to the buffer.
437
+
438
+ Parameters
439
+ ----------
440
+ parcels_gdf:
441
+ Parcels with ``current_density_du_per_ac`` and ``Tier`` columns.
442
+ stops_gdf:
443
+ Stops with ``stop_id``, ``Tier``, and geometry.
444
+ buffer_dist_ft:
445
+ Buffer distance in feet (e.g. 200, 1320, 2640).
446
+
447
+ Returns
448
+ -------
449
+ gpd.GeoDataFrame
450
+ Parcel pieces clipped to the buffer, with ``buffer_zone_id`` set to
451
+ ``"200ft"``, ``"qtr_mi"``, or ``"half_mi"`` depending on the distance.
452
+ """
453
+ # Map distance to zone name
454
+ zone_map = {200: "200ft", 1320: "qtr_mi", 2640: "half_mi"}
455
+ zone_name = zone_map.get(buffer_dist_ft, f"{buffer_dist_ft}ft")
456
+
457
+ # Buffer stops in feet (EPSG:2229)
458
+ buffer_df = gpd.GeoDataFrame(
459
+ {"stop_id": stops_gdf["stop_id"].values, "Tier": stops_gdf["Tier"].values},
460
+ geometry=stops_gdf.to_crs("EPSG:2229").geometry.buffer(buffer_dist_ft),
461
+ crs="EPSG:2229",
462
+ )
463
+
464
+ # Spatial join: parcels intersecting buffers
465
+ parcels_4326 = parcels_gdf.to_crs("EPSG:4326")
466
+ buffer_4326 = buffer_df.to_crs("EPSG:4326")
467
+ joined = gpd.sjoin(
468
+ parcels_4326,
469
+ buffer_4326[["stop_id", "Tier", "geometry"]],
470
+ how="inner",
471
+ predicate="intersects",
472
+ rsuffix="_stop",
473
+ )
474
+
475
+ # Clip to buffer boundary
476
+ trimmed = gpd.overlay(joined, buffer_4326, how="intersection")
477
+ trimmed["buffer_zone_id"] = zone_name
478
+ return trimmed
479
+
480
+ def create_buffer_donuts(
481
+ stops_gdf: gpd.GeoDataFrame,
482
+ scag_density: gpd.GeoDataFrame,
483
+ ) -> gpd.GeoDataFrame:
484
+ """Create 200ft / ¼mi / ½mi donut zones and compute weighted density per parcel.
485
+
486
+ Steps
487
+ -----
488
+ 1. ``trim_around_stations`` for 200 ft, 1320 ft, 2640 ft.
489
+ 2. Create donuts: ¼mi \\ 200ft, ½mi \\ ¼mi.
490
+ 3. Concat all three zones.
491
+ 4. Assign zone density by ``(buffer_zone_id, Tier)``.
492
+ 5. Group by ``APN20`` → weighted ``new_density_du_per_ac``,
493
+ ``dwelling_units_new``, ``dwelling_units_current``.
494
+
495
+ Returns
496
+ -------
497
+ gpd.GeoDataFrame
498
+ One row per APN20 with columns: ``APN20``, ``geometry``, ``area_acres``,
499
+ ``new_density_du_per_ac``, ``dwelling_units_new``,
500
+ ``dwelling_units_current``, ``current_density_du_per_ac``, ``Tier``,
501
+ ``ZN19_CITY``, ``ZN19_SCAG``, ``COUNTY``, ``CITY``.
502
+ """
503
+ # --- 1. Trim for each buffer distance ---
504
+ trim_200 = trim_around_stations(scag_density, stops_gdf, 200)
505
+ trim_qtr = trim_around_stations(scag_density, stops_gdf, 1320)
506
+ trim_half = trim_around_stations(scag_density, stops_gdf, 2640)
507
+
508
+ # --- 2. Create donuts ---
509
+ # ¼mi buffer in EPSG:4326 for overlay
510
+ buffer_qtr_4326 = gpd.GeoDataFrame(
511
+ {"stop_id": stops_gdf["stop_id"].values},
512
+ geometry=stops_gdf.to_crs("EPSG:2229").geometry.buffer(1320).to_crs("EPSG:4326"),
513
+ crs="EPSG:4326",
514
+ )
515
+
516
+ buffer_200_4326 = gpd.GeoDataFrame(
517
+ {"stop_id": stops_gdf["stop_id"].values},
518
+ geometry=stops_gdf.to_crs("EPSG:2229").geometry.buffer(200).to_crs("EPSG:4326"),
519
+ crs="EPSG:4326",
520
+ )
521
+
522
+ qtrmile_donut = gpd.overlay(trim_qtr, buffer_200_4326, how="difference")
523
+ halfmile_donut = gpd.overlay(trim_half, buffer_qtr_4326, how="difference")
524
+
525
+ qtrmile_donut["buffer_zone_id"] = "qtr_mi"
526
+ halfmile_donut["buffer_zone_id"] = "half_mi"
527
+
528
+ # --- 3. Concat ---
529
+ residential = gpd.GeoDataFrame(pd.concat([trim_200, qtrmile_donut, halfmile_donut], ignore_index=True))
530
+
531
+ # --- 4. Area in sq ft ---
532
+ residential["area_sqft"] = residential.to_crs("EPSG:2229").area
533
+
534
+ # --- 5. Assign zone density ---
535
+ zone_densities_series = pd.Series(ZONE_DENSITIES)
536
+ residential["zone_density"] = residential.set_index(["buffer_zone_id", "Tier"]).index.map(zone_densities_series)
537
+
538
+ # --- 6. Aggregate by APN20 ---
539
+ def _aggregate_parcel(group: pd.DataFrame) -> pd.Series:
540
+ apn = group.name
541
+ total_area = group["area_sqft"].sum()
542
+ total_area_acres = total_area / 43560
543
+
544
+ weighted_density = (group["area_sqft"] * group["zone_density"]).sum() / total_area if total_area > 0 else 0.0
545
+
546
+ unioned_geom = unary_union(group.geometry.tolist())
547
+ first = group.iloc[0]
548
+
549
+ return pd.Series(
550
+ {
551
+ "APN20": apn,
552
+ "geometry": unioned_geom,
553
+ "area_acres": total_area_acres,
554
+ "new_density_du_per_ac": weighted_density,
555
+ "dwelling_units_new": weighted_density * total_area_acres,
556
+ "dwelling_units_current": first["current_density_du_per_ac"] * total_area_acres,
557
+ "current_density_du_per_ac": first["current_density_du_per_ac"],
558
+ "Tier": first["Tier"],
559
+ "ZN19_CITY": first.get("ZN19_CITY", ""),
560
+ "ZN19_SCAG": first.get("ZN19_SCAG", ""),
561
+ "COUNTY": first.get("COUNTY", ""),
562
+ "CITY": first.get("CITY", ""),
563
+ }
564
+ )
565
+
566
+ by_apn = (
567
+ residential.groupby("APN20", as_index=True).apply(_aggregate_parcel, include_groups=False).reset_index(drop=True)
568
+ )
569
+
570
+ result = gpd.GeoDataFrame(by_apn, geometry="geometry", crs=residential.crs)
571
+ print(f"Before APN dedup: {len(residential)} rows")
572
+ print(f"After APN dedup: {len(result)} rows")
573
+ print(f"Total dwelling units (new): {result['dwelling_units_new'].sum():.0f}")
574
+ return result
575
+
576
+ def join_scag_ca_parcels(
577
+ scag_by_apn: gpd.GeoDataFrame,
578
+ ca_parcels: gpd.GeoDataFrame,
579
+ ) -> gpd.GeoDataFrame:
580
+ """Outer-join SCAG zoning data onto CA parcels by APN.
581
+
582
+ Returns a GeoDataFrame with combined geometry, city, county, and APN.
583
+ Columns are renamed: ``current_density_du_per_ac`` → ``current_density``,
584
+ ``new_density_du_per_ac`` → ``new_density``.
585
+ """
586
+ scag_cols = [
587
+ "APN20",
588
+ "current_density_du_per_ac",
589
+ "new_density_du_per_ac",
590
+ "dwelling_units_new",
591
+ "dwelling_units_current",
592
+ "ZN19_CITY",
593
+ "ZN19_SCAG",
594
+ "area_acres",
595
+ "CITY",
596
+ "COUNTY",
597
+ "Tier",
598
+ "geometry",
599
+ ]
600
+ existing = [c for c in scag_cols if c in scag_by_apn.columns]
601
+
602
+ merged = ca_parcels.merge(
603
+ scag_by_apn[existing],
604
+ left_on="PARCEL_APN",
605
+ right_on="APN20",
606
+ how="outer",
607
+ suffixes=("_ca", "_scag"),
608
+ )
609
+
610
+ matched = merged["APN20"].notna().sum()
611
+ print(f"CA parcels: {len(ca_parcels)}")
612
+ print(f"Matched with SCAG zoning: {matched} ({matched / len(ca_parcels) * 100:.1f}%)" if len(ca_parcels) else "")
613
+
614
+ # Combine geometries
615
+ geom_cols = [c for c in merged.columns if c.startswith("geometry")]
616
+ if geom_cols:
617
+ merged["geometry"] = merged[geom_cols[0]]
618
+ for c in geom_cols[1:]:
619
+ merged["geometry"] = merged["geometry"].combine_first(merged[c])
620
+
621
+ # Combine city / county / apn
622
+ merged["city"] = merged.get("SITE_CITY", pd.Series(dtype=str)).combine_first(
623
+ merged.get("CITY", pd.Series(dtype=str)).str.upper()
624
+ )
625
+ merged["county"] = merged.get("COUNTYNAME", pd.Series(dtype=str)).combine_first(
626
+ merged.get("COUNTY", pd.Series(dtype=str)).str.upper()
627
+ )
628
+ merged["apn"] = merged["PARCEL_APN"].combine_first(merged["APN20"])
629
+
630
+ # Rename density columns
631
+ merged.rename(
632
+ columns={
633
+ "current_density_du_per_ac": "current_density",
634
+ "new_density_du_per_ac": "new_density",
635
+ },
636
+ inplace=True,
637
+ )
638
+
639
+ return gpd.GeoDataFrame(merged, geometry="geometry", crs=ca_parcels.crs)
640
+
641
+ def assign_nearest_stop(
642
+ parcels_gdf: gpd.GeoDataFrame,
643
+ stops_gdf: gpd.GeoDataFrame,
644
+ buffers_gdf: gpd.GeoDataFrame,
645
+ ) -> gpd.GeoDataFrame:
646
+ """Spatially join parcels to stop buffers, then deduplicate multi-buffer parcels
647
+ by assigning the nearest stop (by centroid distance).
648
+
649
+ Parcels are clipped to their assigned buffer so only the intersecting
650
+ portion is counted.
651
+
652
+ Returns
653
+ -------
654
+ gpd.GeoDataFrame
655
+ One row per ``(stop_id, APN)`` with a ``clipped_geom`` column.
656
+ """
657
+ # Spatial join: parcels → buffers
658
+ parcels_3310 = parcels_gdf.to_crs("EPSG:3310")
659
+ buffers_3310 = buffers_gdf.to_crs("EPSG:3310")
660
+
661
+ joined = gpd.sjoin(
662
+ parcels_3310,
663
+ buffers_3310[["stop_id", "geometry"]],
664
+ how="left",
665
+ predicate="intersects",
666
+ )
667
+
668
+ # Identify parcels intersecting multiple stops
669
+ multi = joined.groupby(joined.index).size()
670
+ multi_ids = multi[multi > 1].index
671
+
672
+ # Deduplicate: keep first stop_id as fallback
673
+ deduped = joined[~joined.index.duplicated(keep="first")].copy()
674
+
675
+ if len(multi_ids) > 0:
676
+ # For multi-buffer parcels, find nearest stop
677
+ multi_parcels = joined.loc[multi_ids, ["stop_id"]]
678
+ multi_exploded = multi_parcels.explode("stop_id").reset_index()
679
+ multi_exploded.columns = ["parcel_idx", "stop_id"]
680
+
681
+ stop_points_3310 = stops_gdf.set_index("stop_id").to_crs("EPSG:3310").geometry
682
+ parcel_centroids = parcels_3310.geometry.centroid
683
+
684
+ multi_exploded["distance"] = multi_exploded.apply(
685
+ lambda r: parcel_centroids.iloc[r["parcel_idx"]].distance(stop_points_3310[r["stop_id"]]),
686
+ axis=1,
687
+ )
688
+
689
+ nearest = multi_exploded.loc[
690
+ multi_exploded.groupby("parcel_idx")["distance"].idxmin(),
691
+ ["parcel_idx", "stop_id"],
692
+ ]
693
+ nearest = nearest.set_index("parcel_idx")["stop_id"]
694
+ deduped.loc[nearest.index, "stop_id"] = nearest
695
+
696
+ # Clip parcels to assigned buffer
697
+ buffer_indexed = buffers_3310.set_index("stop_id")[["geometry"]]
698
+ deduped["buffer_geom"] = deduped["stop_id"].map(buffer_indexed["geometry"])
699
+ deduped["clipped_geom"] = deduped.geometry.intersection(deduped["buffer_geom"])
700
+
701
+ # Deduplicate by (stop_id, APN)
702
+ apn_col = "PARCEL_APN" if "PARCEL_APN" in deduped.columns else "APN20"
703
+ deduped = deduped.groupby(["stop_id", apn_col], as_index=False).first()
704
+
705
+ return deduped
706
+
707
+ def aggregate_parcels_to_stops(
708
+ parcels_with_stops: gpd.GeoDataFrame,
709
+ stops_gdf: gpd.GeoDataFrame,
710
+ ) -> gpd.GeoDataFrame:
711
+ """Sum parcel area and dwelling units per stop.
712
+
713
+ For each stop:
714
+ * ``parcel_acres`` — total clipped parcel area (using ``unary_union`` to
715
+ avoid double-counting overlapping geometries).
716
+ * ``additional_dwelling_units`` — sum of ``max(0, dwelling_units_new -
717
+ dwelling_units_current)`` across parcels where new > current.
718
+ * ``city``, ``county`` — mode (most common value) from associated parcels.
719
+
720
+ Returns
721
+ -------
722
+ gpd.GeoDataFrame
723
+ Stops with added columns ``parcel_acres``, ``additional_dwelling_units``,
724
+ ``city``, ``county``.
725
+ """
726
+ # Parcel area per stop
727
+ area_per_stop = (
728
+ parcels_with_stops.groupby("stop_id")["clipped_geom"]
729
+ .apply(lambda g: unary_union(g.tolist()).area / 4046.86)
730
+ .reset_index()
731
+ )
732
+ area_per_stop.columns = ["stop_id", "parcel_acres"]
733
+
734
+ # Additional dwelling units per stop (only where new > current)
735
+ parcels_with_stops["additional_du"] = np.maximum(
736
+ 0,
737
+ parcels_with_stops.get("dwelling_units_new", 0) - parcels_with_stops.get("dwelling_units_current", 0),
738
+ )
739
+ du_per_stop = (
740
+ parcels_with_stops.groupby("stop_id")["additional_du"]
741
+ .sum()
742
+ .reset_index()
743
+ .rename(columns={"additional_du": "additional_dwelling_units"})
744
+ )
745
+
746
+ # City / county from parcels (mode per stop)
747
+ def _mode(series: pd.Series) -> str:
748
+ return series.mode().iloc[0] if not series.mode().empty else ""
749
+
750
+ city_per_stop = (
751
+ parcels_with_stops.groupby("stop_id")["city"].agg(_mode).reset_index().rename(columns={"city": "city"})
752
+ )
753
+ county_per_stop = (
754
+ parcels_with_stops.groupby("stop_id")["county"].agg(_mode).reset_index().rename(columns={"county": "county"})
755
+ )
756
+
757
+ # Merge back to stops
758
+ result = stops_gdf.merge(area_per_stop, on="stop_id", how="left").fillna({"parcel_acres": 0})
759
+ result = result.merge(du_per_stop, on="stop_id", how="left").fillna({"additional_dwelling_units": 0})
760
+ result = result.merge(city_per_stop, on="stop_id", how="left").fillna({"city": ""})
761
+ result = result.merge(county_per_stop, on="stop_id", how="left").fillna({"county": ""})
762
+
763
+ return result
764
+
765
+ def full_pipeline(
766
+ gtfs_zip_path: str | Path,
767
+ tier_overrides: dict[str, int] | None = None,
768
+ out_path: str | Path | None = None,
769
+ scag_url: str = SCAG_PARCELS_URL,
770
+ ca_url: str = CA_PARCELS_URL,
771
+ scag_out_fields: str = SCAG_OUT_FIELDS,
772
+ ) -> dict[str, gpd.GeoDataFrame]:
773
+ """Run the complete GTFS-to-parcels pipeline.
774
+
775
+ Parameters
776
+ ----------
777
+ gtfs_zip_path:
778
+ Path to a GTFS ``.zip`` file.
779
+ tier_overrides:
780
+ Optional ``{route_id: tier}`` overrides.
781
+ out_path:
782
+ If provided, save stops and parcels to GeoJSON files here.
783
+ scag_url:
784
+ SCAG parcel endpoint URL.
785
+ ca_url:
786
+ CA statewide parcel endpoint URL.
787
+ scag_out_fields:
788
+ Fields to request from the SCAG endpoint.
789
+
790
+ Returns
791
+ -------
792
+ dict
793
+ ``{"stops": stops_gdf, "parcels": ca_parcels_output}``
794
+ """
795
+ print("=== Step 1: Parse GTFS ===")
796
+ stops = parse_gtfs_zip(gtfs_zip_path, tier_overrides=tier_overrides)
797
+ print(f" {len(stops)} stops with Tier 1 or 2")
798
+
799
+ print("=== Step 2: Create 0.5-mi buffers ===")
800
+ buffers = create_half_mi_buffers(stops)
801
+
802
+ print("=== Step 3: Fetch SCAG parcels ===")
803
+ scag = fetch_scag_parcels(buffers, url=scag_url, out_fields=scag_out_fields)
804
+ print(f" {len(scag)} SCAG parcels")
805
+
806
+ print("=== Step 4: Compute SCAG density ===")
807
+ scag_density = compute_scag_density(scag)
808
+
809
+ print("=== Step 5: Create buffer donuts & weighted density ===")
810
+ scag_by_apn = create_buffer_donuts(stops, scag_density)
811
+
812
+ print("=== Step 6: Fetch CA parcels ===")
813
+ ca = fetch_ca_parcels(buffers, url=ca_url)
814
+ print(f" {len(ca)} CA parcels")
815
+
816
+ print("=== Step 7: Join SCAG → CA parcels ===")
817
+ combined = join_scag_ca_parcels(scag_by_apn, ca)
818
+
819
+ print("=== Step 8: Trim to 0.5-mi buffer & assign nearest stop ===")
820
+ parcels_with_stops = assign_nearest_stop(combined, stops, buffers)
821
+
822
+ print("=== Step 9: Aggregate parcels to stops ===")
823
+ stops_result = aggregate_parcels_to_stops(parcels_with_stops, stops)
824
+
825
+ result = {"stops": stops_result, "parcels": combined}
826
+
827
+ if out_path:
828
+ out = Path(out_path)
829
+ out.mkdir(parents=True, exist_ok=True)
830
+ stops_result.to_file(out / "stops.geojson", driver="GeoJSON")
831
+ combined.to_file(out / "parcels.geojson", driver="GeoJSON")
832
+ print(f" Saved to {out}")
833
+
834
+ return result
835
+
836
+
837
+ @app.cell
838
+ def _():
839
+ from typing import Optional
840
+
841
+ import folium
842
+ import marimo as mo
843
+ from folium.plugins import MarkerCluster, VectorGridProtobuf
844
+
845
+ PARCELS_URL = "https://vectortileservices3.arcgis.com/NaFf4UaPo3IgQXqn/arcgis/rest/services/sb79_transit_parcels/VectorTileServer/tile/{z}/{y}/{x}.pbf"
846
+ STOPS_URL = (
847
+ "https://services3.arcgis.com/NaFf4UaPo3IgQXqn/ArcGIS/rest/services/sb79_transit_stations/FeatureServer/0/query"
848
+ )
849
+ return (
850
+ MarkerCluster,
851
+ Optional,
852
+ PARCELS_URL,
853
+ STOPS_URL,
854
+ VectorGridProtobuf,
855
+ folium,
856
+ mo,
857
+ )
858
+
859
+
860
+ @app.cell
861
+ def _(STOPS_URL):
862
+ stops = fetch_from_arcgis(url=STOPS_URL)
863
+ stops
864
+ return (stops,)
865
+
866
+
867
+ @app.cell
868
+ def _(MarkerCluster, PARCELS_URL, VectorGridProtobuf, folium, stops):
869
+ m = folium.Map(location=[34.0617140033952, -118.314146442073], tiles="CartoDB Positron", zoom_start=10)
870
+
871
+ VectorGridProtobuf(PARCELS_URL, "folium_layer_name").add_to(m)
872
+ cluster = MarkerCluster(disable_clustering_at_zoom=10).add_to(m)
873
+ for _, _row in stops.iterrows():
874
+ color = "blue" if _row["Tier"] == 2 else "red"
875
+ cluster.add_child(
876
+ folium.CircleMarker(
877
+ location=[_row.geometry.y, _row.geometry.x],
878
+ radius=5,
879
+ tooltip=folium.Tooltip(
880
+ f"""
881
+ Stop Name: {_row["stop_name"]}<br>
882
+ Tier: {_row["Tier"]}<br>
883
+ Routes: {_row["route_ids_served"]}<br>
884
+ City: {_row["city"]}<br>
885
+ County: {_row["county"]}<br>
886
+ Route type: {_row["routetypes"]}"""
887
+ ),
888
+ color=color,
889
+ fill_color=color,
890
+ ).add_to(m)
891
+ )
892
+ m
893
+ return
894
+
895
+
896
+ @app.cell
897
+ def _(mo):
898
+
899
+ file_input = mo.ui.file(
900
+ label="Upload a GTFS zip file",
901
+ filetypes=[".zip"],
902
+ multiple=False,
903
+ )
904
+ url_input = mo.ui.text(
905
+ label="Or paste a URL to a GTFS zip",
906
+ placeholder="https://example.com/gtfs.zip",
907
+ )
908
+
909
+ mo.hstack([file_input, url_input], justify="start")
910
+ return file_input, url_input
911
+
912
+
913
+ @app.cell
914
+ def _(Optional, file_input, url_input):
915
+ import tempfile
916
+
917
+ # --- React to user input ---
918
+ def get_gtfs_bytes() -> Optional[bytes]:
919
+ """Return GTFS bytes from whichever input the user used."""
920
+ if file_input.value:
921
+ # Uploaded file -> file_input.value is a list of named tuples (name, contents)
922
+ return file_input.value[0].contents
923
+ elif url_input.value.strip():
924
+ url = url_input.value.strip()
925
+ try:
926
+ resp = requests.get(url, timeout=30)
927
+ resp.raise_for_status()
928
+ return resp.content
929
+ except Exception as e:
930
+ raise ValueError(f"Failed to download GTFS from URL: {e}") from None
931
+ return None
932
+
933
+ gtfs_data = get_gtfs_bytes()
934
+
935
+ with tempfile.NamedTemporaryFile(delete=False) as tmp:
936
+ tmp.write(gtfs_data)
937
+ tmp.flush() # Ensure data is written to disk
938
+
939
+ print(f"File created at: {tmp.name}")
940
+
941
+ # Optional: Read back from the start
942
+ new_stops = parse_gtfs_zip(tmp.name)
943
+ new_stops.explore()
944
+ return (new_stops,)
945
+
946
+
947
+ @app.cell
948
+ def _(new_stops):
949
+ buffers = create_half_mi_buffers(new_stops)
950
+ buffers.explore()
951
+ return (buffers,)
952
+
953
+
954
+ @app.cell
955
+ def _(buffers):
956
+ scag_parcels = fetch_scag_parcels(buffers_gdf=buffers)
957
+ scag_parcels
958
+ return (scag_parcels,)
959
+
960
+
961
+ @app.cell
962
+ def _(buffers):
963
+ ca_parcels = fetch_ca_parcels(buffers_gdf=buffers)
964
+ ca_parcels
965
+ return (ca_parcels,)
966
+
967
+
968
+ @app.cell
969
+ def _(scag_parcels):
970
+ scag_with_density = compute_scag_density(scag_parcels=scag_parcels)
971
+ scag_with_density[scag_with_density["current_density_du_per_ac"] > 0][:1000].explore("current_density_du_per_ac")
972
+ return (scag_with_density,)
973
+
974
+
975
+ @app.cell
976
+ def _(new_stops, scag_with_density):
977
+ scag_with_dwelling_units = create_buffer_donuts(stops_gdf=new_stops, scag_density=scag_with_density)
978
+ scag_with_dwelling_units[scag_with_dwelling_units["new_dwelling_units"] > 0][:1000].explore("dwelling_units_new")
979
+ return (scag_with_dwelling_units,)
980
+
981
+
982
+ @app.cell
983
+ def _(ca_parcels, scag_with_dwelling_units):
984
+ joined_parcels = join_scag_ca_parcels(ca_parcels=ca_parcels, scag_by_apn=scag_with_dwelling_units)
985
+ joined_parcels
986
+ return
987
+
988
+
989
+ @app.cell
990
+ def _():
991
+ return
992
+
993
+
994
+ if __name__ == "__main__":
995
+ app.run()
notebooks/src/__init__.py ADDED
File without changes
{src → notebooks/src}/arcgis_paginate.py RENAMED
File without changes
pyproject.toml CHANGED
@@ -44,14 +44,14 @@ ignore = [
44
  ]
45
 
46
  [tool.marimo.runtime]
47
- pythonpath = ["src"]
48
 
49
  [tool.pytest.ini_options]
50
- pythonpath = ["src"]
51
 
52
  [build-system]
53
  requires = ["setuptools>=61"]
54
  build-backend = "setuptools.build_meta"
55
 
56
  [tool.setuptools.packages.find]
57
- where = ["src"]
 
44
  ]
45
 
46
  [tool.marimo.runtime]
47
+ pythonpath = ["notebooks"]
48
 
49
  [tool.pytest.ini_options]
50
+ pythonpath = ["notebooks"]
51
 
52
  [build-system]
53
  requires = ["setuptools>=61"]
54
  build-backend = "setuptools.build_meta"
55
 
56
  [tool.setuptools.packages.find]
57
+ where = ["notebooks"]
tests/test_arcgis_paginate.py CHANGED
@@ -6,8 +6,7 @@ import geopandas as gpd
6
  import pytest
7
  import responses
8
  from shapely.geometry import Polygon, box
9
-
10
- from arcgis_paginate import (
11
  fetch_from_arcgis,
12
  paginate_arcgis,
13
  shapely_to_esri_json,
 
6
  import pytest
7
  import responses
8
  from shapely.geometry import Polygon, box
9
+ from src.arcgis_paginate import (
 
10
  fetch_from_arcgis,
11
  paginate_arcgis,
12
  shapely_to_esri_json,
tests/test_gtfs_to_parcels.py ADDED
@@ -0,0 +1,664 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 pytest
10
+ from sb79map import (
11
+ aggregate_parcels_to_stops,
12
+ assign_nearest_stop,
13
+ compute_scag_density,
14
+ create_buffer_donuts,
15
+ create_half_mi_buffers,
16
+ join_scag_ca_parcels,
17
+ parse_gtfs_zip,
18
+ trim_around_stations,
19
+ )
20
+ from shapely.geometry import Point, box
21
+
22
+
23
+ def _make_gtfs_zip(
24
+ routes: list[dict],
25
+ trips: list[dict],
26
+ stop_times: list[dict],
27
+ stops: list[dict],
28
+ calendar: list[dict] | None = None,
29
+ ) -> bytes:
30
+ """Create an in-memory GTFS zip file for testing."""
31
+ buf = io.BytesIO()
32
+ with zipfile.ZipFile(buf, "w") as z:
33
+ if routes:
34
+ cols = list(routes[0].keys())
35
+ z.writestr(
36
+ "routes.txt",
37
+ ",".join(cols) + "\n" + "\n".join(",".join(str(r[c]) for c in cols) for r in routes),
38
+ )
39
+ if trips:
40
+ cols = list(trips[0].keys())
41
+ z.writestr(
42
+ "trips.txt",
43
+ ",".join(cols) + "\n" + "\n".join(",".join(str(t[c]) for c in cols) for t in trips),
44
+ )
45
+ if stop_times:
46
+ cols = list(stop_times[0].keys())
47
+ z.writestr(
48
+ "stop_times.txt",
49
+ ",".join(cols) + "\n" + "\n".join(",".join(str(s[c]) for c in cols) for s in stop_times),
50
+ )
51
+ if stops:
52
+ cols = list(stops[0].keys())
53
+ z.writestr(
54
+ "stops.txt",
55
+ ",".join(cols) + "\n" + "\n".join(",".join(str(s[c]) for c in cols) for s in stops),
56
+ )
57
+ if calendar:
58
+ cols = list(calendar[0].keys())
59
+ z.writestr(
60
+ "calendar.txt",
61
+ ",".join(cols) + "\n" + "\n".join(",".join(str(c[col]) for col in cols) for c in calendar),
62
+ )
63
+ return buf.getvalue()
64
+
65
+
66
+ def _make_stops_gdf(stops_data: list[dict]) -> gpd.GeoDataFrame:
67
+ """Create a stops GeoDataFrame from a list of dicts."""
68
+ records = []
69
+ for s in stops_data:
70
+ records.append(
71
+ {
72
+ "stop_id": s["stop_id"],
73
+ "stop_name": s.get("stop_name", ""),
74
+ "Tier": s["Tier"],
75
+ "geometry": Point(s["lon"], s["lat"]),
76
+ }
77
+ )
78
+ return gpd.GeoDataFrame(records, crs="EPSG:4326")
79
+
80
+
81
+ def _make_parcels_gdf(parcels_data: list[dict]) -> gpd.GeoDataFrame:
82
+ """Create a parcels GeoDataFrame from a list of dicts."""
83
+ records = []
84
+ for p in parcels_data:
85
+ rec = {
86
+ "APN20": p["APN20"],
87
+ "current_density_du_per_ac": p.get("current_density_du_per_ac", 0),
88
+ "ZN19_CITY": p.get("ZN19_CITY", ""),
89
+ "ZN19_SCAG": p.get("ZN19_SCAG", 0),
90
+ "CITY": p.get("CITY", ""),
91
+ "COUNTY": p.get("COUNTY", ""),
92
+ "Tier": p.get("Tier", 1),
93
+ "geometry": box(*p["bbox"]),
94
+ }
95
+ # Include any extra columns passed in the dict
96
+ for k, v in p.items():
97
+ if k not in rec and k != "bbox":
98
+ rec[k] = v
99
+ records.append(rec)
100
+ return gpd.GeoDataFrame(records, crs="EPSG:4326")
101
+
102
+
103
+ class TestParseGtfsZip:
104
+ def test_basic_parse(self):
105
+ """Parse a minimal GTFS zip with one subway route."""
106
+ gtfs_bytes = _make_gtfs_zip(
107
+ routes=[{"route_id": "801", "route_type": "1", "agency_id": "metro"}],
108
+ trips=[
109
+ {"route_id": "801", "trip_id": "t1", "service_id": "wk", "direction_id": "0"},
110
+ {"route_id": "801", "trip_id": "t2", "service_id": "wk", "direction_id": "1"},
111
+ ],
112
+ stop_times=[
113
+ {"trip_id": "t1", "stop_id": "801S"},
114
+ {"trip_id": "t2", "stop_id": "801S"},
115
+ ],
116
+ stops=[
117
+ {
118
+ "stop_id": "801S",
119
+ "stop_name": "Test Station",
120
+ "stop_lat": "34.0",
121
+ "stop_lon": "-118.0",
122
+ "location_type": "1",
123
+ },
124
+ ],
125
+ calendar=[
126
+ {
127
+ "service_id": "wk",
128
+ "monday": "1",
129
+ "tuesday": "1",
130
+ "wednesday": "1",
131
+ "thursday": "1",
132
+ "friday": "1",
133
+ "saturday": "0",
134
+ "sunday": "0",
135
+ }
136
+ ],
137
+ )
138
+ path = Path(tempfile.gettempdir()) / "_test_gtfs.zip"
139
+
140
+ path.write_bytes(gtfs_bytes)
141
+ try:
142
+ result = parse_gtfs_zip(path)
143
+ assert len(result) == 1
144
+ assert result.iloc[0]["stop_id"] == "801S"
145
+ assert result.iloc[0]["Tier"] == 1 # subway → Tier 1
146
+ assert result.iloc[0]["routetypes"] == "1"
147
+ finally:
148
+ path.unlink(missing_ok=True)
149
+
150
+ def test_tier1_light_rail_high_freq(self):
151
+ """route_type=0 with n_arrivals >= 72 → Tier 1."""
152
+ gtfs_bytes = _make_gtfs_zip(
153
+ routes=[{"route_id": "801", "route_type": "0", "agency_id": "metro"}],
154
+ trips=[{"route_id": "801", "trip_id": f"t{i}", "service_id": "wk", "direction_id": "0"} for i in range(40)]
155
+ + [{"route_id": "801", "trip_id": f"t{i}", "service_id": "wk", "direction_id": "1"} for i in range(40, 80)],
156
+ stop_times=[{"trip_id": f"t{i}", "stop_id": "801S"} for i in range(80)],
157
+ stops=[
158
+ {"stop_id": "801S", "stop_name": "Test", "stop_lat": "34.0", "stop_lon": "-118.0", "location_type": "1"},
159
+ ],
160
+ calendar=[
161
+ {
162
+ "service_id": "wk",
163
+ "monday": "1",
164
+ "tuesday": "1",
165
+ "wednesday": "1",
166
+ "thursday": "1",
167
+ "friday": "1",
168
+ "saturday": "0",
169
+ "sunday": "0",
170
+ }
171
+ ],
172
+ )
173
+ path = Path(tempfile.gettempdir()) / "_test_gtfs2.zip"
174
+
175
+ path.write_bytes(gtfs_bytes)
176
+ try:
177
+ result = parse_gtfs_zip(path)
178
+ assert len(result) == 1
179
+ # 80 trips / 1 weekday service = 80/day >= 72 → Tier 1
180
+ assert result.iloc[0]["Tier"] == 1
181
+ finally:
182
+ path.unlink(missing_ok=True)
183
+
184
+ def test_tier1_light_rail_high_freq_72plus(self):
185
+ """route_type=0 with n_arrivals >= 72 → Tier 1."""
186
+ gtfs_bytes = _make_gtfs_zip(
187
+ routes=[{"route_id": "801", "route_type": "0", "agency_id": "metro"}],
188
+ trips=[{"route_id": "801", "trip_id": f"t{i}", "service_id": "wk", "direction_id": "0"} for i in range(200)]
189
+ + [{"route_id": "801", "trip_id": f"t{i}", "service_id": "wk", "direction_id": "1"} for i in range(200, 400)],
190
+ stop_times=[{"trip_id": f"t{i}", "stop_id": "801S"} for i in range(400)],
191
+ stops=[
192
+ {"stop_id": "801S", "stop_name": "Test", "stop_lat": "34.0", "stop_lon": "-118.0", "location_type": "1"},
193
+ ],
194
+ calendar=[
195
+ {
196
+ "service_id": "wk",
197
+ "monday": "1",
198
+ "tuesday": "1",
199
+ "wednesday": "1",
200
+ "thursday": "1",
201
+ "friday": "1",
202
+ "saturday": "0",
203
+ "sunday": "0",
204
+ }
205
+ ],
206
+ )
207
+ path = Path(tempfile.gettempdir()) / "_test_gtfs3.zip"
208
+
209
+ path.write_bytes(gtfs_bytes)
210
+ try:
211
+ result = parse_gtfs_zip(path)
212
+ assert len(result) == 1
213
+ # 400 trips / 5 days = 80/day >= 72 → Tier 1
214
+ assert result.iloc[0]["Tier"] == 1
215
+ finally:
216
+ path.unlink(missing_ok=True)
217
+
218
+ def test_tier2_light_rail_low_freq(self):
219
+ """route_type=0 with n_arrivals < 72 → Tier 2."""
220
+ gtfs_bytes = _make_gtfs_zip(
221
+ routes=[{"route_id": "801", "route_type": "0", "agency_id": "metro"}],
222
+ trips=[{"route_id": "801", "trip_id": f"t{i}", "service_id": "wk", "direction_id": "0"} for i in range(10)]
223
+ + [{"route_id": "801", "trip_id": f"t{i}", "service_id": "wk", "direction_id": "1"} for i in range(10, 20)],
224
+ stop_times=[{"trip_id": f"t{i}", "stop_id": "801S"} for i in range(20)],
225
+ stops=[
226
+ {"stop_id": "801S", "stop_name": "Test", "stop_lat": "34.0", "stop_lon": "-118.0", "location_type": "1"},
227
+ ],
228
+ calendar=[
229
+ {
230
+ "service_id": "wk",
231
+ "monday": "1",
232
+ "tuesday": "1",
233
+ "wednesday": "1",
234
+ "thursday": "1",
235
+ "friday": "1",
236
+ "saturday": "0",
237
+ "sunday": "0",
238
+ }
239
+ ],
240
+ )
241
+ path = Path(tempfile.gettempdir()) / "_test_gtfs4.zip"
242
+
243
+ path.write_bytes(gtfs_bytes)
244
+ try:
245
+ result = parse_gtfs_zip(path)
246
+ assert len(result) == 1
247
+ # 20 trips / 5 = 4/day < 72 → Tier 2
248
+ assert result.iloc[0]["Tier"] == 2
249
+ finally:
250
+ path.unlink(missing_ok=True)
251
+
252
+ def test_tier2_commuter_rail_medium(self):
253
+ """route_type=2 with 48 <= n_arrivals < 72 → Tier 2."""
254
+ # Use 2 weekday services so 300 trips / 2 = 150/day... still >= 72
255
+ # Need fewer trips: 120 trips / 2 services = 60/day, 48 <= 60 < 72 → Tier 2
256
+ gtfs_bytes = _make_gtfs_zip(
257
+ routes=[{"route_id": "701", "route_type": "2", "agency_id": "metrolink"}],
258
+ trips=[{"route_id": "701", "trip_id": f"t{i}", "service_id": "wk1", "direction_id": "0"} for i in range(30)]
259
+ + [{"route_id": "701", "trip_id": f"t{i}", "service_id": "wk2", "direction_id": "0"} for i in range(30, 60)]
260
+ + [{"route_id": "701", "trip_id": f"t{i}", "service_id": "wk1", "direction_id": "1"} for i in range(60, 90)]
261
+ + [{"route_id": "701", "trip_id": f"t{i}", "service_id": "wk2", "direction_id": "1"} for i in range(90, 120)],
262
+ stop_times=[{"trip_id": f"t{i}", "stop_id": "701S"} for i in range(120)],
263
+ stops=[
264
+ {"stop_id": "701S", "stop_name": "Test", "stop_lat": "34.0", "stop_lon": "-118.0", "location_type": "1"},
265
+ ],
266
+ calendar=[
267
+ {
268
+ "service_id": "wk1",
269
+ "monday": "1",
270
+ "tuesday": "1",
271
+ "wednesday": "1",
272
+ "thursday": "1",
273
+ "friday": "1",
274
+ "saturday": "0",
275
+ "sunday": "0",
276
+ },
277
+ {
278
+ "service_id": "wk2",
279
+ "monday": "1",
280
+ "tuesday": "1",
281
+ "wednesday": "1",
282
+ "thursday": "1",
283
+ "friday": "1",
284
+ "saturday": "0",
285
+ "sunday": "0",
286
+ },
287
+ ],
288
+ )
289
+ path = Path(tempfile.gettempdir()) / "_test_gtfs5.zip"
290
+
291
+ path.write_bytes(gtfs_bytes)
292
+ try:
293
+ result = parse_gtfs_zip(path)
294
+ assert len(result) == 1
295
+ # 120 trips / 2 weekday services = 60/day, 48 <= 60 < 72 → Tier 2
296
+ assert result.iloc[0]["Tier"] == 2
297
+ finally:
298
+ path.unlink(missing_ok=True)
299
+
300
+ def test_tier_override(self):
301
+ """Override a Tier 1 route to Tier 2."""
302
+ gtfs_bytes = _make_gtfs_zip(
303
+ routes=[{"route_id": "801", "route_type": "1", "agency_id": "metro"}],
304
+ trips=[
305
+ {"route_id": "801", "trip_id": "t1", "service_id": "wk", "direction_id": "0"},
306
+ ],
307
+ stop_times=[{"trip_id": "t1", "stop_id": "801S"}],
308
+ stops=[
309
+ {"stop_id": "801S", "stop_name": "Test", "stop_lat": "34.0", "stop_lon": "-118.0", "location_type": "1"},
310
+ ],
311
+ calendar=[
312
+ {
313
+ "service_id": "wk",
314
+ "monday": "1",
315
+ "tuesday": "1",
316
+ "wednesday": "1",
317
+ "thursday": "1",
318
+ "friday": "1",
319
+ "saturday": "0",
320
+ "sunday": "0",
321
+ }
322
+ ],
323
+ )
324
+ path = Path(tempfile.gettempdir()) / "_test_gtfs6.zip"
325
+
326
+ path.write_bytes(gtfs_bytes)
327
+ try:
328
+ result = parse_gtfs_zip(path, tier_overrides={"801": 2})
329
+ assert len(result) == 1
330
+ assert result.iloc[0]["Tier"] == 2 # overridden
331
+ finally:
332
+ path.unlink(missing_ok=True)
333
+
334
+ def test_skip_non_tier_stops(self):
335
+ """Stops with route_type > 2 (e.g. bus) should be excluded."""
336
+ gtfs_bytes = _make_gtfs_zip(
337
+ routes=[{"route_id": "901", "route_type": "3", "agency_id": "metro"}],
338
+ trips=[
339
+ {"route_id": "901", "trip_id": "t1", "service_id": "wk", "direction_id": "0"},
340
+ ],
341
+ stop_times=[{"trip_id": "t1", "stop_id": "901S"}],
342
+ stops=[
343
+ {"stop_id": "901S", "stop_name": "Bus Stop", "stop_lat": "34.0", "stop_lon": "-118.0", "location_type": "1"},
344
+ ],
345
+ calendar=[
346
+ {
347
+ "service_id": "wk",
348
+ "monday": "1",
349
+ "tuesday": "1",
350
+ "wednesday": "1",
351
+ "thursday": "1",
352
+ "friday": "1",
353
+ "saturday": "0",
354
+ "sunday": "0",
355
+ }
356
+ ],
357
+ )
358
+ path = Path(tempfile.gettempdir()) / "_test_gtfs7.zip"
359
+
360
+ path.write_bytes(gtfs_bytes)
361
+ try:
362
+ result = parse_gtfs_zip(path)
363
+ assert len(result) == 0 # no Tier 1 or 2 stops
364
+ finally:
365
+ path.unlink(missing_ok=True)
366
+
367
+ def test_mixed_route_types(self):
368
+ """Station with route_types '0,1' should be Tier 1 (has subway)."""
369
+ gtfs_bytes = _make_gtfs_zip(
370
+ routes=[
371
+ {"route_id": "801", "route_type": "1", "agency_id": "metro"},
372
+ {"route_id": "802", "route_type": "0", "agency_id": "metro"},
373
+ ],
374
+ trips=[
375
+ {"route_id": "801", "trip_id": "t1", "service_id": "wk", "direction_id": "0"},
376
+ {"route_id": "802", "trip_id": "t2", "service_id": "wk", "direction_id": "0"},
377
+ ],
378
+ stop_times=[
379
+ {"trip_id": "t1", "stop_id": "801S"},
380
+ {"trip_id": "t2", "stop_id": "801S"},
381
+ ],
382
+ stops=[
383
+ {"stop_id": "801S", "stop_name": "Mixed", "stop_lat": "34.0", "stop_lon": "-118.0", "location_type": "1"},
384
+ ],
385
+ calendar=[
386
+ {
387
+ "service_id": "wk",
388
+ "monday": "1",
389
+ "tuesday": "1",
390
+ "wednesday": "1",
391
+ "thursday": "1",
392
+ "friday": "1",
393
+ "saturday": "0",
394
+ "sunday": "0",
395
+ }
396
+ ],
397
+ )
398
+ path = Path(tempfile.gettempdir()) / "_test_gtfs8.zip"
399
+
400
+ path.write_bytes(gtfs_bytes)
401
+ try:
402
+ result = parse_gtfs_zip(path)
403
+ assert len(result) == 1
404
+ assert result.iloc[0]["Tier"] == 1 # has route_type 1
405
+ assert "1" in result.iloc[0]["routetypes"]
406
+ finally:
407
+ path.unlink(missing_ok=True)
408
+
409
+
410
+ # ---------------------------------------------------------------------------
411
+ # Tests: create_half_mi_buffers
412
+ # ---------------------------------------------------------------------------
413
+
414
+
415
+ class TestCreateHalfMiBuffers:
416
+ def test_basic(self):
417
+ stops = _make_stops_gdf(
418
+ [
419
+ {"stop_id": "A", "Tier": 1, "lat": 34.0, "lon": -118.0},
420
+ ]
421
+ )
422
+ buffers = create_half_mi_buffers(stops)
423
+ assert len(buffers) == 1
424
+ assert buffers.crs.to_string() == "EPSG:3310"
425
+ # Buffer should be a polygon, not a point
426
+ assert buffers.geometry.iloc[0].geom_type in ("Polygon", "MultiPolygon")
427
+ # Area should be roughly pi * 804.7^2 ≈ 2,034,000 m²
428
+ area = buffers.geometry.iloc[0].area
429
+ assert 1_900_000 < area < 2_100_000
430
+
431
+
432
+ # ---------------------------------------------------------------------------
433
+ # Tests: compute_scag_density
434
+ # ---------------------------------------------------------------------------
435
+
436
+
437
+ class TestComputeScagDensity:
438
+ def test_la_density(self):
439
+ parcels = _make_parcels_gdf(
440
+ [
441
+ {"APN20": "1", "ZN19_CITY": "RD1.5", "CITY": "Los Angeles", "bbox": (0, 0, 100, 100)},
442
+ ]
443
+ )
444
+ result = compute_scag_density(parcels)
445
+ assert "current_density_du_per_ac" in result.columns
446
+ # RD1.5 → 43560 / 1500 = 29.04
447
+ assert result.iloc[0]["current_density_du_per_ac"] == pytest.approx(29.04, rel=0.01)
448
+
449
+ def test_non_la_density(self):
450
+ parcels = _make_parcels_gdf(
451
+ [
452
+ {"APN20": "1", "ZN19_SCAG": 1111, "CITY": "Other", "bbox": (0, 0, 100, 100)},
453
+ ]
454
+ )
455
+ result = compute_scag_density(parcels)
456
+ # 1111 → 10 du/ac
457
+ assert result.iloc[0]["current_density_du_per_ac"] == 10
458
+
459
+ def test_non_la_density_zero_default(self):
460
+ """Unrecognized ZN19_SCAG codes should get 0."""
461
+ parcels = _make_parcels_gdf(
462
+ [
463
+ {"APN20": "1", "ZN19_SCAG": 9999, "CITY": "Other", "bbox": (0, 0, 100, 100)},
464
+ ]
465
+ )
466
+ result = compute_scag_density(parcels)
467
+ assert result.iloc[0]["current_density_du_per_ac"] == 0
468
+
469
+
470
+ # ---------------------------------------------------------------------------
471
+ # Tests: trim_around_stations
472
+ # ---------------------------------------------------------------------------
473
+
474
+
475
+ class TestTrimAroundStations:
476
+ def test_parcel_within_buffer(self):
477
+ stops = _make_stops_gdf(
478
+ [
479
+ {"stop_id": "A", "Tier": 1, "lat": 34.0, "lon": -118.0},
480
+ ]
481
+ )
482
+ # Parcel right next to the stop
483
+ parcels = _make_parcels_gdf(
484
+ [
485
+ {"APN20": "1", "current_density_du_per_ac": 10, "Tier": 1, "bbox": (-118.001, 33.999, -117.999, 34.001)},
486
+ ]
487
+ )
488
+ result = trim_around_stations(parcels, stops, 200)
489
+ assert len(result) >= 1
490
+ assert "buffer_zone_id" in result.columns
491
+ assert result["buffer_zone_id"].iloc[0] == "200ft"
492
+
493
+ def test_parcel_far_from_stop(self):
494
+ stops = _make_stops_gdf(
495
+ [
496
+ {"stop_id": "A", "Tier": 1, "lat": 34.0, "lon": -118.0},
497
+ ]
498
+ )
499
+ # Parcel far away
500
+ parcels = _make_parcels_gdf(
501
+ [
502
+ {"APN20": "1", "current_density_du_per_ac": 10, "Tier": 1, "bbox": (-117.0, 34.0, -116.99, 34.01)},
503
+ ]
504
+ )
505
+ result = trim_around_stations(parcels, stops, 200)
506
+ assert len(result) == 0 # no intersection
507
+
508
+
509
+ # ---------------------------------------------------------------------------
510
+ # Tests: create_buffer_donuts
511
+ # ---------------------------------------------------------------------------
512
+
513
+
514
+ class TestCreateBufferDonuts:
515
+ def test_weighted_density(self):
516
+ stops = _make_stops_gdf(
517
+ [
518
+ {"stop_id": "A", "Tier": 1, "lat": 34.0, "lon": -118.0},
519
+ ]
520
+ )
521
+ parcels = _make_parcels_gdf(
522
+ [
523
+ {
524
+ "APN20": "1",
525
+ "current_density_du_per_ac": 10,
526
+ "ZN19_CITY": "",
527
+ "ZN19_SCAG": 0,
528
+ "CITY": "Other",
529
+ "COUNTY": "LA",
530
+ "Tier": 1,
531
+ "bbox": (-118.001, 33.999, -117.999, 34.001),
532
+ },
533
+ ]
534
+ )
535
+ result = create_buffer_donuts(stops, parcels)
536
+ assert len(result) >= 1
537
+ assert "new_density_du_per_ac" in result.columns
538
+ assert "dwelling_units_new" in result.columns
539
+ assert "dwelling_units_current" in result.columns
540
+ assert result["new_density_du_per_ac"].iloc[0] > 0
541
+
542
+
543
+ # ---------------------------------------------------------------------------
544
+ # Tests: join_scag_ca_parcels
545
+ # ---------------------------------------------------------------------------
546
+
547
+
548
+ class TestJoinScagCaParcels:
549
+ def test_outer_join(self):
550
+ scag = _make_parcels_gdf(
551
+ [
552
+ {"APN20": "1", "current_density_du_per_ac": 10, "new_density_du_per_ac": 20, "bbox": (0, 0, 1, 1)},
553
+ ]
554
+ )
555
+ ca = gpd.GeoDataFrame(
556
+ {"PARCEL_APN": ["1", "2"], "SITE_CITY": ["LA", "SF"], "COUNTYNAME": ["Los Angeles", "San Francisco"]},
557
+ geometry=[box(0, 0, 1, 1), box(2, 2, 3, 3)],
558
+ crs="EPSG:4326",
559
+ )
560
+ result = join_scag_ca_parcels(scag, ca)
561
+ assert len(result) == 2
562
+ assert "current_density" in result.columns
563
+ assert "new_density" in result.columns
564
+ assert "city" in result.columns
565
+ assert "county" in result.columns
566
+ assert "apn" in result.columns
567
+
568
+
569
+ # ---------------------------------------------------------------------------
570
+ # Tests: assign_nearest_stop
571
+ # ---------------------------------------------------------------------------
572
+
573
+
574
+ class TestAssignNearestStop:
575
+ def test_single_stop(self):
576
+ stops = _make_stops_gdf(
577
+ [
578
+ {"stop_id": "A", "Tier": 1, "lat": 34.0, "lon": -118.0},
579
+ ]
580
+ )
581
+ buffers = create_half_mi_buffers(stops)
582
+ parcels = gpd.GeoDataFrame(
583
+ {"PARCEL_APN": ["1"]},
584
+ geometry=[Point(-118.0005, 34.0005).buffer(0.001)],
585
+ crs="EPSG:4326",
586
+ )
587
+ result = assign_nearest_stop(parcels, stops, buffers)
588
+ assert len(result) == 1
589
+ assert "clipped_geom" in result.columns
590
+ assert result["stop_id"].iloc[0] == "A"
591
+
592
+ def test_multi_buffer_nearest(self):
593
+ """Parcel intersecting two stop buffers should be assigned to the nearest."""
594
+ stops = _make_stops_gdf(
595
+ [
596
+ {"stop_id": "A", "Tier": 1, "lat": 34.0, "lon": -118.0},
597
+ {"stop_id": "B", "Tier": 1, "lat": 34.01, "lon": -118.0},
598
+ ]
599
+ )
600
+ buffers = create_half_mi_buffers(stops)
601
+ # Parcel closer to stop A
602
+ parcels = gpd.GeoDataFrame(
603
+ {"PARCEL_APN": ["1"]},
604
+ geometry=[Point(-118.0001, 34.0001).buffer(0.001)],
605
+ crs="EPSG:4326",
606
+ )
607
+ result = assign_nearest_stop(parcels, stops, buffers)
608
+ assert len(result) == 1
609
+ assert result["stop_id"].iloc[0] == "A"
610
+
611
+
612
+ # ---------------------------------------------------------------------------
613
+ # Tests: aggregate_parcels_to_stops
614
+ # ---------------------------------------------------------------------------
615
+
616
+
617
+ class TestAggregateParcelsToStops:
618
+ def test_basic_aggregation(self):
619
+ stops = _make_stops_gdf(
620
+ [
621
+ {"stop_id": "A", "Tier": 1, "lat": 34.0, "lon": -118.0},
622
+ ]
623
+ )
624
+ parcels = gpd.GeoDataFrame(
625
+ {
626
+ "stop_id": ["A"],
627
+ "clipped_geom": [box(-118.001, 33.999, -117.999, 34.001)],
628
+ "dwelling_units_new": [100],
629
+ "dwelling_units_current": [50],
630
+ "city": ["LOS ANGELES"],
631
+ "county": ["LOS ANGELES"],
632
+ "geometry": [box(-118.001, 33.999, -117.999, 34.001)],
633
+ },
634
+ crs="EPSG:4326",
635
+ )
636
+
637
+ result = aggregate_parcels_to_stops(parcels, stops)
638
+ assert len(result) == 1
639
+ assert result["parcel_acres"].iloc[0] > 0
640
+ assert result["additional_dwelling_units"].iloc[0] == 50 # 100 - 50
641
+ assert result["city"].iloc[0] == "LOS ANGELES"
642
+ assert result["county"].iloc[0] == "LOS ANGELES"
643
+
644
+ def test_no_additional_units_when_current_exceeds_new(self):
645
+ stops = _make_stops_gdf(
646
+ [
647
+ {"stop_id": "A", "Tier": 1, "lat": 34.0, "lon": -118.0},
648
+ ]
649
+ )
650
+ parcels = gpd.GeoDataFrame(
651
+ {
652
+ "stop_id": ["A"],
653
+ "clipped_geom": [box(-118.001, 33.999, -117.999, 34.001)],
654
+ "dwelling_units_new": [30],
655
+ "dwelling_units_current": [100],
656
+ "city": ["LA"],
657
+ "county": ["LA"],
658
+ "geometry": [box(-118.001, 33.999, -117.999, 34.001)],
659
+ },
660
+ crs="EPSG:4326",
661
+ )
662
+
663
+ result = aggregate_parcels_to_stops(parcels, stops)
664
+ assert result["additional_dwelling_units"].iloc[0] == 0 # max(0, 30-100) = 0