Spaces:
Sleeping

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

add notesbooks

Browse files
Files changed (2) hide show
  1. notebooks/gtfs.py +627 -0
  2. notebooks/sb79-map.py +77 -0
notebooks/gtfs.py ADDED
@@ -0,0 +1,627 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.12"
3
+ # dependencies = [
4
+ # "marimo>=0.23.3",
5
+ # "polars==1.30.0",
6
+ # "altair==4.2.0",
7
+ # "pandas==2.3.0",
8
+ # ]
9
+ # ///
10
+
11
+ import marimo
12
+
13
+ __generated_with = "0.23.3"
14
+ app = marimo.App(width="medium")
15
+
16
+ with app.setup:
17
+ import json
18
+ import time
19
+
20
+ import geopandas as gpd
21
+ import numpy as np
22
+ import pandas as pd
23
+ import requests
24
+
25
+ SCAG_PARCELS = "https://rdp.scag.ca.gov/mapping/rest/services/Housing/2020_Annual_Land_Use/MapServer/0/query"
26
+ CA_PARCELS = "https://services1.arcgis.com/jUJYIo9tSA7EHvfZ/ArcGIS/rest/services/CA_Statewide_Parcels_Public_view/FeatureServer/0/query"
27
+ HALF_MI_M = 804.7
28
+ STOPS_URL = r"https://services3.arcgis.com/NaFf4UaPo3IgQXqn/ArcGIS/rest/services/sb79_transit_stops/FeatureServer/0/query?where=0%3D0&objectIds=&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&resultType=none&distance=0.0&units=esriSRUnit_Meter&outDistance=&relationParam=&returnGeodetic=false&outFields=*&returnHiddenFields=false&returnGeometry=true&featureEncoding=esriDefault&multipatchOption=xyFootprint&maxAllowableOffset=&geometryPrecision=&outSR=&defaultSR=&datumTransformation=&applyVCSProjection=false&returnIdsOnly=false&returnUniqueIdsOnly=false&returnCountOnly=false&returnExtentOnly=false&returnQueryGeometry=false&returnDistinctValues=false&cacheHint=false&collation=&orderByFields=&groupByFieldsForStatistics=&returnAggIds=false&outStatistics=&having=&resultOffset=&resultRecordCount=&returnZ=false&returnM=false&returnTrueCurves=false&returnExceededLimitFeatures=true&quantizationParameters=&sqlFormat=none&f=pgeojson"
29
+ OUT_PATH = r"C:\Users\dknom\code\missing_metro\data"
30
+
31
+
32
+ @app.cell
33
+ def _():
34
+ stops_df = gpd.read_file(STOPS_URL)
35
+ stops_df
36
+ return (stops_df,)
37
+
38
+
39
+ @app.cell
40
+ def _(stops_df):
41
+ def shapely_to_esri_json(polygon, wkid=3857):
42
+ if polygon.is_empty:
43
+ return None
44
+ # Exterior ring
45
+ coords = list(polygon.exterior.coords)
46
+ rings = [[[x, y] for x, y in coords]]
47
+ return {"rings": rings, "spatialReference": {"wkid": wkid}}
48
+
49
+ parcels = gpd.GeoDataFrame()
50
+ buffer = stops_df.copy()
51
+ buffer.geometry = stops_df.to_crs("EPSG:3310").geometry.buffer(HALF_MI_M, resolution=8)
52
+
53
+ requests_per_second = 10
54
+ delay = 1.0 / requests_per_second
55
+ max_record_count = 2000
56
+
57
+ for _, _row in buffer.iterrows():
58
+ _esri_geom = shapely_to_esri_json(_row.geometry, wkid=3310)
59
+ _offset = 0
60
+
61
+ while True:
62
+ _params = {
63
+ "geometry": json.dumps(_esri_geom),
64
+ "geometryType": "esriGeometryPolygon",
65
+ "spatialRel": "esriSpatialRelIntersects",
66
+ "inSR": 3310,
67
+ "outFields": "APN20,COUNTY,CITY,IL_RATIO,ZN19_CITY,ZN19_SCAG,TCAC_2024,"
68
+ "APPAREL1MI,EDUC1MI,GROCERY1MI,HOSPIT1MI,RESTAUR1MI,JOBS_30MIN,YEAR",
69
+ "returnGeometry": "true",
70
+ "f": "geojson",
71
+ "where": "1=1",
72
+ "resultOffset": _offset,
73
+ "resultRecordCount": max_record_count,
74
+ }
75
+
76
+ _resp = requests.get(SCAG_PARCELS, params=_params)
77
+ _resp.raise_for_status()
78
+ _data = _resp.json()
79
+
80
+ _features = _data.get("features", [])
81
+ if not _features:
82
+ break
83
+
84
+ _parcels = gpd.GeoDataFrame.from_features(_features)
85
+ parcels = gpd.GeoDataFrame(pd.concat([parcels, _parcels], ignore_index=True))
86
+
87
+ _offset += max_record_count
88
+ time.sleep(delay)
89
+
90
+ # Check if the server indicated there are more results
91
+ if not _data.get("exceededTransferLimit", False):
92
+ break
93
+
94
+ parcels = parcels.set_crs("EPSG:4326").to_crs("EPSG:3310")
95
+ parcels
96
+ return
97
+
98
+
99
+ @app.cell
100
+ def _():
101
+ clipped_parcels = gpd.read_file(OUT_PATH + r"\clipped_parcels.geojson", driver="GeoJSON")
102
+ clipped_parcels
103
+ return (clipped_parcels,)
104
+
105
+
106
+ @app.cell
107
+ def _(clipped_parcels):
108
+ clipped_parcels
109
+ return
110
+
111
+
112
+ @app.cell
113
+ def _():
114
+ # Load the deduped CA parcels (already deduped by APN + clipped to buffer)
115
+ ca_parcels = gpd.read_file(OUT_PATH + r"\deduped_parcels.geojson", driver="GeoJSON")
116
+ ca_parcels
117
+ return (ca_parcels,)
118
+
119
+
120
+ @app.cell
121
+ def _(clipped_parcels):
122
+ # Deduplicate SCAG parcels by APN20 (same fix as CA parcels)
123
+ scag_deduped = clipped_parcels.groupby("APN20", as_index=False).first().set_crs(clipped_parcels.crs)
124
+ print(f"SCAG parcels: {len(clipped_parcels)} -> {len(scag_deduped)} after APN dedup")
125
+ return (scag_deduped,)
126
+
127
+
128
+ @app.cell
129
+ def _(scag_deduped):
130
+ # Compute density_limit on the deduped SCAG parcels
131
+ la_density = scag_deduped.to_crs(epsg=2229)["ZN19_CITY"].case_when(
132
+ [
133
+ (scag_deduped["ZN19_CITY"].str.contains("RD1.5"), 43560 / 1500),
134
+ (scag_deduped["ZN19_CITY"].str.contains("RD2"), 43560 / 2000),
135
+ (scag_deduped["ZN19_CITY"].str.contains("RD3"), 43560 / 3000),
136
+ (scag_deduped["ZN19_CITY"].str.contains("RD4"), 43560 / 4000),
137
+ (scag_deduped["ZN19_CITY"].str.contains("RD5"), 43560 / 5000),
138
+ (scag_deduped["ZN19_CITY"].str.contains("RD6"), 43560 / 6000),
139
+ (scag_deduped["ZN19_CITY"].str.contains("RMP"), 43560 / 20000),
140
+ (scag_deduped["ZN19_CITY"].str.contains("R3"), 43560 / 800),
141
+ (scag_deduped["ZN19_CITY"].str.contains("RAS3"), 43560 / 800),
142
+ (scag_deduped["ZN19_CITY"].str.contains("R4"), 43560 / 400),
143
+ (scag_deduped["ZN19_CITY"].str.contains("RAS4"), 43560 / 400),
144
+ (scag_deduped["ZN19_CITY"].str.contains("R5"), 43560 / 200),
145
+ (scag_deduped["ZN19_CITY"].str.contains("RE40"), 43560 / 40000),
146
+ (scag_deduped["ZN19_CITY"].str.contains("RE20"), 43560 / 20000),
147
+ (scag_deduped["ZN19_CITY"].str.contains("RE15"), 43560 / 15000),
148
+ (scag_deduped["ZN19_CITY"].str.contains("RE11"), 43560 / 11000),
149
+ (scag_deduped["ZN19_CITY"].str.contains("RE9"), 43560 / 9000),
150
+ (scag_deduped["ZN19_CITY"].str.contains("RS"), 43560 / 7500),
151
+ (scag_deduped["ZN19_CITY"].str.contains("R1"), 43560 / 5000),
152
+ (scag_deduped["ZN19_CITY"].str.contains("RU"), 43560 / 3500),
153
+ (scag_deduped["ZN19_CITY"].str.contains("RZ2.5"), 43560 / 2500),
154
+ (scag_deduped["ZN19_CITY"].str.contains("RZ3"), 43560 / 3000),
155
+ (scag_deduped["ZN19_CITY"].str.contains("RZ4"), 43560 / 4000),
156
+ (scag_deduped["ZN19_CITY"].str.contains("RW1"), 43560 / 2300),
157
+ (scag_deduped["ZN19_CITY"].str.contains("R2"), 43560 / 2500),
158
+ (scag_deduped["ZN19_CITY"].str.contains("RW2"), 43560 / 1150),
159
+ (scag_deduped["ZN19_CITY"] != "Los Angeles", 0),
160
+ ]
161
+ )
162
+
163
+ non_la_density = scag_deduped["ZN19_SCAG"].case_when(
164
+ [
165
+ (scag_deduped["ZN19_SCAG"] == 1111, 10),
166
+ (scag_deduped["ZN19_SCAG"] == 1112, 8),
167
+ (scag_deduped["ZN19_SCAG"] == 1113, 2),
168
+ (scag_deduped["ZN19_SCAG"] == 1121, 3 / (scag_deduped.area / 4047)),
169
+ (scag_deduped["ZN19_SCAG"] == 1122, 3 / (scag_deduped.area / 4047)),
170
+ (scag_deduped["ZN19_SCAG"] == 1140, 3 / (scag_deduped.area / 4047)),
171
+ (scag_deduped["ZN19_SCAG"] == 1123, 18),
172
+ (scag_deduped["ZN19_SCAG"] == 1124, 60),
173
+ (scag_deduped["ZN19_SCAG"] == 1125, 80),
174
+ (scag_deduped["ZN19_SCAG"] == 1131, 6),
175
+ (scag_deduped["ZN19_SCAG"] == 1150, 1),
176
+ (scag_deduped["ZN19_SCAG"] != 0, 0),
177
+ ]
178
+ )
179
+
180
+ scag_deduped["density_limit"] = np.where(scag_deduped["CITY"] == "Los Angeles", la_density, non_la_density)
181
+ scag_deduped
182
+ return
183
+
184
+
185
+ @app.cell
186
+ def _(scag_deduped, stops_df):
187
+ def trim_around_stations(buffer_distance: int) -> tuple[gpd.GeoDataFrame, gpd.GeoDataFrame]:
188
+ buffer_df = stops_df.to_crs(epsg=2229) # NAD83 / California zone 5 (feet)
189
+ buffer_df.geometry = buffer_df.buffer(buffer_distance).to_crs(epsg=4326)
190
+
191
+ temp_residential_df = scag_deduped.to_crs(epsg=4326)
192
+
193
+ residential_in_buffer = gpd.sjoin(
194
+ temp_residential_df, buffer_df, how="inner", rsuffix="_right", predicate="intersects"
195
+ )
196
+ trim_df = gpd.overlay(residential_in_buffer, buffer_df, how="intersection")
197
+ print(f"Total residential parcels: {len(temp_residential_df)}")
198
+ print(f"Residential parcels within {buffer_distance} feet of stations: {len(residential_in_buffer)}")
199
+ return buffer_df, trim_df
200
+
201
+ return (trim_around_stations,)
202
+
203
+
204
+ @app.cell
205
+ def _(trim_around_stations):
206
+ # %%
207
+ buffer_200ft_df, trim_200ft_df = trim_around_stations(200)
208
+ trim_200ft_df.explore()
209
+ return buffer_200ft_df, trim_200ft_df
210
+
211
+
212
+ @app.cell
213
+ def _(trim_around_stations):
214
+ # %%
215
+ buffer_halfmile_df, trim_halfmile_df = trim_around_stations(2640)
216
+ trim_halfmile_df[:1000].explore()
217
+ return (trim_halfmile_df,)
218
+
219
+
220
+ @app.cell
221
+ def _(trim_around_stations):
222
+
223
+ # %%
224
+ buffer_qtrmile_df, trim_qtrmile_df = trim_around_stations(1320)
225
+ trim_qtrmile_df[:1000].explore()
226
+ return buffer_qtrmile_df, trim_qtrmile_df
227
+
228
+
229
+ @app.cell
230
+ def _(buffer_qtrmile_df, trim_halfmile_df):
231
+ # %%
232
+ halfmile_donut = gpd.overlay(trim_halfmile_df, buffer_qtrmile_df, how="difference")
233
+ halfmile_donut[:1000].explore()
234
+ return (halfmile_donut,)
235
+
236
+
237
+ @app.cell
238
+ def _(buffer_200ft_df, trim_qtrmile_df):
239
+ # %%
240
+ qtrmile_donut = gpd.overlay(trim_qtrmile_df, buffer_200ft_df, how="difference")
241
+ qtrmile_donut
242
+ return (qtrmile_donut,)
243
+
244
+
245
+ @app.cell
246
+ def _(halfmile_donut):
247
+ halfmile_donut
248
+ return
249
+
250
+
251
+ @app.cell
252
+ def _(halfmile_donut, qtrmile_donut, trim_200ft_df):
253
+ # %%
254
+ trim_200ft_df["buffer_zone"] = "200ft"
255
+
256
+ qtrmile_donut["buffer_zone"] = "qtr_mi"
257
+
258
+ halfmile_donut["buffer_zone"] = "half_mi"
259
+
260
+ # Concat all three zones
261
+ residential_around_metro = gpd.GeoDataFrame(pd.concat([trim_200ft_df, qtrmile_donut, halfmile_donut]))
262
+
263
+ # Calculate area in sqft per row (EPSG:2229 is in feet)
264
+ residential_around_metro["area_sqft"] = residential_around_metro.to_crs(epsg=2229).area
265
+
266
+ # Assign zone-specific density (du/acre) based on Tier and buffer zone
267
+ # 200ft: Tier 1=160 du/ac, Tier 2=140 du/ac
268
+ # Qtr mi: Tier 1=120 du/ac, Tier 2=100 du/ac
269
+ # Half mi: Tier 1=100 du/ac, Tier 2=80 du/ac
270
+ zone_densities = pd.Series(
271
+ {
272
+ ("200ft", 1): 160,
273
+ ("200ft", 2): 140,
274
+ ("qtr_mi", 1): 120,
275
+ ("qtr_mi", 2): 100,
276
+ ("half_mi", 1): 100,
277
+ ("half_mi", 2): 80,
278
+ }
279
+ )
280
+ residential_around_metro["zone_density"] = residential_around_metro.set_index(["buffer_zone", "Tier_1"]).index.map(
281
+ zone_densities
282
+ )
283
+
284
+ # Now group by APN20 to get one row per parcel
285
+ # Union geometries, sum area per zone, calculate weighted density
286
+ from shapely import unary_union
287
+
288
+ def aggregate_parcel(group):
289
+ """Aggregate a single parcel's pieces across buffer zones."""
290
+ apn = group.name
291
+ total_area = group["area_sqft"].sum()
292
+ total_area_acres = total_area / 43560
293
+
294
+ # Weighted density = sum(zone_area * zone_density) / total_area
295
+ weighted_density = (group["area_sqft"] * group["zone_density"]).sum() / total_area
296
+
297
+ # Union all geometry pieces back together
298
+ unioned_geom = unary_union(group.geometry.tolist())
299
+
300
+ # Take first value for non-varying attributes
301
+ first = group.iloc[0]
302
+
303
+ return pd.Series(
304
+ {
305
+ "APN20": apn,
306
+ "geometry": unioned_geom,
307
+ "area_sqft": total_area,
308
+ "area_acres": total_area_acres,
309
+ "weighted_density": weighted_density,
310
+ "dwelling_units_new": weighted_density * total_area_acres,
311
+ "dwelling_units_current": first["density_limit"] * total_area_acres,
312
+ "density_limit": first["density_limit"],
313
+ "ZN19_CITY": first["ZN19_CITY"],
314
+ "ZN19_SCAG": first["ZN19_SCAG"],
315
+ "COUNTY": first["COUNTY"],
316
+ "CITY": first["CITY"],
317
+ "Tier_1": first["Tier_1"],
318
+ }
319
+ )
320
+
321
+ residential_by_apn = (
322
+ residential_around_metro.groupby("APN20", as_index=True)
323
+ .apply(aggregate_parcel, include_groups=False)
324
+ .reset_index(drop=True)
325
+ )
326
+
327
+ residential_by_apn = gpd.GeoDataFrame(residential_by_apn, geometry="geometry", crs=residential_around_metro.crs)
328
+
329
+ print(f"Before dedup: {len(residential_around_metro)} rows")
330
+ print(f"After APN dedup: {len(residential_by_apn)} rows")
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
338
+ def _(ca_parcels, residential_by_apn):
339
+ # Join residential_by_apn (SCAG zoning data) onto CA parcels by APN
340
+ # residential_by_apn has APN20, CA parcels have PARCEL_APN
341
+ scag_cols_to_join = [
342
+ "APN20",
343
+ "density_limit",
344
+ "weighted_density",
345
+ "dwelling_units_new",
346
+ "dwelling_units_current",
347
+ "ZN19_CITY",
348
+ "ZN19_SCAG",
349
+ "area_acres",
350
+ "CITY",
351
+ "COUNTY",
352
+ "TIER_1",
353
+ "geometry",
354
+ ]
355
+ # Only keep columns that exist in residential_by_apn
356
+ existing_cols = [c for c in scag_cols_to_join if c in residential_by_apn.columns]
357
+ ca_parcels_with_zoning = ca_parcels.merge(
358
+ residential_by_apn[existing_cols], left_on="PARCEL_APN", right_on="APN20", how="outer"
359
+ )
360
+ matched = ca_parcels_with_zoning["APN20"].notna().sum()
361
+ print(f"CA parcels: {len(ca_parcels)}")
362
+ print(f"Matched with SCAG zoning: {matched} ({matched / len(ca_parcels) * 100:.1f}%)")
363
+
364
+ # Audit non-matches: which SCAG APN20s didn't find a CA parcel match?
365
+ matched_apns = set(ca_parcels_with_zoning.dropna(subset=["APN20"])["APN20"].unique())
366
+ all_scag_apns = set(residential_by_apn["APN20"].unique())
367
+ unmatched_apns = all_scag_apns - matched_apns
368
+ print(f"SCAG parcels not matched to CA parcels: {len(unmatched_apns)}")
369
+
370
+ if len(unmatched_apns) > 0:
371
+ unmatched = residential_by_apn[residential_by_apn["APN20"].isin(unmatched_apns)]
372
+ print(f" Total dwelling units in unmatched: {unmatched['dwelling_units_new'].sum():.0f}")
373
+ print(f" Counties in unmatched: {unmatched['COUNTY'].value_counts().to_dict()}")
374
+
375
+ ca_parcels_with_zoning
376
+ return (ca_parcels_with_zoning,)
377
+
378
+
379
+ @app.cell
380
+ def _(ca_parcels_with_zoning):
381
+ ca_parcels_with_zoning["geometry"] = ca_parcels_with_zoning["geometry_x"].combine_first(
382
+ ca_parcels_with_zoning["geometry_y"]
383
+ )
384
+ ca_parcels_with_zoning["city"] = ca_parcels_with_zoning["SITE_CITY"].combine_first(
385
+ ca_parcels_with_zoning["CITY"].str.upper()
386
+ )
387
+ ca_parcels_with_zoning["county"] = ca_parcels_with_zoning["COUNTYNAME"].combine_first(
388
+ ca_parcels_with_zoning["COUNTY"].str.upper()
389
+ )
390
+ ca_parcels_with_zoning["apn"] = ca_parcels_with_zoning["PARCEL_APN"].combine_first(ca_parcels_with_zoning["APN20"])
391
+ ca_parcels_output = ca_parcels_with_zoning.rename(
392
+ columns={"density_limit": "current_density", "weighted_density": "new_density"}
393
+ )
394
+ ca_parcels_output
395
+ return (ca_parcels_output,)
396
+
397
+
398
+ @app.cell
399
+ def _():
400
+ return
401
+
402
+
403
+ @app.cell
404
+ def _(ca_parcels_output):
405
+ ca_parcels_output[
406
+ [
407
+ "geometry",
408
+ "city",
409
+ "county",
410
+ "apn",
411
+ "current_density",
412
+ "new_density",
413
+ "dwelling_units_current",
414
+ "dwelling_units_new",
415
+ "ZN19_CITY",
416
+ "ZN19_SCAG",
417
+ "area_acres",
418
+ ]
419
+ ].to_file(OUT_PATH + r"\parcels_with_zoning.json", driver="GeoJSON")
420
+ return
421
+
422
+
423
+ @app.cell
424
+ def _(stops_df):
425
+ stops_df["district_name"].value_counts()
426
+ return
427
+
428
+
429
+ @app.cell
430
+ def _(stops_df):
431
+ # from urllib.parse import urlencode
432
+ # import json
433
+ # import pandas as pd
434
+ # import time
435
+ # CA_PARCELS = 'https://services1.arcgis.com/jUJYIo9tSA7EHvfZ/ArcGIS/rest/services/CA_Statewide_Parcels_Public_view/FeatureServer/0/query?'
436
+
437
+ # def shapely_to_esri_json(polygon, wkid=3857):
438
+ # if polygon.is_empty:
439
+ # return None
440
+ # # Exterior ring
441
+ # coords = list(polygon.exterior.coords)
442
+ # rings = [[[x, y] for x, y in coords]]
443
+ # return {
444
+ # "rings": rings,
445
+ # "spatialReference": {"wkid": wkid}
446
+ # }
447
+
448
+ HALF_MI_M = 804.7
449
+ buffer = stops_df.copy()
450
+ buffer.geometry = stops_df.to_crs("EPSG:3310").geometry.buffer(HALF_MI_M, resolution=8)
451
+
452
+ # requests_per_second = 10
453
+ # delay = 1.0 / requests_per_second
454
+ # parcels = gpd.GeoDataFrame()
455
+
456
+ # for _, _row in buffer.iterrows():
457
+ # _esri_geom = shapely_to_esri_json(_row.geometry, wkid=3310)
458
+ # _params = {
459
+ # 'geometry': json.dumps(_esri_geom).replace(' ', ''),
460
+ # 'geometryType': 'esriGeometryPolygon',
461
+ # 'spatialRel': 'esriSpatialRelIntersects',
462
+ # 'inSR': 3310,
463
+ # 'outFields': '*',
464
+ # 'returnGeometry': 'true', # set true if you need parcel shapes
465
+ # 'f': 'geojson',
466
+ # 'where': '1=1',
467
+ # }
468
+ # _url = CA_PARCELS + urlencode(_params, safe='{}:,[]*')
469
+ # print(_url)
470
+ # _parcels = gpd.read_file(_url, driver='GeoJSON')
471
+ # if len(_parcels) > 2000:
472
+ # print(len(_parcels), _row['stop_name'], _row['district_name'])
473
+
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,)
485
+
486
+
487
+ @app.cell
488
+ def _(parcel_file):
489
+ parcel_file["COUNTYNAME"].value_counts()
490
+ return
491
+
492
+
493
+ @app.cell
494
+ def _(buffer):
495
+ buffer
496
+ return
497
+
498
+
499
+ @app.cell
500
+ def _(stops_df):
501
+ stops_df
502
+ return
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"]],
517
+ how="left",
518
+ predicate="intersects",
519
+ )
520
+
521
+ # 2. Identify parcels that intersect multiple stops
522
+ multi = parcels_with_stops.groupby(parcels_with_stops.index).size()
523
+ multi_parcel_ids = multi[multi > 1].index
524
+ multi_parcel_ids
525
+ return multi_parcel_ids, parcels_with_stops
526
+
527
+
528
+ @app.cell
529
+ def _(
530
+ buffer,
531
+ multi_parcel_ids,
532
+ parcels_clipped,
533
+ parcels_with_stops,
534
+ stops_df,
535
+ unary_union,
536
+ ):
537
+ print("collect all intersecting stop_ids and assign nearest")
538
+
539
+ # 1. Deduplicate parcels_with_stops to one row per parcel
540
+ # (keep first stop_id as fallback for single-buffer parcels)
541
+ parcels_deduped = parcels_with_stops[~parcels_with_stops.index.duplicated(keep="first")].copy()
542
+
543
+ # 2. For multi-buffer parcels, find the nearest stop
544
+ multi_parcels = parcels_with_stops.loc[multi_parcel_ids, ["stop_id"]]
545
+ multi_exploded = multi_parcels.explode("stop_id").reset_index()
546
+ multi_exploded.columns = ["parcel_idx", "stop_id"]
547
+
548
+ # 3. Attach geometries in projected CRS (EPSG:3310) for meaningful distances
549
+ stop_points_3310 = stops_df.set_index("stop_id").to_crs("EPSG:3310").geometry
550
+ parcel_centroids_3310 = parcels_clipped.to_crs("EPSG:3310").geometry.centroid
551
+
552
+ multi_exploded["distance"] = multi_exploded.apply(
553
+ lambda r: parcel_centroids_3310[r["parcel_idx"]].distance(stop_points_3310[r["stop_id"]]),
554
+ axis=1,
555
+ )
556
+
557
+ # 4. Keep only the closest stop for each multi-buffer parcel
558
+ nearest = multi_exploded.loc[
559
+ multi_exploded.groupby("parcel_idx")["distance"].idxmin(),
560
+ ["parcel_idx", "stop_id"],
561
+ ]
562
+ nearest = nearest.set_index("parcel_idx")["stop_id"]
563
+
564
+ # 5. Override stop_id for multi-buffer parcels with their nearest stop
565
+ parcels_deduped.loc[nearest.index, "stop_id"] = nearest
566
+
567
+ print("clipping parcels to buffer boundaries")
568
+ # Clip each parcel to its assigned stop's buffer so we only count
569
+ # the portion of the parcel that actually falls within the buffer
570
+ buffer_indexed = buffer.set_index("stop_id")[["geometry"]]
571
+ parcels_deduped["buffer_geom"] = parcels_deduped["stop_id"].map(buffer_indexed["geometry"])
572
+ parcels_deduped["clipped_geom"] = parcels_deduped.geometry.intersection(parcels_deduped["buffer_geom"])
573
+
574
+ print("deduplicating by APN to remove duplicate parcel rows")
575
+ # The same APN can appear many times (same parcel fetched from multiple
576
+ # buffer queries). Group by stop_id + APN to keep one row per unique parcel.
577
+ parcels_deduped = parcels_deduped.groupby(["stop_id", "PARCEL_APN"], as_index=False).first()
578
+
579
+ print("summing all parcels areas (using union to avoid double-counting overlapping geometries)")
580
+ # Use unary_union to merge any remaining overlapping geometries
581
+ # (e.g., different APNs sharing the same parcel shape like condos)
582
+ area_per_stop = (
583
+ parcels_deduped.groupby("stop_id")["clipped_geom"]
584
+ .apply(lambda g: unary_union(g.tolist()).area / 4046.86)
585
+ .reset_index()
586
+ )
587
+ area_per_stop.columns = ["stop_id", "parcel_acres"]
588
+
589
+ print("merging back to stops")
590
+ stops_with_parcel_area_df = stops_df.merge(area_per_stop, on="stop_id", how="left").fillna(0)
591
+ return parcels_deduped, stops_with_parcel_area_df
592
+
593
+
594
+ @app.cell
595
+ def _(stops_with_parcel_area_df):
596
+ stops_with_parcel_area_df
597
+ return
598
+
599
+
600
+ @app.cell
601
+ def _(stops_with_parcel_area_df):
602
+ stops_with_parcel_area_df.to_file(
603
+ r"C:\Users\dknom\code\missing_metro\data\stops_with_parcel_area.geojson", driver="GeoJSON"
604
+ )
605
+ return
606
+
607
+
608
+ @app.cell
609
+ def _(parcels_deduped):
610
+ parcels_deduped.set_geometry("clipped_geom").drop(columns=["geometry", "buffer_geom"]).set_crs("EPSG:3310").to_file(
611
+ r"C:\Users\dknom\code\missing_metro\data\deduped_parcels.geojson", driver="GeoJSON"
612
+ )
613
+ return
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
621
+
622
+
623
+ if __name__ == "__main__":
624
+ app.run()
625
+
626
+ if __name__ == "__main__":
627
+ app.run()
notebooks/sb79-map.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()