Spaces:
Sleeping

dn commited on
Commit
29e1587
·
1 Parent(s): 2814b78

ready to present

Browse files
Files changed (2) hide show
  1. notebooks/sb79map.py +170 -117
  2. tests/test_gtfs_to_parcels.py +7 -28
notebooks/sb79map.py CHANGED
@@ -333,6 +333,9 @@ with app.setup(hide_code=True):
333
  )
334
  if parcels.empty:
335
  return parcels
 
 
 
336
  return parcels.set_crs("EPSG:4326").to_crs(f"EPSG:{wkid}")
337
 
338
  def fetch_ca_parcels(
@@ -359,9 +362,8 @@ with app.setup(hide_code=True):
359
 
360
  # Deduplicate by APN
361
  if "PARCEL_APN" in parcels.columns:
362
- before = len(parcels)
363
  parcels = parcels.groupby("PARCEL_APN", as_index=False).first()
364
- print(f"CA parcels: {before} → {len(parcels)} after APN dedup")
365
  return parcels.set_crs("EPSG:4326").to_crs(f"EPSG:{wkid}")
366
 
367
  def compute_scag_density(scag_parcels: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
@@ -530,14 +532,14 @@ with app.setup(hide_code=True):
530
  3. Concat all three zones.
531
  4. Assign zone density by ``(buffer_zone_id, Tier)``.
532
  5. Group by ``APN20`` → weighted ``new_density_du_per_ac``,
533
- ``dwelling_units_new``, ``dwelling_units_current``.
534
 
535
  Returns
536
  -------
537
  gpd.GeoDataFrame
538
  One row per APN20 with columns: ``APN20``, ``geometry``, ``area_acres``,
539
- ``new_density_du_per_ac``, ``dwelling_units_new``,
540
- ``dwelling_units_current``, ``current_density_du_per_ac``, ``Tier``,
541
  ``ZN19_CITY``, ``ZN19_SCAG``, ``COUNTY``, ``CITY``.
542
  """
543
  # --- 1. Trim for each buffer distance ---
@@ -583,7 +585,6 @@ with app.setup(hide_code=True):
583
  # Weighted density: sum(area_sqft * zone_density) / total_area
584
  residential["area_x_density"] = residential["area_sqft"] * residential["zone_density"]
585
  weighted_sum = residential.groupby("APN20")["area_x_density"].sum()
586
- weighted_density = np.where(area_agg > 0, weighted_sum / area_agg, 0.0)
587
 
588
  # Union geometry per APN
589
  geom_agg = residential.groupby("APN20")["geometry"].agg(unary_union)
@@ -600,6 +601,9 @@ with app.setup(hide_code=True):
600
  "buffer_zone_id",
601
  ]
602
  ]
 
 
 
603
 
604
  # Build result
605
  by_apn = gpd.GeoDataFrame(
@@ -608,8 +612,8 @@ with app.setup(hide_code=True):
608
  "geometry": geom_agg.values,
609
  "area_acres": area_acres.values,
610
  "new_density_du_per_ac": weighted_density,
611
- "dwelling_units_new": weighted_density * area_acres.values,
612
- "dwelling_units_current": first_agg["current_density_du_per_ac"].fillna(0).values * area_acres.values,
613
  "current_density_du_per_ac": first_agg["current_density_du_per_ac"].values,
614
  "Tier": first_agg["Tier"].values,
615
  "ZN19_CITY": first_agg["ZN19_CITY"].values,
@@ -621,10 +625,10 @@ with app.setup(hide_code=True):
621
  geometry="geometry",
622
  crs=residential.crs,
623
  )
624
-
625
- print(f"Before APN dedup: {len(residential)} rows")
626
- print(f"After APN dedup: {len(by_apn)} rows")
627
- print(f"Total dwelling units (new): {by_apn['dwelling_units_new'].sum():.0f}")
628
  return by_apn
629
 
630
  def join_scag_ca_parcels(
@@ -641,6 +645,10 @@ with app.setup(hide_code=True):
641
  "APN20",
642
  "ZN19_CITY",
643
  "ZN19_SCAG",
 
 
 
 
644
  "area_acres",
645
  "CITY",
646
  "COUNTY",
@@ -684,7 +692,7 @@ with app.setup(hide_code=True):
684
  stops_gdf: gpd.GeoDataFrame,
685
  buffers_gdf: gpd.GeoDataFrame,
686
  ) -> gpd.GeoDataFrame:
687
- """Spatially join parcels to stop buffers, then deduplicate multi-buffer parcels
688
  by assigning the nearest stop (by centroid distance).
689
 
690
  Parcels are clipped to their assigned buffer so only the intersecting
@@ -693,7 +701,7 @@ with app.setup(hide_code=True):
693
  Returns
694
  -------
695
  gpd.GeoDataFrame
696
- One row per ``(stop_id, APN)`` with a ``clipped_geom`` column.
697
  """
698
  # Reproject once
699
  parcels_3310 = parcels_gdf.to_crs("EPSG:3310")
@@ -715,29 +723,20 @@ with app.setup(hide_code=True):
715
  deduped = joined[~joined.index.duplicated(keep="first")].copy()
716
 
717
  if len(multi_ids) > 0:
718
- # ---- VECTORIZED nearest-stop assignment ----
719
- # Filter to multi-stop parcels only
720
  multi_rows = joined.loc[multi_ids].copy()
721
-
722
- # Get centroids for these parcels (aligned with multi_rows by index)
723
  centroids_3310 = parcels_3310.loc[multi_ids].geometry.centroid
724
-
725
- # Get stop points (indexed by stop_id)
726
  stops_3310 = stops_gdf.set_index("stop_id").to_crs("EPSG:3310").geometry
727
 
728
- # Compute distances: for each row, distance from parcel centroid to its stop
729
- # Vectorized: pass arrays of (centroids, stop_points)
730
  stop_points_for_rows = stops_3310.loc[multi_rows["stop_id"]].values
731
  centroid_array = centroids_3310.loc[multi_rows.index].values
732
 
733
- # Shapely distance (vectorized over arrays)
734
  multi_rows["distance"] = shapely.distance(centroid_array, stop_points_for_rows)
735
 
736
- # For each original parcel index, pick the stop with minimum distance
737
  nearest_idx = multi_rows.groupby(multi_rows.index)["distance"].idxmin()
738
  nearest = multi_rows.loc[nearest_idx, ["stop_id"]]
739
 
740
- # Assign back to deduped
741
  deduped.loc[nearest.index, "stop_id"] = nearest["stop_id"]
742
 
743
  # Clip parcels to assigned buffer
@@ -745,10 +744,14 @@ with app.setup(hide_code=True):
745
  deduped["buffer_geom"] = deduped["stop_id"].map(buffer_indexed["geometry"])
746
  deduped["clipped_geom"] = deduped.geometry.intersection(deduped["buffer_geom"])
747
 
748
- # Deduplicate by (stop_id, APN)
749
  apn_col = "PARCEL_APN" if "PARCEL_APN" in deduped.columns else "APN20"
750
- deduped = deduped.groupby(["stop_id", apn_col], as_index=False).first()
751
- deduped = deduped.set_crs("EPSG:3310")
 
 
 
 
752
  return deduped
753
 
754
  def aggregate_parcels_to_stops(
@@ -760,8 +763,8 @@ with app.setup(hide_code=True):
760
  For each stop:
761
  * ``parcel_acres`` — total clipped parcel area (using ``unary_union`` to
762
  avoid double-counting overlapping geometries).
763
- * ``additional_dwelling_units`` — sum of ``max(0, dwelling_units_new -
764
- dwelling_units_current)`` across parcels where new > current.
765
  * ``city``, ``county`` — mode (most common value) from associated parcels.
766
 
767
  Returns
@@ -779,10 +782,6 @@ with app.setup(hide_code=True):
779
  area_per_stop.columns = ["stop_id", "parcel_acres"]
780
 
781
  # Additional dwelling units per stop (only where new > current)
782
- parcels_with_stops["additional_du"] = np.maximum(
783
- 0,
784
- parcels_with_stops.get("dwelling_units_new", 0) - parcels_with_stops.get("dwelling_units_current", 0),
785
- )
786
  du_per_stop = (
787
  parcels_with_stops.groupby("stop_id")["additional_du"]
788
  .sum()
@@ -795,10 +794,10 @@ with app.setup(hide_code=True):
795
  return series.mode().iloc[0] if not series.mode().empty else ""
796
 
797
  city_per_stop = (
798
- parcels_with_stops.groupby("stop_id")["city"].agg(_mode).reset_index().rename(columns={"city": "city"})
799
  )
800
  county_per_stop = (
801
- parcels_with_stops.groupby("stop_id")["county"].agg(_mode).reset_index().rename(columns={"county": "county"})
802
  )
803
 
804
  # Merge back to stops
@@ -881,7 +880,7 @@ with app.setup(hide_code=True):
881
  return result
882
 
883
 
884
- @app.cell
885
  def _():
886
  from typing import Optional
887
 
@@ -904,43 +903,7 @@ def _():
904
  )
905
 
906
 
907
- @app.cell
908
- def _(STOPS_URL):
909
- stops = fetch_from_arcgis(url=STOPS_URL)
910
- stops
911
- return (stops,)
912
-
913
-
914
- @app.cell
915
- def _(MarkerCluster, PARCELS_URL, VectorGridProtobuf, folium, stops):
916
- m = folium.Map(location=[34.0617140033952, -118.314146442073], tiles="CartoDB Positron", zoom_start=10)
917
-
918
- VectorGridProtobuf(PARCELS_URL, "folium_layer_name").add_to(m)
919
- cluster = MarkerCluster(disable_clustering_at_zoom=10).add_to(m)
920
- for _, _row in stops.iterrows():
921
- color = "blue" if _row["Tier"] == 2 else "red"
922
- cluster.add_child(
923
- folium.CircleMarker(
924
- location=[_row.geometry.y, _row.geometry.x],
925
- radius=5,
926
- tooltip=folium.Tooltip(
927
- f"""
928
- Stop Name: {_row["stop_name"]}<br>
929
- Tier: {_row["Tier"]}<br>
930
- Routes: {_row["route_ids_served"]}<br>
931
- City: {_row["city"]}<br>
932
- County: {_row["county"]}<br>
933
- Route type: {_row["routetypes"]}"""
934
- ),
935
- color=color,
936
- fill_color=color,
937
- ).add_to(m)
938
- )
939
- m
940
- return
941
-
942
-
943
- @app.cell
944
  def _(mo):
945
 
946
  file_input = mo.ui.file(
@@ -958,9 +921,11 @@ def _(mo):
958
  return file_input, url_input
959
 
960
 
961
- @app.cell
962
  def _(Optional, file_input, url_input):
963
  # --- React to user input ---
 
 
964
  def get_gtfs_bytes() -> Optional[bytes]:
965
  """Return GTFS bytes from whichever input the user used."""
966
  if file_input.value:
@@ -982,14 +947,38 @@ def _(Optional, file_input, url_input):
982
  tmp.write(gtfs_data)
983
  tmp.flush() # Ensure data is written to disk
984
 
985
- print(f"File created at: {tmp.name}")
986
-
987
  # Optional: Read back from the start
988
  new_stops = parse_gtfs_zip(tmp.name, tier_overrides={"route-mourbghe-3": 2})
989
- new_stops.explore(tiles="CartoDB positron")
990
  return (new_stops,)
991
 
992
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
993
  @app.cell
994
  def _(new_stops):
995
  buffers = create_half_mi_buffers(new_stops)
@@ -997,86 +986,150 @@ def _(new_stops):
997
  return (buffers,)
998
 
999
 
1000
- @app.cell
1001
  def _(buffers):
1002
- ca_parcels = fetch_ca_parcels(buffers_gdf=buffers)
1003
  scag_parcels = fetch_scag_parcels(buffers_gdf=buffers)
1004
- scag_parcels[2000:4000].explore(tiles="CartoDB positron")
1005
- return ca_parcels, scag_parcels
1006
 
1007
 
1008
  @app.cell
1009
  def _(scag_parcels):
1010
- scag_with_density = compute_scag_density(scag_parcels=scag_parcels)
1011
- scag_with_density[2000:4000].explore("current_density_du_per_ac", tiles="CartoDB positron", vmax=50)
1012
- return (scag_with_density,)
1013
 
1014
 
1015
- @app.cell
1016
- def _(new_stops, scag_with_density):
 
 
1017
  scag_with_dwelling_units = create_buffer_donuts(stops_gdf=new_stops, scag_density=scag_with_density)
1018
  return (scag_with_dwelling_units,)
1019
 
1020
 
1021
  @app.cell
1022
- def _(scag_with_dwelling_units):
1023
- scag_with_dwelling_units[2000:4000].explore("buffer_zone_id", tiles="CartoDB positron")
1024
- return
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1025
 
 
1026
 
1027
- @app.cell
1028
- def _(scag_with_dwelling_units):
1029
- scag_with_dwelling_units[2000:4000].explore("dwelling_units_new", tiles="CartoDB positron")
1030
  return
1031
 
1032
 
1033
  @app.cell
1034
  def _(scag_with_dwelling_units):
1035
- scag_with_dwelling_units
 
 
 
 
1036
  return
1037
 
1038
 
1039
  @app.cell
1040
- def _(buffers, ca_parcels, scag_with_dwelling_units, stops):
1041
- joined_parcels = join_scag_ca_parcels(ca_parcels=ca_parcels, scag_by_apn=scag_with_dwelling_units)
1042
- parcels_with_stops = assign_nearest_stop(joined_parcels, stops, buffers)
1043
-
1044
- print("=== Step 9: Aggregate parcels to stops ===")
1045
- stops_result = aggregate_parcels_to_stops(parcels_with_stops, stops)
 
 
 
 
 
 
1046
 
1047
- {"stops": stops_result, "parcels": joined_parcels}
1048
  return
1049
 
1050
 
 
 
 
 
 
 
 
 
1051
  @app.cell
1052
- def _(ca_parcels):
1053
- ca_parcels
 
1054
  return
1055
 
1056
 
1057
  @app.cell
1058
- def _(scag_parcels):
1059
- scag_parcels
1060
  return
1061
 
1062
 
1063
- @app.cell
1064
- def _(ca_parcels, scag_with_density):
1065
- temp_joined = join_scag_ca_parcels(ca_parcels=ca_parcels, scag_by_apn=scag_with_density)
1066
- temp_joined
1067
- return (temp_joined,)
1068
 
1069
 
1070
- @app.cell
1071
- def _(buffers, new_stops, temp_joined):
1072
- temp_assigned = assign_nearest_stop(buffers_gdf=buffers, stops_gdf=new_stops, parcels_gdf=temp_joined)
1073
- temp_assigned.set_geometry("clipped_geom").set_crs("EPSG:3310")[:2000].explore()
1074
- return (temp_assigned,)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1075
 
1076
 
1077
  @app.cell
1078
- def _(temp_assigned):
1079
- compute_scag_density(scag_parcels=temp_assigned)
 
 
1080
  return
1081
 
1082
 
 
333
  )
334
  if parcels.empty:
335
  return parcels
336
+ if "APN20" in parcels.columns:
337
+ parcels = parcels.groupby("APN20", as_index=False).first()
338
+
339
  return parcels.set_crs("EPSG:4326").to_crs(f"EPSG:{wkid}")
340
 
341
  def fetch_ca_parcels(
 
362
 
363
  # Deduplicate by APN
364
  if "PARCEL_APN" in parcels.columns:
365
+ before = len(parcels) # noqa: F841
366
  parcels = parcels.groupby("PARCEL_APN", as_index=False).first()
 
367
  return parcels.set_crs("EPSG:4326").to_crs(f"EPSG:{wkid}")
368
 
369
  def compute_scag_density(scag_parcels: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
 
532
  3. Concat all three zones.
533
  4. Assign zone density by ``(buffer_zone_id, Tier)``.
534
  5. Group by ``APN20`` → weighted ``new_density_du_per_ac``,
535
+ ``new_dwelling_units``, ``current_dwelling_units``.
536
 
537
  Returns
538
  -------
539
  gpd.GeoDataFrame
540
  One row per APN20 with columns: ``APN20``, ``geometry``, ``area_acres``,
541
+ ``new_density_du_per_ac``, ``new_dwelling_units``,
542
+ ``current_dwelling_units``, ``current_density_du_per_ac``, ``Tier``,
543
  ``ZN19_CITY``, ``ZN19_SCAG``, ``COUNTY``, ``CITY``.
544
  """
545
  # --- 1. Trim for each buffer distance ---
 
585
  # Weighted density: sum(area_sqft * zone_density) / total_area
586
  residential["area_x_density"] = residential["area_sqft"] * residential["zone_density"]
587
  weighted_sum = residential.groupby("APN20")["area_x_density"].sum()
 
588
 
589
  # Union geometry per APN
590
  geom_agg = residential.groupby("APN20")["geometry"].agg(unary_union)
 
601
  "buffer_zone_id",
602
  ]
603
  ]
