Spaces:
Sleeping

dn commited on
Commit
56c2f9b
·
1 Parent(s): 1d0385c

tests pass for real

Browse files
Files changed (2) hide show
  1. notebooks/sb79map.py +140 -71
  2. tests/test_gtfs_to_parcels.py +7 -6
notebooks/sb79map.py CHANGED
@@ -2,9 +2,11 @@
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
 
@@ -186,6 +188,14 @@ with app.setup(hide_code=True):
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:
@@ -195,7 +205,7 @@ with app.setup(hide_code=True):
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
 
@@ -356,6 +366,10 @@ with app.setup(hide_code=True):
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:
@@ -369,7 +383,7 @@ with app.setup(hide_code=True):
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),
@@ -398,34 +412,47 @@ with app.setup(hide_code=True):
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(
@@ -472,8 +499,20 @@ with app.setup(hide_code=True):
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
 
@@ -486,7 +525,7 @@ with app.setup(hide_code=True):
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``,
@@ -535,43 +574,57 @@ with app.setup(hide_code=True):
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,
@@ -940,50 +993,66 @@ def _(Optional, file_input, url_input):
940
  print(f"File created at: {tmp.name}")
941
 
942
  # Optional: Read back from the start
943
- new_stops = parse_gtfs_zip(tmp.name)
944
- new_stops.explore()
945
  return (new_stops,)
946
 
947
 
948
  @app.cell
949
  def _(new_stops):
950
  buffers = create_half_mi_buffers(new_stops)
951
- buffers.explore()
952
  return (buffers,)
953
 
954
 
955
- @app.cell
956
- def _(buffers):
957
- scag_parcels = fetch_scag_parcels(buffers_gdf=buffers)
958
- scag_parcels
959
- return (scag_parcels,)
960
-
961
-
962
  @app.cell
963
  def _(buffers):
964
  ca_parcels = fetch_ca_parcels(buffers_gdf=buffers)
965
- ca_parcels
966
- return (ca_parcels,)
 
967
 
968
 
969
  @app.cell
970
  def _(scag_parcels):
971
  scag_with_density = compute_scag_density(scag_parcels=scag_parcels)
972
- scag_with_density[scag_with_density["current_density_du_per_ac"] > 0][:1000].explore("current_density_du_per_ac")
973
  return (scag_with_density,)
974
 
975
 
976
  @app.cell
977
  def _(new_stops, scag_with_density):
978
  scag_with_dwelling_units = create_buffer_donuts(stops_gdf=new_stops, scag_density=scag_with_density)
979
- scag_with_dwelling_units[scag_with_dwelling_units["new_dwelling_units"] > 0][:1000].explore("dwelling_units_new")
980
  return (scag_with_dwelling_units,)
981
 
982
 
983
  @app.cell
984
- def _(ca_parcels, scag_with_dwelling_units):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
985
  joined_parcels = join_scag_ca_parcels(ca_parcels=ca_parcels, scag_by_apn=scag_with_dwelling_units)
986
- joined_parcels
 
 
 
 
 
987
  return
988
 
989
 
 
2
  # requires-python = ">=3.13"
3
  # dependencies = [
4
  # "auto-mix-prep>=0.2.0",
5
+ # "folium>=0.12",
6
  # "geopandas>=1.1.3",
7
+ # "mapclassify>=2.10.0",
8
  # "marimo>=0.23.3",
9
+ # "matplotlib>=3.10.9",
10
  # ]
11
  # ///
12
 
 
188
  parent_stations = stops_df[stops_df["location_type"] == "1"].copy()
189
  boarding_stops = stops_df[stops_df["location_type"] == "0"].copy()
190
 
191
+ # If there are no parent stations (location_type=1), treat all boarding
192
+ # stops (location_type=0) as individual stations. Some GTFS feeds
193
+ # (e.g. OC Streetcar) only have location_type=0 stops with no parent
194
+ # station hierarchy.
195
+ if parent_stations.empty:
196
+ parent_stations = boarding_stops.copy()
197
+ boarding_stops = gpd.GeoDataFrame() # no routes to propagate
198
+
199
  stop_times = list(csv.DictReader(io.StringIO(z.read("stop_times.txt").decode("utf-8"))))
200
  stop_to_routes: dict[str, set[str]] = defaultdict(set)
201
  for st in stop_times:
 
205
 
206
  parent_to_routes: dict[str, set[str]] = defaultdict(set)
207
  for _, bs in boarding_stops.iterrows():
208
+ parent = bs["parent_station"] if "parent_station" in bs else None
209
  if parent and parent in set(parent_stations["stop_id"]):
210
  parent_to_routes[parent].update(stop_to_routes.get(bs["stop_id"], set()))
211
 
 
366
  def compute_scag_density(scag_parcels: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
367
  """Add ``current_density_du_per_ac`` to SCAG parcels using LA / non-LA logic.
368
 
369
+ For LA parcels, first tries ``ZN19_CITY`` zone codes. If no match is found,
370
+ falls through to try ``ZN19_SCAG`` codes. Parcels that don't match any code
371
+ get ``NaN`` (excluded from downstream calculations).
372
+
373
  Parameters
374
  ----------
375
  scag_parcels:
 
383
  """
384
  df = scag_parcels.copy()
385
 
386
+ # --- LA density: map ZN19_CITY zone codes → du/ac ---
387
  la_density = df["ZN19_CITY"].case_when(
388
  [
389
  (df["ZN19_CITY"].str.contains("RD1.5", na=False), 43560 / 1500),
 
412
  (df["ZN19_CITY"].str.contains("RW1", na=False), 43560 / 2300),
413
  (df["ZN19_CITY"].str.contains("R2", na=False), 43560 / 2500),
414
  (df["ZN19_CITY"].str.contains("RW2", na=False), 43560 / 1150),
415
+ (df["ZN19_CITY"].str.contains("C1", na=False), 100),
416
+ (df["ZN19_CITY"].str.contains("C2", na=False), 43560 / 400),
417
+ (df["ZN19_CITY"].str.contains("C3", na=False), 110),
418
+ (df["ZN19_CITY"].str.contains("C4", na=False), 200),
419
  ]
420
  )
421
 
422
+ # --- Non-LA / fallback density: map ZN19_SCAG codes → du/ac ---
423
+ zn19_scag = df["ZN19_SCAG"].astype(str)
424
  area_acres = df.to_crs("EPSG:2229").area / 43560
425
+ scag_density = zn19_scag.case_when(
426
  [
427
+ (zn19_scag == "1110", 1 / area_acres.replace(0, np.nan)),
428
+ (zn19_scag == "1111", 1 / area_acres.replace(0, np.nan)),
429
+ (zn19_scag == "1112", 1 / area_acres.replace(0, np.nan)),
430
+ (zn19_scag == "1113", 1 / area_acres.replace(0, np.nan)),
431
+ (zn19_scag == "1121", 3 / area_acres.replace(0, np.nan)),
432
+ (zn19_scag == "1122", 3 / area_acres.replace(0, np.nan)),
433
+ (zn19_scag == "1140", 3 / area_acres.replace(0, np.nan)),
434
+ (zn19_scag == "1123", 18),
435
+ (zn19_scag == "1124", 60),
436
+ (zn19_scag == "1125", 80),
437
+ (zn19_scag == "1131", 6),
438
+ (zn19_scag == "1150", 1),
439
+ (zn19_scag == "1150", 1),
440
+ (zn19_scag == "1600", 40),
441
+ (zn19_scag == "1610", 40),
442
+ (zn19_scag == "1620", 30),
443
+ (zn19_scag.isin(["1220", "1221", "1222"]), 47),
444
+ (zn19_scag.isin(["2000", "2100", "2200", "2300", "2400", "2500", "2600", "2700"]), 1 / 5),
445
+ (zn19_scag.isin(["1900", "7777", "1500", "1233", "1210", "1211", "1212", "1213", "1247"]), 0),
446
+ (zn19_scag == zn19_scag, np.nan),
447
  ]
448
  )
449
 
450
+ # For LA parcels: use ZN19_CITY density if matched, otherwise fall through to SCAG
451
+ is_la = df["CITY"] == "Los Angeles"
452
+
453
+ df["current_density_du_per_ac"] = scag_density
454
+ df.loc[is_la, "current_density_du_per_ac"] = la_density
455
+
456
  return df
457
 
458
  def trim_around_stations(
 
499
  rsuffix="_stop",
500
  )
501
 
502
+ # Normalize Tier column name after sjoin
503
+ # - If parcels had Tier, sjoin renames buffer's Tier to Tier__stop
504
+ # and parcels' Tier to Tier_left (geopandas 1.x behavior)
505
+ # - If parcels didn't have Tier, sjoin keeps buffer's Tier as-is
506
+ if "Tier_left" in joined.columns:
507
+ # Parcels had Tier; use the buffer's Tier (Tier__stop)
508
+ joined["Tier"] = joined["Tier__stop"]
509
+ joined.drop(columns=["Tier_left", "Tier__stop"], inplace=True)
510
+ elif "Tier__stop" in joined.columns:
511
+ # Parcels didn't have Tier; rename buffer's Tier back
512
+ joined.rename(columns={"Tier__stop": "Tier"}, inplace=True)
513
+
514
  # Clip to buffer boundary
515
+ trimmed = gpd.overlay(joined, buffer_4326[["stop_id", "geometry"]], how="intersection")
516
  trimmed["buffer_zone_id"] = zone_name
517
  return trimmed
518
 
 
525
  Steps
526
  -----
527
  1. ``trim_around_stations`` for 200 ft, 1320 ft, 2640 ft.
528
+ 2. Create donuts: ¼mi \\\\ 200ft, ½mi \\\\ ¼mi.
529
  3. Concat all three zones.
530
  4. Assign zone density by ``(buffer_zone_id, Tier)``.
531
  5. Group by ``APN20`` → weighted ``new_density_du_per_ac``,
 
574
  zone_densities_series = pd.Series(ZONE_DENSITIES)
575
  residential["zone_density"] = residential.set_index(["buffer_zone_id", "Tier"]).index.map(zone_densities_series)
576
 
577
+ # --- 6. Aggregate by APN20 (vectorized) ---
578
+ # Total area per APN
579
+ area_agg = residential.groupby("APN20")["area_sqft"].sum().rename("area_sqft_total")
580
+ area_acres = area_agg / 43560
 
581
 
582
+ # Weighted density: sum(area_sqft * zone_density) / total_area
583
+ residential["area_x_density"] = residential["area_sqft"] * residential["zone_density"]
584
+ weighted_sum = residential.groupby("APN20")["area_x_density"].sum()
585
+ weighted_density = np.where(area_agg > 0, weighted_sum / area_agg, 0.0)
586
 
587
+ # Union geometry per APN
588
+ geom_agg = residential.groupby("APN20")["geometry"].agg(unary_union)
589
 
590
+ # First values for other columns
591
+ first_agg = residential.groupby("APN20").first()[
592
+ [
593
+ "current_density_du_per_ac",
594
+ "Tier",
595
+ "ZN19_CITY",
596
+ "ZN19_SCAG",
597
+ "COUNTY",
598
+ "CITY",
599
+ "buffer_zone_id",
600
+ ]
601
+ ]
 
 
 
 
602
 
603
+ # Build result
604
+ by_apn = gpd.GeoDataFrame(
605
+ {
606
+ "APN20": area_agg.index,
607
+ "geometry": geom_agg.values,
608
+ "area_acres": area_acres.values,
609
+ "new_density_du_per_ac": weighted_density,
610
+ "dwelling_units_new": weighted_density * area_acres.values,
611
+ "dwelling_units_current": first_agg["current_density_du_per_ac"].values * area_acres.values,
612
+ "current_density_du_per_ac": first_agg["current_density_du_per_ac"].values,
613
+ "Tier": first_agg["Tier"].values,
614
+ "ZN19_CITY": first_agg["ZN19_CITY"].values,
615
+ "ZN19_SCAG": first_agg["ZN19_SCAG"].values,
616
+ "COUNTY": first_agg["COUNTY"].values,
617
+ "CITY": first_agg["CITY"].values,
618
+ "buffer_zone_id": first_agg["buffer_zone_id"].values,
619
+ },
620
+ geometry="geometry",
621
+ crs=residential.crs,
622
  )
623
 
 
624
  print(f"Before APN dedup: {len(residential)} rows")
625
+ print(f"After APN dedup: {len(by_apn)} rows")
626
+ print(f"Total dwelling units (new): {by_apn['dwelling_units_new'].sum():.0f}")
627
+ return by_apn
628
 
629
  def join_scag_ca_parcels(
630
  scag_by_apn: gpd.GeoDataFrame,
 
993
  print(f"File created at: {tmp.name}")
994
 
995
  # Optional: Read back from the start
996
+ new_stops = parse_gtfs_zip(tmp.name, tier_overrides={"route-mourbghe-3": 2})
997
+ new_stops.explore(tiles="CartoDB positron")
998
  return (new_stops,)
999
 
1000
 
1001
  @app.cell
1002
  def _(new_stops):
1003
  buffers = create_half_mi_buffers(new_stops)
1004
+ buffers.explore(tiles="CartoDB positron")
1005
  return (buffers,)
1006
 
1007
 
 
 
 
 
 
 
 
1008
  @app.cell
1009
  def _(buffers):
1010
  ca_parcels = fetch_ca_parcels(buffers_gdf=buffers)
1011
+ scag_parcels = fetch_scag_parcels(buffers_gdf=buffers)
1012
+ scag_parcels[2000:4000].explore(tiles="CartoDB positron")
1013
+ return ca_parcels, scag_parcels
1014
 
1015
 
1016
  @app.cell
1017
  def _(scag_parcels):
1018
  scag_with_density = compute_scag_density(scag_parcels=scag_parcels)
1019
+ scag_with_density[2000:4000].explore("current_density_du_per_ac", tiles="CartoDB positron", vmax=50)
1020
  return (scag_with_density,)
1021
 
1022
 
1023
  @app.cell
1024
  def _(new_stops, scag_with_density):
1025
  scag_with_dwelling_units = create_buffer_donuts(stops_gdf=new_stops, scag_density=scag_with_density)
 
1026
  return (scag_with_dwelling_units,)
1027
 
1028
 
1029
  @app.cell
1030
+ def _(scag_with_dwelling_units):
1031
+ scag_with_dwelling_units[2000:4000].explore("buffer_zone_id", tiles="CartoDB positron")
1032
+ return
1033
+
1034
+
1035
+ @app.cell
1036
+ def _(scag_with_dwelling_units):
1037
+ scag_with_dwelling_units[2000:4000].explore("dwelling_units_new", tiles="CartoDB positron")
1038
+ return
1039
+
1040
+
1041
+ @app.cell
1042
+ def _(scag_with_dwelling_units):
1043
+ scag_with_dwelling_units
1044
+ return
1045
+
1046
+
1047
+ @app.cell
1048
+ def _(buffers, ca_parcels, scag_with_dwelling_units, stops):
1049
  joined_parcels = join_scag_ca_parcels(ca_parcels=ca_parcels, scag_by_apn=scag_with_dwelling_units)
1050
+ parcels_with_stops = assign_nearest_stop(joined_parcels, stops, buffers)
1051
+
1052
+ print("=== Step 9: Aggregate parcels to stops ===")
1053
+ stops_result = aggregate_parcels_to_stops(parcels_with_stops, stops)
1054
+
1055
+ {"stops": stops_result, "parcels": joined_parcels}
1056
  return
1057
 
1058
 
tests/test_gtfs_to_parcels.py CHANGED
@@ -6,6 +6,7 @@ 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,
@@ -499,22 +500,22 @@ class TestComputeScagDensity:
499
  def test_non_la_density(self):
500
  parcels = _make_parcels_gdf(
501
  [
502
- {"APN20": "1", "ZN19_SCAG": 1111, "CITY": "Other", "bbox": (0, 0, 100, 100)},
503
  ]
504
  )
505
  result = compute_scag_density(parcels)
506
- # 1111 → 10 du/ac
507
- assert result.iloc[0]["current_density_du_per_ac"] == 10
508
 
509
  def test_non_la_density_zero_default(self):
510
- """Unrecognized ZN19_SCAG codes should get 0."""
511
  parcels = _make_parcels_gdf(
512
  [
513
- {"APN20": "1", "ZN19_SCAG": 9999, "CITY": "Other", "bbox": (0, 0, 100, 100)},
514
  ]
515
  )
516
  result = compute_scag_density(parcels)
517
- assert result.iloc[0]["current_density_du_per_ac"] == 0
518
 
519
 
520
  # ---------------------------------------------------------------------------
 
6
  from pathlib import Path
7
 
8
  import geopandas as gpd
9
+ import numpy as np
10
  import pytest
11
  from sb79map import (
12
  aggregate_parcels_to_stops,
 
500
  def test_non_la_density(self):
501
  parcels = _make_parcels_gdf(
502
  [
503
+ {"APN20": "1", "ZN19_SCAG": 1111, "CITY": "Other", "bbox": (-118.3, 34.0, -118.2, 34.1)},
504
  ]
505
  )
506
  result = compute_scag_density(parcels)
507
+ # 1111 → 1 / area_acres (area-dependent)
508
+ assert result.iloc[0]["current_density_du_per_ac"] > 0
509
 
510
  def test_non_la_density_zero_default(self):
511
+ """Unrecognized ZN19_SCAG codes should get NaN (excluded downstream)."""
512
  parcels = _make_parcels_gdf(
513
  [
514
+ {"APN20": "1", "ZN19_SCAG": 9999, "CITY": "Other", "bbox": (-118.3, 34.0, -118.2, 34.1)},
515
  ]
516
  )
517
  result = compute_scag_density(parcels)
518
+ assert np.isnan(result.iloc[0]["current_density_du_per_ac"])
519
 
520
 
521
  # ---------------------------------------------------------------------------