604
+ weighted_density = np.where(
605
+ (area_agg > 0) & (first_agg["current_density_du_per_ac"].notna()), weighted_sum / area_agg, np.nan
606
+ )
607
 
608
  # Build result
609
  by_apn = gpd.GeoDataFrame(
 
612
  "geometry": geom_agg.values,
613
  "area_acres": area_acres.values,
614
  "new_density_du_per_ac": weighted_density,
615
+ "new_dwelling_units": weighted_density * area_acres.values,
616
+ "current_dwelling_units": first_agg["current_density_du_per_ac"].values * area_acres.values,
617
  "current_density_du_per_ac": first_agg["current_density_du_per_ac"].values,
618
  "Tier": first_agg["Tier"].values,
619
  "ZN19_CITY": first_agg["ZN19_CITY"].values,
 
625
  geometry="geometry",
626
  crs=residential.crs,
627
  )
628
+ by_apn["additional_du"] = np.maximum(
629
+ 0,
630
+ by_apn.get("new_dwelling_units", 0) - by_apn.get("current_dwelling_units", 0),
631
+ )
632
  return by_apn
633
 
634
  def join_scag_ca_parcels(
 
645
  "APN20",
646
  "ZN19_CITY",
647
  "ZN19_SCAG",
648
+ "new_dwelling_units",
649
+ "current_dwelling_units",
650
+ "new_density_du_per_ac",
651
+ "current_density_du_per_ac",
652
  "area_acres",
653
  "CITY",
654
  "COUNTY",
 
692
  stops_gdf: gpd.GeoDataFrame,
693
  buffers_gdf: gpd.GeoDataFrame,
694
  ) -> gpd.GeoDataFrame:
695
+ """Spatially join parcels to stop buffers, then deduplicate multi‑buffer parcels
696
  by assigning the nearest stop (by centroid distance).
697
 
698
  Parcels are clipped to their assigned buffer so only the intersecting
 
701
  Returns
702
  -------
703
  gpd.GeoDataFrame
704
+ One row per ``(stop_id, APN)`` with ``clipped_geom`` as the active geometry.
705
  """
706
  # Reproject once
707
  parcels_3310 = parcels_gdf.to_crs("EPSG:3310")
 
723
  deduped = joined[~joined.index.duplicated(keep="first")].copy()
724
 
725
  if len(multi_ids) > 0:
726
+ # Vectorized nearest‑stop assignment
 
727
  multi_rows = joined.loc[multi_ids].copy()
 
 
728
  centroids_3310 = parcels_3310.loc[multi_ids].geometry.centroid
 
 
729
  stops_3310 = stops_gdf.set_index("stop_id").to_crs("EPSG:3310").geometry
730
 
 
 
731
  stop_points_for_rows = stops_3310.loc[multi_rows["stop_id"]].values
732
  centroid_array = centroids_3310.loc[multi_rows.index].values
733
 
 
734
  multi_rows["distance"] = shapely.distance(centroid_array, stop_points_for_rows)
735
 
 
736
  nearest_idx = multi_rows.groupby(multi_rows.index)["distance"].idxmin()
737
  nearest = multi_rows.loc[nearest_idx, ["stop_id"]]
738
 
739
+ # Assign the nearest stop back
740
  deduped.loc[nearest.index, "stop_id"] = nearest["stop_id"]
741
 
742
  # Clip parcels to assigned buffer
 
744
  deduped["buffer_geom"] = deduped["stop_id"].map(buffer_indexed["geometry"])
745
  deduped["clipped_geom"] = deduped.geometry.intersection(deduped["buffer_geom"])
746
 
747
+ # Ensure exactly one row per (stop_id, APN)
748
  apn_col = "PARCEL_APN" if "PARCEL_APN" in deduped.columns else "APN20"
749
+ deduped = deduped.drop_duplicates(subset=["stop_id", apn_col], keep="first")
750
+
751
+ # Set active geometry to clipped_geom and drop other geometry columns
752
+ deduped = deduped.set_geometry("clipped_geom", crs="EPSG:3310")
753
+ deduped = deduped.drop(columns=["geometry", "buffer_geom"], errors="ignore")
754
+
755
  return deduped
756
 
757
  def aggregate_parcels_to_stops(
 
763
  For each stop:
764
  * ``parcel_acres`` — total clipped parcel area (using ``unary_union`` to
765
  avoid double-counting overlapping geometries).
766
+ * ``additional_dwelling_units`` — sum of ``max(0, new_dwelling_units -
767
+ current_dwelling_units)`` across parcels where new > current.
768
  * ``city``, ``county`` — mode (most common value) from associated parcels.
769
 
770
  Returns
 
782
  area_per_stop.columns = ["stop_id", "parcel_acres"]
783
 
784
  # Additional dwelling units per stop (only where new > current)
 
 
 
 
785
  du_per_stop = (
786
  parcels_with_stops.groupby("stop_id")["additional_du"]
787
  .sum()
 
794
  return series.mode().iloc[0] if not series.mode().empty else ""
795
 
796
  city_per_stop = (
797
+ parcels_with_stops.groupby("stop_id")["CITY"].agg(_mode).reset_index().rename(columns={"CITY": "city"})
798
  )
799
  county_per_stop = (
800
+ parcels_with_stops.groupby("stop_id")["COUNTY"].agg(_mode).reset_index().rename(columns={"COUNTY": "county"})
801
  )
802
 
803
  # Merge back to stops
 
880
  return result
881
 
882
 
883
+ @app.cell(hide_code=True)
884
  def _():
885
  from typing import Optional
886
 
 
903
  )
904
 
905
 
906
+ @app.cell(hide_code=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
907
  def _(mo):
908
 
909
  file_input = mo.ui.file(
 
921
  return file_input, url_input
922
 
923
 
924
+ @app.cell(hide_code=True)
925
  def _(Optional, file_input, url_input):
926
  # --- React to user input ---
927
+ print("Getting GTFS zip file from github")
928
+
929
  def get_gtfs_bytes() -> Optional[bytes]:
930
  """Return GTFS bytes from whichever input the user used."""
931
  if file_input.value:
 
947
  tmp.write(gtfs_data)
948
  tmp.flush() # Ensure data is written to disk
949
 
 
 
950
  # Optional: Read back from the start
951
  new_stops = parse_gtfs_zip(tmp.name, tier_overrides={"route-mourbghe-3": 2})
 
952
  return (new_stops,)
953
 
954
 
955
+ @app.cell
956
+ def _(new_stops, prestops_gdf):
957
+ # Creating GIS from GTFS and assigning a Tier
958
+ # Tier 1: All subways and light rail or regional trains with more than 72 trains/day
959
+ # Tier 2: All light rail < 72 trains/day or regional trains > 48 trains/day
960
+ # All other transit stops are not covered by SB-79
961
+ # OC street car stops are Tier 2
962
+ def assign_tier_to_stops():
963
+ Tier_1 = prestops_gdf[
964
+ ((prestops_gdf["routetypes"].str.contains("2")) & (prestops_gdf["n_arrivals"] >= 72))
965
+ | (prestops_gdf["routetypes"].str.contains("1"))
966
+ ]
967
+ Tier_2 = prestops_gdf[
968
+ (
969
+ (prestops_gdf["routetypes"].str.contains("2"))
970
+ & ((prestops_gdf["n_arrivals"] < 72) & (prestops_gdf["n_arrivals"] >= 48))
971
+ )
972
+ | (prestops_gdf["routetypes"].str.contains("0"))
973
+ ]
974
+ Tier_1["Tier"] = 1
975
+ Tier_2["Tier"] = 2
976
+ stops_df = pd.concat([Tier_1, Tier_2]) # noqa: F841
977
+
978
+ new_stops.explore("Tier", tiles="CartoDB positron")
979
+ return
980
+
981
+
982
  @app.cell
983
  def _(new_stops):
984
  buffers = create_half_mi_buffers(new_stops)
 
986
  return (buffers,)
987
 
988
 
989
+ @app.cell(hide_code=True)
990
  def _(buffers):
 
991
  scag_parcels = fetch_scag_parcels(buffers_gdf=buffers)
992
+ return (scag_parcels,)
 
993
 
994
 
995
  @app.cell
996
  def _(scag_parcels):
997
+ # There are > 6000 parcels, which is too much to draw, can only show a subset, but calculations done on all parcels
998
+ scag_parcels[2000:6000].explore(tiles="CartoDB positron")
999
+ return
1000
 
1001
 
1002
+ @app.cell(hide_code=True)
1003
+ def _(new_stops, scag_parcels):
1004
+ scag_with_density = compute_scag_density(scag_parcels=scag_parcels)
1005
+
1006
  scag_with_dwelling_units = create_buffer_donuts(stops_gdf=new_stops, scag_density=scag_with_density)
1007
  return (scag_with_dwelling_units,)
1008
 
1009
 
1010
  @app.cell
1011
+ def _(
1012
+ buffer_200_4326,
1013
+ buffer_dist_ft,
1014
+ buffer_qtr_4326,
1015
+ parcels_gdf,
1016
+ scag_density,
1017
+ scag_with_dwelling_units,
1018
+ stops_gdf,
1019
+ ):
1020
+ # Create 200ft, quarter mi, and half mi zones around the stations
1021
+ def create_donuts():
1022
+ def trim_around_stations():
1023
+ buffer_df = stops_gdf.to_crs("EPSG:2229").geometry.buffer(buffer_dist_ft)
1024
+ joined = gpd.sjoin( # noqa: F841
1025
+ parcels_gdf.to_crs("EPSG:4326"),
1026
+ buffer_df.to_crs("EPSG:4326"),
1027
+ predicate="intersects",
1028
+ )
1029
+
1030
+ trim_200 = trim_around_stations(scag_density, stops_gdf, 200)
1031
+ trim_qtr = trim_around_stations(scag_density, stops_gdf, 1320)
1032
+ trim_half = trim_around_stations(scag_density, stops_gdf, 2640)
1033
+ qtrmile_donut = gpd.overlay(trim_qtr, buffer_200_4326, how="difference")
1034
+ halfmile_donut = gpd.overlay(trim_half, buffer_qtr_4326, how="difference")
1035
 
1036
+ residential = gpd.GeoDataFrame(pd.concat([trim_200, qtrmile_donut, halfmile_donut], ignore_index=True)) # noqa: F841
1037
 
1038
+ scag_with_dwelling_units[2000:6000].explore("buffer_zone_id", tiles="CartoDB positron")
 
 
1039
  return
1040
 
1041
 
1042
  @app.cell
1043
  def _(scag_with_dwelling_units):
1044
+ # The new densities will be
1045
+ # 200ft: 120 du/ac
1046
+ # 1/4 mi: 100 du/ac
1047
+ # 1/2 mi: 80 du/ac
1048
+ scag_with_dwelling_units[2000:6000].explore("new_density_du_per_ac", tiles="CartoDB positron")
1049
  return
1050
 
1051
 
1052
  @app.cell
1053
+ def _(area_acres, df, scag_with_dwelling_units):
1054
+ # Translating zoning code to density units to get the density units
1055
+ # https://scag-spm-documentation.readthedocs.io/en/latest/scag_lu_codes_description/
1056
+ def calc_current_density():
1057
+ la_density = df["ZN19_CITY"].case_when( # noqa: F841
1058
+ [
1059
+ (df["ZN19_CITY"] == "1122", 43560 / 1500),
1060
+ (df["ZN19_CITY"] == "1140", 3 / area_acres.replace(0, np.nan)),
1061
+ (df["ZN19_CITY"] == "1123", 18),
1062
+ (df["ZN19_CITY"] == "1124", 60),
1063
+ ]
1064
+ )
1065
 
1066
+ scag_with_dwelling_units[2000:6000].explore("current_density_du_per_ac", tiles="CartoDB positron")
1067
  return
1068
 
1069
 
1070
+ @app.cell(hide_code=True)
1071
+ def _(buffers, new_stops, scag_with_dwelling_units):
1072
+ parcels_with_stops = assign_nearest_stop(scag_with_dwelling_units, new_stops, buffers)
1073
+
1074
+ stops_result = aggregate_parcels_to_stops(parcels_with_stops, new_stops)
1075
+ return parcels_with_stops, stops_result
1076
+
1077
+
1078
  @app.cell
1079
+ def _(parcels_with_stops):
1080
+ # Showing the potential new dwelling units = new_du - current_du
1081
+ parcels_with_stops[2000:6000].explore("additional_du", tiles="CartoDB positron")
1082
  return
1083
 
1084
 
1085
  @app.cell
1086
+ def _(stops_result):
1087
+ print(f"Total potential dwelling units for OC street car: {int(stops_result['additional_dwelling_units'].sum())}")
1088
  return
1089
 
1090
 
1091
+ @app.cell(hide_code=True)
1092
+ def _(STOPS_URL):
1093
+ stops = fetch_from_arcgis(url=STOPS_URL)
1094
+ stops = stops.set_crs("EPSG:4326")
1095
+ return (stops,)
1096
 
1097
 
1098
+ @app.cell(hide_code=True)
1099
+ def _(MarkerCluster, PARCELS_URL, VectorGridProtobuf, folium, stops):
1100
+ m = folium.Map(location=[34.0617140033952, -118.314146442073], tiles="CartoDB Positron", zoom_start=5)
1101
+
1102
+ VectorGridProtobuf(PARCELS_URL, "folium_layer_name").add_to(m)
1103
+ cluster = MarkerCluster(disable_clustering_at_zoom=10).add_to(m)
1104
+
1105
+ for _, _row in stops.iterrows():
1106
+ color = "blue" if _row["Tier"] == 2 else "red"
1107
+ cluster.add_child(
1108
+ folium.CircleMarker(
1109
+ location=[_row.geometry.y, _row.geometry.x],
1110
+ radius=5,
1111
+ tooltip=folium.Tooltip(
1112
+ f"""
1113
+ Stop Name: {_row["stop_name"]}<br>
1114
+ Tier: {_row["Tier"]}<br>
1115
+ Routes: {_row["route_ids_served"]}<br>
1116
+ City: {_row["city"]}<br>
1117
+ County: {_row["county"]}<br>
1118
+ Route type: {_row["routetypes"]}<br>
1119
+ Parcel acres: {_row["parcel_acres"]}"""
1120
+ ),
1121
+ color=color,
1122
+ fill_color=color,
1123
+ ).add_to(m)
1124
+ )
1125
+ return (m,)
1126
 
1127
 
1128
  @app.cell
1129
+ def _(m):
1130
+ # We only need the GTFS transit schedules and this notebook will calculate
1131
+ # the potential that SB 79 has for California housing crisis
1132
+ m
1133
  return
1134
 
1135
 
tests/test_gtfs_to_parcels.py CHANGED
@@ -586,8 +586,8 @@ class TestCreateBufferDonuts:
586
  result = create_buffer_donuts(stops, parcels)
587
  assert len(result) >= 1
588
  assert "new_density_du_per_ac" in result.columns
589
- assert "dwelling_units_new" in result.columns
590
- assert "dwelling_units_current" in result.columns
591
  assert result["new_density_du_per_ac"].iloc[0] > 0
592
 
593
 
@@ -674,10 +674,11 @@ class TestAggregateParcelsToStops:
674
  {
675
  "stop_id": ["A"],
676
  "clipped_geom": [box(-118.001, 33.999, -117.999, 34.001)],
677
- "dwelling_units_new": [100],
678
- "dwelling_units_current": [50],
679
- "city": ["LOS ANGELES"],
680
- "county": ["LOS ANGELES"],
 
681
  "geometry": [box(-118.001, 33.999, -117.999, 34.001)],
682
  },
683
  crs="EPSG:4326",
@@ -689,25 +690,3 @@ class TestAggregateParcelsToStops:
689
  assert result["additional_dwelling_units"].iloc[0] == 50 # 100 - 50
690
  assert result["city"].iloc[0] == "LOS ANGELES"
691
  assert result["county"].iloc[0] == "LOS ANGELES"
692
-
693
- def test_no_additional_units_when_current_exceeds_new(self):
694
- stops = _make_stops_gdf(
695
- [
696
- {"stop_id": "A", "Tier": 1, "lat": 34.0, "lon": -118.0},
697
- ]
698
- )
699
- parcels = gpd.GeoDataFrame(
700
- {
701
- "stop_id": ["A"],
702
- "clipped_geom": [box(-118.001, 33.999, -117.999, 34.001)],
703
- "dwelling_units_new": [30],
704
- "dwelling_units_current": [100],
705
- "city": ["LA"],
706
- "county": ["LA"],
707
- "geometry": [box(-118.001, 33.999, -117.999, 34.001)],
708
- },
709
- crs="EPSG:4326",
710
- )
711
-
712
- result = aggregate_parcels_to_stops(parcels, stops)
713
- assert result["additional_dwelling_units"].iloc[0] == 0 # max(0, 30-100) = 0
 
586
  result = create_buffer_donuts(stops, parcels)
587
  assert len(result) >= 1
588
  assert "new_density_du_per_ac" in result.columns
589
+ assert "new_dwelling_units" in result.columns
590
+ assert "current_dwelling_units" in result.columns
591
  assert result["new_density_du_per_ac"].iloc[0] > 0
592
 
593
 
 
674
  {
675
  "stop_id": ["A"],
676
  "clipped_geom": [box(-118.001, 33.999, -117.999, 34.001)],
677
+ "new_dwelling_units": [100],
678
+ "current_dwelling_units": [50],
679
+ "additional_du": [50],
680
+ "CITY": ["LOS ANGELES"],
681
+ "COUNTY": ["LOS ANGELES"],
682
  "geometry": [box(-118.001, 33.999, -117.999, 34.001)],
683
  },
684
  crs="EPSG:4326",
 
690
  assert result["additional_dwelling_units"].iloc[0] == 50 # 100 - 50
691
  assert result["city"].iloc[0] == "LOS ANGELES"
692
  assert result["county"].iloc[0] == "LOS ANGELES"