Spaces:
Sleeping
Sleeping
dn commited on
Commit ·
acf4d51
1
Parent(s): 93255ff
refactoring sb79map
Browse files- notebooks/sb79map.py +16 -258
- pyproject.toml +6 -5
- shared/__init__.py +0 -0
- shared/api/__init__.py +0 -0
- {notebooks/src → shared/api}/arcgis.py +0 -0
- shared/pipelines/sb79.py +168 -0
- shared/utils/__init__.py +0 -0
- {notebooks → shared/utils}/constants.py +0 -0
- tests/test_arcgis.py +2 -1
- tests/test_gtfs_to_parcels.py +25 -37
- uv.lock +42 -0
notebooks/sb79map.py
CHANGED
|
@@ -12,207 +12,32 @@
|
|
| 12 |
|
| 13 |
import marimo
|
| 14 |
|
|
|
|
|
|
|
| 15 |
__generated_with = "0.23.5"
|
| 16 |
app = marimo.App()
|
| 17 |
|
| 18 |
with app.setup(hide_code=True):
|
| 19 |
-
import csv # noqa: I001
|
| 20 |
-
import io
|
| 21 |
import tempfile
|
| 22 |
-
import
|
| 23 |
-
from collections import defaultdict
|
| 24 |
-
from pathlib import Path
|
| 25 |
-
from typing import Any
|
| 26 |
-
from constants import SCAG_PARCELS_URL
|
| 27 |
-
from constants import CA_PARCELS_URL, HALF_MI_M, SCAG_OUT_FIELDS, ZONE_DENSITIES
|
| 28 |
-
from src.arcgis import fetch_from_arcgis
|
| 29 |
|
|
|
|
| 30 |
import geopandas as gpd
|
|
|
|
|
|
|
|
|
|
| 31 |
import numpy as np
|
| 32 |
import pandas as pd
|
| 33 |
import requests
|
| 34 |
import shapely
|
|
|
|
| 35 |
from shapely import unary_union
|
| 36 |
-
from typing import Optional
|
| 37 |
|
| 38 |
-
import
|
| 39 |
-
import
|
| 40 |
-
from folium.plugins import MarkerCluster, VectorGridProtobuf
|
| 41 |
-
import mapclassify # noqa: f401
|
| 42 |
-
import matplotlib # noqa: f401
|
| 43 |
|
| 44 |
__generated_with = "0.23.5"
|
| 45 |
|
| 46 |
-
def parse_gtfs_zip(
|
| 47 |
-
gtfs_path: str | Path,
|
| 48 |
-
tier_overrides: dict[str, int] | None = None,
|
| 49 |
-
) -> gpd.GeoDataFrame:
|
| 50 |
-
"""Parse a GTFS zip and return a GeoDataFrame of Tier-1/Tier-2 parent stations.
|
| 51 |
-
|
| 52 |
-
Parameters
|
| 53 |
-
----------
|
| 54 |
-
gtfs_path:
|
| 55 |
-
Path to a ``.zip`` file containing standard GTFS tables.
|
| 56 |
-
tier_overrides:
|
| 57 |
-
Optional mapping ``{route_id: tier}`` to force a specific tier for
|
| 58 |
-
a route regardless of the automatic logic.
|
| 59 |
-
|
| 60 |
-
Returns
|
| 61 |
-
-------
|
| 62 |
-
gpd.GeoDataFrame
|
| 63 |
-
Only stops that qualify as Tier 1 or Tier 2 are returned.
|
| 64 |
-
"""
|
| 65 |
-
z = zipfile.ZipFile(gtfs_path)
|
| 66 |
-
|
| 67 |
-
routes = list(csv.DictReader(io.StringIO(z.read("routes.txt").decode("utf-8"))))
|
| 68 |
-
route_info: dict[str, dict[str, Any]] = {}
|
| 69 |
-
for r in routes:
|
| 70 |
-
route_info[r["route_id"]] = r
|
| 71 |
-
|
| 72 |
-
cal = list(csv.DictReader(io.StringIO(z.read("calendar.txt").decode("utf-8"))))
|
| 73 |
-
weekday_services = {c["service_id"] for c in cal if c["monday"] == "1"}
|
| 74 |
-
|
| 75 |
-
trips = list(csv.DictReader(io.StringIO(z.read("trips.txt").decode("utf-8"))))
|
| 76 |
-
trip_to_route: dict[str, str] = {}
|
| 77 |
-
route_dir_counts: dict[str, dict[str, int]] = defaultdict(lambda: {"0": 0, "1": 0})
|
| 78 |
-
for t in trips:
|
| 79 |
-
trip_to_route[t["trip_id"]] = t["route_id"]
|
| 80 |
-
if t["service_id"] in weekday_services:
|
| 81 |
-
route_dir_counts[t["route_id"]][t["direction_id"]] += 1
|
| 82 |
-
|
| 83 |
-
num_wkday = len(weekday_services)
|
| 84 |
-
|
| 85 |
-
route_trains_per_day: dict[str, int] = {}
|
| 86 |
-
for rid, dirs in route_dir_counts.items():
|
| 87 |
-
route_trains_per_day[rid] = round((dirs.get("0", 0) + dirs.get("1", 0)) / num_wkday)
|
| 88 |
-
|
| 89 |
-
stops = list(csv.DictReader(io.StringIO(z.read("stops.txt").decode("utf-8"))))
|
| 90 |
-
stops_df = pd.DataFrame(stops)
|
| 91 |
-
|
| 92 |
-
parent_stations = stops_df[stops_df["location_type"] == "1"].copy()
|
| 93 |
-
boarding_stops = stops_df[stops_df["location_type"] == "0"].copy()
|
| 94 |
-
|
| 95 |
-
# If there are no parent stations (location_type=1), treat all boarding
|
| 96 |
-
# stops (location_type=0) as individual stations. Some GTFS feeds
|
| 97 |
-
# (e.g. OC Streetcar) only have location_type=0 stops with no parent
|
| 98 |
-
# station hierarchy.
|
| 99 |
-
if parent_stations.empty:
|
| 100 |
-
parent_stations = boarding_stops.copy()
|
| 101 |
-
boarding_stops = gpd.GeoDataFrame() # no routes to propagate
|
| 102 |
-
|
| 103 |
-
stop_times = list(csv.DictReader(io.StringIO(z.read("stop_times.txt").decode("utf-8"))))
|
| 104 |
-
stop_to_routes: dict[str, set[str]] = defaultdict(set)
|
| 105 |
-
for st in stop_times:
|
| 106 |
-
rid = trip_to_route.get(st["trip_id"])
|
| 107 |
-
if rid:
|
| 108 |
-
stop_to_routes[st["stop_id"]].add(rid)
|
| 109 |
-
|
| 110 |
-
parent_to_routes: dict[str, set[str]] = defaultdict(set)
|
| 111 |
-
for _, bs in boarding_stops.iterrows():
|
| 112 |
-
parent = bs["parent_station"] if "parent_station" in bs else None
|
| 113 |
-
if parent and parent in set(parent_stations["stop_id"]):
|
| 114 |
-
parent_to_routes[parent].update(stop_to_routes.get(bs["stop_id"], set()))
|
| 115 |
-
|
| 116 |
-
for _, ps in parent_stations.iterrows():
|
| 117 |
-
parent_to_routes[ps["stop_id"]].update(stop_to_routes.get(ps["stop_id"], set()))
|
| 118 |
-
|
| 119 |
-
# --- Build the output GeoDataFrame ---
|
| 120 |
-
records: list[dict[str, Any]] = []
|
| 121 |
-
for _, ps in parent_stations.iterrows():
|
| 122 |
-
pid = ps["stop_id"]
|
| 123 |
-
served_routes = sorted(parent_to_routes.get(pid, set()))
|
| 124 |
-
if not served_routes:
|
| 125 |
-
continue
|
| 126 |
-
|
| 127 |
-
# Collect route types and count arrivals
|
| 128 |
-
types: set[str] = set()
|
| 129 |
-
total_arrivals = 0
|
| 130 |
-
agencies: set[str] = set()
|
| 131 |
-
for rid in served_routes:
|
| 132 |
-
ri = route_info.get(rid, {})
|
| 133 |
-
types.add(ri.get("route_type", ""))
|
| 134 |
-
total_arrivals += route_trains_per_day.get(rid, 0)
|
| 135 |
-
agencies.add(ri.get("agency_id", ""))
|
| 136 |
-
|
| 137 |
-
routetypes_str = ",".join(sorted(types, key=int))
|
| 138 |
-
|
| 139 |
-
# Tier assignment
|
| 140 |
-
has_type_1 = "1" in types
|
| 141 |
-
has_type_0 = "0" in types
|
| 142 |
-
has_type_2 = "2" in types
|
| 143 |
-
|
| 144 |
-
tier: int | None = None
|
| 145 |
-
if has_type_1:
|
| 146 |
-
tier = 1
|
| 147 |
-
elif (has_type_0 or has_type_2) and total_arrivals >= 72:
|
| 148 |
-
tier = 1
|
| 149 |
-
elif has_type_2 and 48 <= total_arrivals < 72:
|
| 150 |
-
tier = 2
|
| 151 |
-
elif has_type_0 and total_arrivals < 72:
|
| 152 |
-
tier = 2
|
| 153 |
-
|
| 154 |
-
# Apply overrides
|
| 155 |
-
if tier_overrides:
|
| 156 |
-
for rid in served_routes:
|
| 157 |
-
if rid in tier_overrides:
|
| 158 |
-
tier = tier_overrides[rid]
|
| 159 |
-
break
|
| 160 |
-
|
| 161 |
-
if tier is None:
|
| 162 |
-
continue # skip stops that don't qualify
|
| 163 |
-
|
| 164 |
-
records.append(
|
| 165 |
-
{
|
| 166 |
-
"stop_id": pid,
|
| 167 |
-
"stop_name": ps.get("stop_name", ""),
|
| 168 |
-
"stop_lat": float(ps["stop_lat"]),
|
| 169 |
-
"stop_lon": float(ps["stop_lon"]),
|
| 170 |
-
"Tier": tier,
|
| 171 |
-
"agency": ",".join(sorted(agencies)),
|
| 172 |
-
"route_ids_served": ",".join(served_routes),
|
| 173 |
-
"routetypes": routetypes_str,
|
| 174 |
-
"n_arrivals": total_arrivals,
|
| 175 |
-
}
|
| 176 |
-
)
|
| 177 |
-
|
| 178 |
-
if not records:
|
| 179 |
-
return gpd.GeoDataFrame(
|
| 180 |
-
{
|
| 181 |
-
"stop_id": pd.Series(dtype=str),
|
| 182 |
-
"stop_name": pd.Series(dtype=str),
|
| 183 |
-
"Tier": pd.Series(dtype=int),
|
| 184 |
-
"agency": pd.Series(dtype=str),
|
| 185 |
-
"route_ids_served": pd.Series(dtype=str),
|
| 186 |
-
"routetypes": pd.Series(dtype=str),
|
| 187 |
-
"n_arrivals": pd.Series(dtype=int),
|
| 188 |
-
},
|
| 189 |
-
geometry=pd.Series(dtype=object),
|
| 190 |
-
crs="EPSG:4326",
|
| 191 |
-
)
|
| 192 |
-
|
| 193 |
-
result = gpd.GeoDataFrame(
|
| 194 |
-
records,
|
| 195 |
-
geometry=gpd.points_from_xy(
|
| 196 |
-
[r["stop_lon"] for r in records],
|
| 197 |
-
[r["stop_lat"] for r in records],
|
| 198 |
-
crs="EPSG:4326",
|
| 199 |
-
),
|
| 200 |
-
)
|
| 201 |
-
result.drop(columns=["stop_lat", "stop_lon"], inplace=True)
|
| 202 |
-
return result
|
| 203 |
-
|
| 204 |
-
def create_half_mi_buffers(stops_gdf: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
|
| 205 |
-
"""Create 0.5-mile (804.7 m) circular buffers around each stop.
|
| 206 |
-
|
| 207 |
-
Returns a GeoDataFrame in EPSG:3310 with the same ``stop_id`` index.
|
| 208 |
-
"""
|
| 209 |
-
buffers = gpd.GeoDataFrame(
|
| 210 |
-
{"stop_id": stops_gdf["stop_id"].values},
|
| 211 |
-
geometry=stops_gdf.to_crs("EPSG:3310").geometry.buffer(HALF_MI_M, resolution=8),
|
| 212 |
-
crs="EPSG:3310",
|
| 213 |
-
)
|
| 214 |
-
return buffers
|
| 215 |
-
|
| 216 |
def fetch_scag_parcels(
|
| 217 |
buffers_gdf: gpd.GeoDataFrame,
|
| 218 |
url: str = SCAG_PARCELS_URL,
|
|
@@ -710,77 +535,6 @@ with app.setup(hide_code=True):
|
|
| 710 |
|
| 711 |
return result
|
| 712 |
|
| 713 |
-
def full_pipeline(
|
| 714 |
-
gtfs_zip_path: str | Path,
|
| 715 |
-
tier_overrides: dict[str, int] | None = None,
|
| 716 |
-
out_path: str | Path | None = None,
|
| 717 |
-
scag_url: str = SCAG_PARCELS_URL,
|
| 718 |
-
ca_url: str = CA_PARCELS_URL,
|
| 719 |
-
scag_out_fields: str = SCAG_OUT_FIELDS,
|
| 720 |
-
) -> dict[str, gpd.GeoDataFrame]:
|
| 721 |
-
"""Run the complete GTFS-to-parcels pipeline.
|
| 722 |
-
|
| 723 |
-
Parameters
|
| 724 |
-
----------
|
| 725 |
-
gtfs_zip_path:
|
| 726 |
-
Path to a GTFS ``.zip`` file.
|
| 727 |
-
tier_overrides:
|
| 728 |
-
Optional ``{route_id: tier}`` overrides.
|
| 729 |
-
out_path:
|
| 730 |
-
If provided, save stops and parcels to GeoJSON files here.
|
| 731 |
-
scag_url:
|
| 732 |
-
SCAG parcel endpoint URL.
|
| 733 |
-
ca_url:
|
| 734 |
-
CA statewide parcel endpoint URL.
|
| 735 |
-
scag_out_fields:
|
| 736 |
-
Fields to request from the SCAG endpoint.
|
| 737 |
-
|
| 738 |
-
Returns
|
| 739 |
-
-------
|
| 740 |
-
dict
|
| 741 |
-
``{"stops": stops_gdf, "parcels": ca_parcels_output}``
|
| 742 |
-
"""
|
| 743 |
-
print("=== Step 1: Parse GTFS ===")
|
| 744 |
-
stops = parse_gtfs_zip(gtfs_zip_path, tier_overrides=tier_overrides)
|
| 745 |
-
print(f" {len(stops)} stops with Tier 1 or 2")
|
| 746 |
-
|
| 747 |
-
print("=== Step 2: Create 0.5-mi buffers ===")
|
| 748 |
-
buffers = create_half_mi_buffers(stops)
|
| 749 |
-
|
| 750 |
-
print("=== Step 3: Fetch SCAG parcels ===")
|
| 751 |
-
scag = fetch_scag_parcels(buffers, url=scag_url, out_fields=scag_out_fields)
|
| 752 |
-
print(f" {len(scag)} SCAG parcels")
|
| 753 |
-
|
| 754 |
-
print("=== Step 4: Compute SCAG density ===")
|
| 755 |
-
scag_density = compute_scag_density(scag)
|
| 756 |
-
|
| 757 |
-
print("=== Step 5: Create buffer donuts & weighted density ===")
|
| 758 |
-
scag_by_apn = create_buffer_donuts(stops, scag_density)
|
| 759 |
-
|
| 760 |
-
print("=== Step 6: Fetch CA parcels ===")
|
| 761 |
-
ca = fetch_ca_parcels(buffers, url=ca_url)
|
| 762 |
-
print(f" {len(ca)} CA parcels")
|
| 763 |
-
|
| 764 |
-
print("=== Step 7: Join SCAG → CA parcels ===")
|
| 765 |
-
combined = join_scag_ca_parcels(scag_by_apn, ca)
|
| 766 |
-
|
| 767 |
-
print("=== Step 8: Trim to 0.5-mi buffer & assign nearest stop ===")
|
| 768 |
-
parcels_with_stops = assign_nearest_stop(combined, stops, buffers)
|
| 769 |
-
|
| 770 |
-
print("=== Step 9: Aggregate parcels to stops ===")
|
| 771 |
-
stops_result = aggregate_parcels_to_stops(parcels_with_stops, stops)
|
| 772 |
-
|
| 773 |
-
result = {"stops": stops_result, "parcels": combined}
|
| 774 |
-
|
| 775 |
-
if out_path:
|
| 776 |
-
out = Path(out_path)
|
| 777 |
-
out.mkdir(parents=True, exist_ok=True)
|
| 778 |
-
stops_result.to_file(out / "stops.geojson", driver="GeoJSON")
|
| 779 |
-
combined.to_file(out / "parcels.geojson", driver="GeoJSON")
|
| 780 |
-
print(f" Saved to {out}")
|
| 781 |
-
|
| 782 |
-
return result
|
| 783 |
-
|
| 784 |
PARCELS_URL = "https://vectortileservices3.arcgis.com/NaFf4UaPo3IgQXqn/arcgis/rest/services/sb79_transit_parcels/VectorTileServer/tile/{z}/{y}/{x}.pbf"
|
| 785 |
STOPS_URL = (
|
| 786 |
"https://services3.arcgis.com/NaFf4UaPo3IgQXqn/ArcGIS/rest/services/sb79_transit_stations/FeatureServer/0/query"
|
|
@@ -840,7 +594,7 @@ def _(file_input, url_input):
|
|
| 840 |
tmp.flush() # Ensure data is written to disk
|
| 841 |
|
| 842 |
# Optional: Read back from the start
|
| 843 |
-
new_stops =
|
| 844 |
return (new_stops,)
|
| 845 |
|
| 846 |
|
|
@@ -873,7 +627,11 @@ def _(new_stops, prestops_gdf):
|
|
| 873 |
|
| 874 |
@app.cell
|
| 875 |
def _(new_stops):
|
| 876 |
-
buffers =
|
|
|
|
|
|
|
|
|
|
|
|
|
| 877 |
buffers.explore(tiles="CartoDB positron")
|
| 878 |
return (buffers,)
|
| 879 |
|
|
|
|
| 12 |
|
| 13 |
import marimo
|
| 14 |
|
| 15 |
+
from shared.pipelines.sb79 import assign_tier_to_stops_from_gtfs
|
| 16 |
+
|
| 17 |
__generated_with = "0.23.5"
|
| 18 |
app = marimo.App()
|
| 19 |
|
| 20 |
with app.setup(hide_code=True):
|
|
|
|
|
|
|
| 21 |
import tempfile
|
| 22 |
+
from typing import Optional
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
+
import folium
|
| 25 |
import geopandas as gpd
|
| 26 |
+
import mapclassify # noqa: f401
|
| 27 |
+
import marimo as mo
|
| 28 |
+
import matplotlib # noqa: f401
|
| 29 |
import numpy as np
|
| 30 |
import pandas as pd
|
| 31 |
import requests
|
| 32 |
import shapely
|
| 33 |
+
from folium.plugins import MarkerCluster, VectorGridProtobuf
|
| 34 |
from shapely import unary_union
|
|
|
|
| 35 |
|
| 36 |
+
from shared.api.arcgis import fetch_from_arcgis
|
| 37 |
+
from shared.utils.constants import CA_PARCELS_URL, HALF_MI_M, SCAG_OUT_FIELDS, SCAG_PARCELS_URL, ZONE_DENSITIES
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
__generated_with = "0.23.5"
|
| 40 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
def fetch_scag_parcels(
|
| 42 |
buffers_gdf: gpd.GeoDataFrame,
|
| 43 |
url: str = SCAG_PARCELS_URL,
|
|
|
|
| 535 |
|
| 536 |
return result
|
| 537 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 538 |
PARCELS_URL = "https://vectortileservices3.arcgis.com/NaFf4UaPo3IgQXqn/arcgis/rest/services/sb79_transit_parcels/VectorTileServer/tile/{z}/{y}/{x}.pbf"
|
| 539 |
STOPS_URL = (
|
| 540 |
"https://services3.arcgis.com/NaFf4UaPo3IgQXqn/ArcGIS/rest/services/sb79_transit_stations/FeatureServer/0/query"
|
|
|
|
| 594 |
tmp.flush() # Ensure data is written to disk
|
| 595 |
|
| 596 |
# Optional: Read back from the start
|
| 597 |
+
new_stops = assign_tier_to_stops_from_gtfs(tmp.name, tier_overrides={"route-mourbghe-3": 2})
|
| 598 |
return (new_stops,)
|
| 599 |
|
| 600 |
|
|
|
|
| 627 |
|
| 628 |
@app.cell
|
| 629 |
def _(new_stops):
|
| 630 |
+
buffers = gpd.GeoDataFrame(
|
| 631 |
+
{"stop_id": new_stops["stop_id"].values},
|
| 632 |
+
geometry=new_stops.to_crs("EPSG:3310").geometry.buffer(HALF_MI_M, resolution=8),
|
| 633 |
+
crs="EPSG:3310",
|
| 634 |
+
)
|
| 635 |
buffers.explore(tiles="CartoDB positron")
|
| 636 |
return (buffers,)
|
| 637 |
|
pyproject.toml
CHANGED
|
@@ -10,6 +10,7 @@ dependencies = [
|
|
| 10 |
"folium>=0.20.0",
|
| 11 |
"geopandas>=1.1.3",
|
| 12 |
"geopolars>=0.1.0a4",
|
|
|
|
| 13 |
"ipyleaflet>=0.20.0",
|
| 14 |
"mapclassify>=2.10.0",
|
| 15 |
"marimo[lsp,recommended]>=0.23.5",
|
|
@@ -45,15 +46,15 @@ ignore = [
|
|
| 45 |
"F401"
|
| 46 |
]
|
| 47 |
|
| 48 |
-
[tool.marimo.runtime]
|
| 49 |
-
pythonpath = ["notebooks"]
|
| 50 |
-
|
| 51 |
[tool.pytest.ini_options]
|
| 52 |
-
pythonpath = ["
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
[build-system]
|
| 55 |
requires = ["setuptools>=61"]
|
| 56 |
build-backend = "setuptools.build_meta"
|
| 57 |
|
| 58 |
[tool.setuptools.packages.find]
|
| 59 |
-
where = ["
|
|
|
|
| 10 |
"folium>=0.20.0",
|
| 11 |
"geopandas>=1.1.3",
|
| 12 |
"geopolars>=0.1.0a4",
|
| 13 |
+
"gtfs-kit>=12.0.4",
|
| 14 |
"ipyleaflet>=0.20.0",
|
| 15 |
"mapclassify>=2.10.0",
|
| 16 |
"marimo[lsp,recommended]>=0.23.5",
|
|
|
|
| 46 |
"F401"
|
| 47 |
]
|
| 48 |
|
|
|
|
|
|
|
|
|
|
| 49 |
[tool.pytest.ini_options]
|
| 50 |
+
pythonpath = ["."]
|
| 51 |
+
|
| 52 |
+
[tool.marimo.runtime]
|
| 53 |
+
pythonpath = ["."]
|
| 54 |
|
| 55 |
[build-system]
|
| 56 |
requires = ["setuptools>=61"]
|
| 57 |
build-backend = "setuptools.build_meta"
|
| 58 |
|
| 59 |
[tool.setuptools.packages.find]
|
| 60 |
+
where = ["."]
|
shared/__init__.py
ADDED
|
File without changes
|
shared/api/__init__.py
ADDED
|
File without changes
|
{notebooks/src → shared/api}/arcgis.py
RENAMED
|
File without changes
|
shared/pipelines/sb79.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import csv
|
| 2 |
+
import io
|
| 3 |
+
import zipfile
|
| 4 |
+
from collections import defaultdict
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
import geopandas as gpd
|
| 9 |
+
import pandas as pd
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def assign_tier_to_stops_from_gtfs(
|
| 13 |
+
gtfs_path: str | Path,
|
| 14 |
+
tier_overrides: dict[str, int] | None = None,
|
| 15 |
+
) -> gpd.GeoDataFrame:
|
| 16 |
+
"""Parse a GTFS zip and return a GeoDataFrame of Tier-1/Tier-2 parent stations.
|
| 17 |
+
|
| 18 |
+
Parameters
|
| 19 |
+
----------
|
| 20 |
+
gtfs_path:
|
| 21 |
+
Path to a ``.zip`` file containing standard GTFS tables.
|
| 22 |
+
tier_overrides:
|
| 23 |
+
Optional mapping ``{route_id: tier}`` to force a specific tier for
|
| 24 |
+
a route regardless of the automatic logic.
|
| 25 |
+
|
| 26 |
+
Returns
|
| 27 |
+
-------
|
| 28 |
+
gpd.GeoDataFrame
|
| 29 |
+
Only stops that qualify as Tier 1 or Tier 2 are returned.
|
| 30 |
+
"""
|
| 31 |
+
z = zipfile.ZipFile(gtfs_path)
|
| 32 |
+
|
| 33 |
+
routes = list(csv.DictReader(io.StringIO(z.read("routes.txt").decode("utf-8"))))
|
| 34 |
+
route_info: dict[str, dict[str, Any]] = {}
|
| 35 |
+
for r in routes:
|
| 36 |
+
route_info[r["route_id"]] = r
|
| 37 |
+
|
| 38 |
+
cal = list(csv.DictReader(io.StringIO(z.read("calendar.txt").decode("utf-8"))))
|
| 39 |
+
weekday_services = {c["service_id"] for c in cal if c["monday"] == "1"}
|
| 40 |
+
|
| 41 |
+
trips = list(csv.DictReader(io.StringIO(z.read("trips.txt").decode("utf-8"))))
|
| 42 |
+
trip_to_route: dict[str, str] = {}
|
| 43 |
+
route_dir_counts: dict[str, dict[str, int]] = defaultdict(lambda: {"0": 0, "1": 0})
|
| 44 |
+
for t in trips:
|
| 45 |
+
trip_to_route[t["trip_id"]] = t["route_id"]
|
| 46 |
+
if t["service_id"] in weekday_services:
|
| 47 |
+
route_dir_counts[t["route_id"]][t["direction_id"]] += 1
|
| 48 |
+
|
| 49 |
+
num_wkday = len(weekday_services)
|
| 50 |
+
|
| 51 |
+
route_trains_per_day: dict[str, int] = {}
|
| 52 |
+
for rid, dirs in route_dir_counts.items():
|
| 53 |
+
route_trains_per_day[rid] = round((dirs.get("0", 0) + dirs.get("1", 0)) / num_wkday)
|
| 54 |
+
|
| 55 |
+
stops = list(csv.DictReader(io.StringIO(z.read("stops.txt").decode("utf-8"))))
|
| 56 |
+
stops_df = pd.DataFrame(stops)
|
| 57 |
+
|
| 58 |
+
parent_stations = stops_df[stops_df["location_type"] == "1"].copy()
|
| 59 |
+
boarding_stops = stops_df[stops_df["location_type"] == "0"].copy()
|
| 60 |
+
|
| 61 |
+
# If there are no parent stations (location_type=1), treat all boarding
|
| 62 |
+
# stops (location_type=0) as individual stations. Some GTFS feeds
|
| 63 |
+
# (e.g. OC Streetcar) only have location_type=0 stops with no parent
|
| 64 |
+
# station hierarchy.
|
| 65 |
+
if parent_stations.empty:
|
| 66 |
+
parent_stations = boarding_stops.copy()
|
| 67 |
+
boarding_stops = gpd.GeoDataFrame() # no routes to propagate
|
| 68 |
+
|
| 69 |
+
stop_times = list(csv.DictReader(io.StringIO(z.read("stop_times.txt").decode("utf-8"))))
|
| 70 |
+
stop_to_routes: dict[str, set[str]] = defaultdict(set)
|
| 71 |
+
for st in stop_times:
|
| 72 |
+
rid = trip_to_route.get(st["trip_id"])
|
| 73 |
+
if rid:
|
| 74 |
+
stop_to_routes[st["stop_id"]].add(rid)
|
| 75 |
+
|
| 76 |
+
parent_to_routes: dict[str, set[str]] = defaultdict(set)
|
| 77 |
+
for _, bs in boarding_stops.iterrows():
|
| 78 |
+
parent = bs["parent_station"] if "parent_station" in bs else None
|
| 79 |
+
if parent and parent in set(parent_stations["stop_id"]):
|
| 80 |
+
parent_to_routes[parent].update(stop_to_routes.get(bs["stop_id"], set()))
|
| 81 |
+
|
| 82 |
+
for _, ps in parent_stations.iterrows():
|
| 83 |
+
parent_to_routes[ps["stop_id"]].update(stop_to_routes.get(ps["stop_id"], set()))
|
| 84 |
+
|
| 85 |
+
# --- Build the output GeoDataFrame ---
|
| 86 |
+
records: list[dict[str, Any]] = []
|
| 87 |
+
for _, ps in parent_stations.iterrows():
|
| 88 |
+
pid = ps["stop_id"]
|
| 89 |
+
served_routes = sorted(parent_to_routes.get(pid, set()))
|
| 90 |
+
if not served_routes:
|
| 91 |
+
continue
|
| 92 |
+
|
| 93 |
+
# Collect route types and count arrivals
|
| 94 |
+
types: set[str] = set()
|
| 95 |
+
total_arrivals = 0
|
| 96 |
+
agencies: set[str] = set()
|
| 97 |
+
for rid in served_routes:
|
| 98 |
+
ri = route_info.get(rid, {})
|
| 99 |
+
types.add(ri.get("route_type", ""))
|
| 100 |
+
total_arrivals += route_trains_per_day.get(rid, 0)
|
| 101 |
+
agencies.add(ri.get("agency_id", ""))
|
| 102 |
+
|
| 103 |
+
routetypes_str = ",".join(sorted(types, key=int))
|
| 104 |
+
|
| 105 |
+
# Tier assignment
|
| 106 |
+
has_type_1 = "1" in types
|
| 107 |
+
has_type_0 = "0" in types
|
| 108 |
+
has_type_2 = "2" in types
|
| 109 |
+
|
| 110 |
+
tier: int | None = None
|
| 111 |
+
if has_type_1:
|
| 112 |
+
tier = 1
|
| 113 |
+
elif (has_type_0 or has_type_2) and total_arrivals >= 72:
|
| 114 |
+
tier = 1
|
| 115 |
+
elif has_type_2 and 48 <= total_arrivals < 72:
|
| 116 |
+
tier = 2
|
| 117 |
+
elif has_type_0 and total_arrivals < 72:
|
| 118 |
+
tier = 2
|
| 119 |
+
|
| 120 |
+
# Apply overrides
|
| 121 |
+
if tier_overrides:
|
| 122 |
+
for rid in served_routes:
|
| 123 |
+
if rid in tier_overrides:
|
| 124 |
+
tier = tier_overrides[rid]
|
| 125 |
+
break
|
| 126 |
+
|
| 127 |
+
if tier is None:
|
| 128 |
+
continue # skip stops that don't qualify
|
| 129 |
+
|
| 130 |
+
records.append(
|
| 131 |
+
{
|
| 132 |
+
"stop_id": pid,
|
| 133 |
+
"stop_name": ps.get("stop_name", ""),
|
| 134 |
+
"stop_lat": float(ps["stop_lat"]),
|
| 135 |
+
"stop_lon": float(ps["stop_lon"]),
|
| 136 |
+
"Tier": tier,
|
| 137 |
+
"agency": ",".join(sorted(agencies)),
|
| 138 |
+
"route_ids_served": ",".join(served_routes),
|
| 139 |
+
"routetypes": routetypes_str,
|
| 140 |
+
"n_arrivals": total_arrivals,
|
| 141 |
+
}
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
if not records:
|
| 145 |
+
return gpd.GeoDataFrame(
|
| 146 |
+
{
|
| 147 |
+
"stop_id": pd.Series(dtype=str),
|
| 148 |
+
"stop_name": pd.Series(dtype=str),
|
| 149 |
+
"Tier": pd.Series(dtype=int),
|
| 150 |
+
"agency": pd.Series(dtype=str),
|
| 151 |
+
"route_ids_served": pd.Series(dtype=str),
|
| 152 |
+
"routetypes": pd.Series(dtype=str),
|
| 153 |
+
"n_arrivals": pd.Series(dtype=int),
|
| 154 |
+
},
|
| 155 |
+
geometry=pd.Series(dtype=object),
|
| 156 |
+
crs="EPSG:4326",
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
result = gpd.GeoDataFrame(
|
| 160 |
+
records,
|
| 161 |
+
geometry=gpd.points_from_xy(
|
| 162 |
+
[r["stop_lon"] for r in records],
|
| 163 |
+
[r["stop_lat"] for r in records],
|
| 164 |
+
crs="EPSG:4326",
|
| 165 |
+
),
|
| 166 |
+
)
|
| 167 |
+
result.drop(columns=["stop_lat", "stop_lon"], inplace=True)
|
| 168 |
+
return result
|
shared/utils/__init__.py
ADDED
|
File without changes
|
{notebooks → shared/utils}/constants.py
RENAMED
|
File without changes
|
tests/test_arcgis.py
CHANGED
|
@@ -6,7 +6,8 @@ import geopandas as gpd
|
|
| 6 |
import pytest
|
| 7 |
import responses
|
| 8 |
from shapely.geometry import Polygon, box
|
| 9 |
-
|
|
|
|
| 10 |
fetch_from_arcgis,
|
| 11 |
paginate_arcgis,
|
| 12 |
shapely_to_esri_json,
|
|
|
|
| 6 |
import pytest
|
| 7 |
import responses
|
| 8 |
from shapely.geometry import Polygon, box
|
| 9 |
+
|
| 10 |
+
from shared.api.arcgis import (
|
| 11 |
fetch_from_arcgis,
|
| 12 |
paginate_arcgis,
|
| 13 |
shapely_to_esri_json,
|
tests/test_gtfs_to_parcels.py
CHANGED
|
@@ -8,17 +8,18 @@ from pathlib import Path
|
|
| 8 |
import geopandas as gpd
|
| 9 |
import numpy as np
|
| 10 |
import pytest
|
| 11 |
-
from
|
|
|
|
|
|
|
| 12 |
aggregate_parcels_to_stops,
|
| 13 |
assign_nearest_stop,
|
| 14 |
compute_scag_density,
|
| 15 |
create_buffer_donuts,
|
| 16 |
-
create_half_mi_buffers,
|
| 17 |
join_scag_ca_parcels,
|
| 18 |
-
parse_gtfs_zip,
|
| 19 |
trim_around_stations,
|
| 20 |
)
|
| 21 |
-
from
|
|
|
|
| 22 |
|
| 23 |
|
| 24 |
def _make_gtfs_zip(
|
|
@@ -79,6 +80,15 @@ def _make_stops_gdf(stops_data: list[dict]) -> gpd.GeoDataFrame:
|
|
| 79 |
return gpd.GeoDataFrame(records, crs="EPSG:4326")
|
| 80 |
|
| 81 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
def _make_parcels_gdf(parcels_data: list[dict]) -> gpd.GeoDataFrame:
|
| 83 |
"""Create a parcels GeoDataFrame from a list of dicts."""
|
| 84 |
records = []
|
|
@@ -140,7 +150,7 @@ class TestParseGtfsZip:
|
|
| 140 |
|
| 141 |
path.write_bytes(gtfs_bytes)
|
| 142 |
try:
|
| 143 |
-
result =
|
| 144 |
assert len(result) == 1
|
| 145 |
assert result.iloc[0]["stop_id"] == "801S"
|
| 146 |
assert result.iloc[0]["Tier"] == 1 # subway → Tier 1
|
|
@@ -175,7 +185,7 @@ class TestParseGtfsZip:
|
|
| 175 |
|
| 176 |
path.write_bytes(gtfs_bytes)
|
| 177 |
try:
|
| 178 |
-
result =
|
| 179 |
assert len(result) == 1
|
| 180 |
# 80 trips / 1 weekday service = 80/day >= 72 → Tier 1
|
| 181 |
assert result.iloc[0]["Tier"] == 1
|
|
@@ -209,7 +219,7 @@ class TestParseGtfsZip:
|
|
| 209 |
|
| 210 |
path.write_bytes(gtfs_bytes)
|
| 211 |
try:
|
| 212 |
-
result =
|
| 213 |
assert len(result) == 1
|
| 214 |
# 400 trips / 5 days = 80/day >= 72 → Tier 1
|
| 215 |
assert result.iloc[0]["Tier"] == 1
|
|
@@ -243,7 +253,7 @@ class TestParseGtfsZip:
|
|
| 243 |
|
| 244 |
path.write_bytes(gtfs_bytes)
|
| 245 |
try:
|
| 246 |
-
result =
|
| 247 |
assert len(result) == 1
|
| 248 |
# 20 trips / 5 = 4/day < 72 → Tier 2
|
| 249 |
assert result.iloc[0]["Tier"] == 2
|
|
@@ -291,7 +301,7 @@ class TestParseGtfsZip:
|
|
| 291 |
|
| 292 |
path.write_bytes(gtfs_bytes)
|
| 293 |
try:
|
| 294 |
-
result =
|
| 295 |
assert len(result) == 1
|
| 296 |
# 120 trips / 2 weekday services = 60/day, 48 <= 60 < 72 → Tier 2
|
| 297 |
assert result.iloc[0]["Tier"] == 2
|
|
@@ -326,7 +336,7 @@ class TestParseGtfsZip:
|
|
| 326 |
|
| 327 |
path.write_bytes(gtfs_bytes)
|
| 328 |
try:
|
| 329 |
-
result =
|
| 330 |
assert len(result) == 1
|
| 331 |
assert result.iloc[0]["Tier"] == 2 # overridden
|
| 332 |
finally:
|
|
@@ -360,7 +370,7 @@ class TestParseGtfsZip:
|
|
| 360 |
|
| 361 |
path.write_bytes(gtfs_bytes)
|
| 362 |
try:
|
| 363 |
-
result =
|
| 364 |
assert len(result) == 0 # no Tier 1 or 2 stops
|
| 365 |
finally:
|
| 366 |
path.unlink(missing_ok=True)
|
|
@@ -407,7 +417,7 @@ class TestParseGtfsZip:
|
|
| 407 |
|
| 408 |
path.write_bytes(gtfs_bytes)
|
| 409 |
try:
|
| 410 |
-
result =
|
| 411 |
assert len(result) == 1
|
| 412 |
assert result.iloc[0]["stop_id"] == "S1"
|
| 413 |
assert result.iloc[0]["Tier"] == 2 # route_type=0, 2 trips/5=0.4/day < 72
|
|
@@ -450,7 +460,7 @@ class TestParseGtfsZip:
|
|
| 450 |
|
| 451 |
path.write_bytes(gtfs_bytes)
|
| 452 |
try:
|
| 453 |
-
result =
|
| 454 |
assert len(result) == 1
|
| 455 |
assert result.iloc[0]["Tier"] == 1 # has route_type 1
|
| 456 |
assert "1" in result.iloc[0]["routetypes"]
|
|
@@ -458,28 +468,6 @@ class TestParseGtfsZip:
|
|
| 458 |
path.unlink(missing_ok=True)
|
| 459 |
|
| 460 |
|
| 461 |
-
# ---------------------------------------------------------------------------
|
| 462 |
-
# Tests: create_half_mi_buffers
|
| 463 |
-
# ---------------------------------------------------------------------------
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
class TestCreateHalfMiBuffers:
|
| 467 |
-
def test_basic(self):
|
| 468 |
-
stops = _make_stops_gdf(
|
| 469 |
-
[
|
| 470 |
-
{"stop_id": "A", "Tier": 1, "lat": 34.0, "lon": -118.0},
|
| 471 |
-
]
|
| 472 |
-
)
|
| 473 |
-
buffers = create_half_mi_buffers(stops)
|
| 474 |
-
assert len(buffers) == 1
|
| 475 |
-
assert buffers.crs.to_string() == "EPSG:3310"
|
| 476 |
-
# Buffer should be a polygon, not a point
|
| 477 |
-
assert buffers.geometry.iloc[0].geom_type in ("Polygon", "MultiPolygon")
|
| 478 |
-
# Area should be roughly pi * 804.7^2 ≈ 2,034,000 m²
|
| 479 |
-
area = buffers.geometry.iloc[0].area
|
| 480 |
-
assert 1_900_000 < area < 2_100_000
|
| 481 |
-
|
| 482 |
-
|
| 483 |
# ---------------------------------------------------------------------------
|
| 484 |
# Tests: compute_scag_density
|
| 485 |
# ---------------------------------------------------------------------------
|
|
@@ -627,7 +615,7 @@ class TestAssignNearestStop:
|
|
| 627 |
{"stop_id": "A", "Tier": 1, "lat": 34.0, "lon": -118.0},
|
| 628 |
]
|
| 629 |
)
|
| 630 |
-
buffers =
|
| 631 |
parcels = gpd.GeoDataFrame(
|
| 632 |
{"PARCEL_APN": ["1"]},
|
| 633 |
geometry=[Point(-118.0005, 34.0005).buffer(0.001)],
|
|
@@ -646,7 +634,7 @@ class TestAssignNearestStop:
|
|
| 646 |
{"stop_id": "B", "Tier": 1, "lat": 34.01, "lon": -118.0},
|
| 647 |
]
|
| 648 |
)
|
| 649 |
-
buffers =
|
| 650 |
# Parcel closer to stop A
|
| 651 |
parcels = gpd.GeoDataFrame(
|
| 652 |
{"PARCEL_APN": ["1"]},
|
|
|
|
| 8 |
import geopandas as gpd
|
| 9 |
import numpy as np
|
| 10 |
import pytest
|
| 11 |
+
from shapely.geometry import Point, box
|
| 12 |
+
|
| 13 |
+
from notebooks.sb79map import (
|
| 14 |
aggregate_parcels_to_stops,
|
| 15 |
assign_nearest_stop,
|
| 16 |
compute_scag_density,
|
| 17 |
create_buffer_donuts,
|
|
|
|
| 18 |
join_scag_ca_parcels,
|
|
|
|
| 19 |
trim_around_stations,
|
| 20 |
)
|
| 21 |
+
from shared.pipelines.sb79 import assign_tier_to_stops_from_gtfs
|
| 22 |
+
from shared.utils.constants import HALF_MI_M
|
| 23 |
|
| 24 |
|
| 25 |
def _make_gtfs_zip(
|
|
|
|
| 80 |
return gpd.GeoDataFrame(records, crs="EPSG:4326")
|
| 81 |
|
| 82 |
|
| 83 |
+
def _make_half_mi_buffer_gdf(stops: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
|
| 84 |
+
"""Create a GeoDataFrame of half-mile buffers around stops."""
|
| 85 |
+
return gpd.GeoDataFrame(
|
| 86 |
+
{"stop_id": stops["stop_id"].values},
|
| 87 |
+
geometry=stops.to_crs("EPSG:3310").geometry.buffer(HALF_MI_M, resolution=8),
|
| 88 |
+
crs="EPSG:3310",
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
def _make_parcels_gdf(parcels_data: list[dict]) -> gpd.GeoDataFrame:
|
| 93 |
"""Create a parcels GeoDataFrame from a list of dicts."""
|
| 94 |
records = []
|
|
|
|
| 150 |
|
| 151 |
path.write_bytes(gtfs_bytes)
|
| 152 |
try:
|
| 153 |
+
result = assign_tier_to_stops_from_gtfs(path)
|
| 154 |
assert len(result) == 1
|
| 155 |
assert result.iloc[0]["stop_id"] == "801S"
|
| 156 |
assert result.iloc[0]["Tier"] == 1 # subway → Tier 1
|
|
|
|
| 185 |
|
| 186 |
path.write_bytes(gtfs_bytes)
|
| 187 |
try:
|
| 188 |
+
result = assign_tier_to_stops_from_gtfs(path)
|
| 189 |
assert len(result) == 1
|
| 190 |
# 80 trips / 1 weekday service = 80/day >= 72 → Tier 1
|
| 191 |
assert result.iloc[0]["Tier"] == 1
|
|
|
|
| 219 |
|
| 220 |
path.write_bytes(gtfs_bytes)
|
| 221 |
try:
|
| 222 |
+
result = assign_tier_to_stops_from_gtfs(path)
|
| 223 |
assert len(result) == 1
|
| 224 |
# 400 trips / 5 days = 80/day >= 72 → Tier 1
|
| 225 |
assert result.iloc[0]["Tier"] == 1
|
|
|
|
| 253 |
|
| 254 |
path.write_bytes(gtfs_bytes)
|
| 255 |
try:
|
| 256 |
+
result = assign_tier_to_stops_from_gtfs(path)
|
| 257 |
assert len(result) == 1
|
| 258 |
# 20 trips / 5 = 4/day < 72 → Tier 2
|
| 259 |
assert result.iloc[0]["Tier"] == 2
|
|
|
|
| 301 |
|
| 302 |
path.write_bytes(gtfs_bytes)
|
| 303 |
try:
|
| 304 |
+
result = assign_tier_to_stops_from_gtfs(path)
|
| 305 |
assert len(result) == 1
|
| 306 |
# 120 trips / 2 weekday services = 60/day, 48 <= 60 < 72 → Tier 2
|
| 307 |
assert result.iloc[0]["Tier"] == 2
|
|
|
|
| 336 |
|
| 337 |
path.write_bytes(gtfs_bytes)
|
| 338 |
try:
|
| 339 |
+
result = assign_tier_to_stops_from_gtfs(path, tier_overrides={"801": 2})
|
| 340 |
assert len(result) == 1
|
| 341 |
assert result.iloc[0]["Tier"] == 2 # overridden
|
| 342 |
finally:
|
|
|
|
| 370 |
|
| 371 |
path.write_bytes(gtfs_bytes)
|
| 372 |
try:
|
| 373 |
+
result = assign_tier_to_stops_from_gtfs(path)
|
| 374 |
assert len(result) == 0 # no Tier 1 or 2 stops
|
| 375 |
finally:
|
| 376 |
path.unlink(missing_ok=True)
|
|
|
|
| 417 |
|
| 418 |
path.write_bytes(gtfs_bytes)
|
| 419 |
try:
|
| 420 |
+
result = assign_tier_to_stops_from_gtfs(path)
|
| 421 |
assert len(result) == 1
|
| 422 |
assert result.iloc[0]["stop_id"] == "S1"
|
| 423 |
assert result.iloc[0]["Tier"] == 2 # route_type=0, 2 trips/5=0.4/day < 72
|
|
|
|
| 460 |
|
| 461 |
path.write_bytes(gtfs_bytes)
|
| 462 |
try:
|
| 463 |
+
result = assign_tier_to_stops_from_gtfs(path)
|
| 464 |
assert len(result) == 1
|
| 465 |
assert result.iloc[0]["Tier"] == 1 # has route_type 1
|
| 466 |
assert "1" in result.iloc[0]["routetypes"]
|
|
|
|
| 468 |
path.unlink(missing_ok=True)
|
| 469 |
|
| 470 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 471 |
# ---------------------------------------------------------------------------
|
| 472 |
# Tests: compute_scag_density
|
| 473 |
# ---------------------------------------------------------------------------
|
|
|
|
| 615 |
{"stop_id": "A", "Tier": 1, "lat": 34.0, "lon": -118.0},
|
| 616 |
]
|
| 617 |
)
|
| 618 |
+
buffers = _make_half_mi_buffer_gdf(stops)
|
| 619 |
parcels = gpd.GeoDataFrame(
|
| 620 |
{"PARCEL_APN": ["1"]},
|
| 621 |
geometry=[Point(-118.0005, 34.0005).buffer(0.001)],
|
|
|
|
| 634 |
{"stop_id": "B", "Tier": 1, "lat": 34.01, "lon": -118.0},
|
| 635 |
]
|
| 636 |
)
|
| 637 |
+
buffers = _make_half_mi_buffer_gdf(stops)
|
| 638 |
# Parcel closer to stop A
|
| 639 |
parcels = gpd.GeoDataFrame(
|
| 640 |
{"PARCEL_APN": ["1"]},
|
uv.lock
CHANGED
|
@@ -686,6 +686,24 @@ wheels = [
|
|
| 686 |
{ url = "https://files.pythonhosted.org/packages/11/8c/c9138d881c79aa0ea9ed83cbd58d5ca75624378b38cee225dcf5c42cc91f/griffelib-2.0.2-py3-none-any.whl", hash = "sha256:925c857658fb1ba40c0772c37acbc2ab650bd794d9c1b9726922e36ea4117ea1", size = 142357, upload-time = "2026-03-27T11:34:46.275Z" },
|
| 687 |
]
|
| 688 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 689 |
[[package]]
|
| 690 |
name = "h11"
|
| 691 |
version = "0.16.0"
|
|
@@ -966,6 +984,12 @@ wheels = [
|
|
| 966 |
{ url = "https://files.pythonhosted.org/packages/7b/91/984aca2ec129e2757d1e4e3c81c3fcda9d0f85b74670a094cc443d9ee949/joblib-1.5.3-py3-none-any.whl", hash = "sha256:5fc3c5039fc5ca8c0276333a188bbd59d6b7ab37fe6632daa76bc7f9ec18e713", size = 309071, upload-time = "2025-12-15T08:41:44.973Z" },
|
| 967 |
]
|
| 968 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 969 |
[[package]]
|
| 970 |
name = "jsonschema"
|
| 971 |
version = "4.26.0"
|
|
@@ -1445,6 +1469,7 @@ dependencies = [
|
|
| 1445 |
{ name = "folium" },
|
| 1446 |
{ name = "geopandas" },
|
| 1447 |
{ name = "geopolars" },
|
|
|
|
| 1448 |
{ name = "ipyleaflet" },
|
| 1449 |
{ name = "mapclassify" },
|
| 1450 |
{ name = "marimo", extra = ["lsp", "recommended"] },
|
|
@@ -1468,6 +1493,7 @@ requires-dist = [
|
|
| 1468 |
{ name = "folium", specifier = ">=0.20.0" },
|
| 1469 |
{ name = "geopandas", specifier = ">=1.1.3" },
|
| 1470 |
{ name = "geopolars", specifier = ">=0.1.0a4" },
|
|
|
|
| 1471 |
{ name = "ipyleaflet", specifier = ">=0.20.0" },
|
| 1472 |
{ name = "mapclassify", specifier = ">=2.10.0" },
|
| 1473 |
{ name = "marimo", extras = ["lsp", "recommended"], specifier = ">=0.23.5" },
|
|
@@ -2666,6 +2692,22 @@ wheels = [
|
|
| 2666 |
{ url = "https://files.pythonhosted.org/packages/d0/02/fa464cdfbe6b26e0600b62c528b72d8608f5cc49f96b8d6e38c95d60c676/rpds_py-0.30.0-cp314-cp314t-win_amd64.whl", hash = "sha256:27f4b0e92de5bfbc6f86e43959e6edd1425c33b5e69aab0984a72047f2bcf1e3", size = 226532, upload-time = "2025-11-30T20:24:14.634Z" },
|
| 2667 |
]
|
| 2668 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2669 |
[[package]]
|
| 2670 |
name = "ruff"
|
| 2671 |
version = "0.15.12"
|
|
|
|
| 686 |
{ url = "https://files.pythonhosted.org/packages/11/8c/c9138d881c79aa0ea9ed83cbd58d5ca75624378b38cee225dcf5c42cc91f/griffelib-2.0.2-py3-none-any.whl", hash = "sha256:925c857658fb1ba40c0772c37acbc2ab650bd794d9c1b9726922e36ea4117ea1", size = 142357, upload-time = "2026-03-27T11:34:46.275Z" },
|
| 687 |
]
|
| 688 |
|
| 689 |
+
[[package]]
|
| 690 |
+
name = "gtfs-kit"
|
| 691 |
+
version = "12.0.4"
|
| 692 |
+
source = { registry = "https://pypi.org/simple" }
|
| 693 |
+
dependencies = [
|
| 694 |
+
{ name = "folium" },
|
| 695 |
+
{ name = "geopandas" },
|
| 696 |
+
{ name = "json2html" },
|
| 697 |
+
{ name = "pandas" },
|
| 698 |
+
{ name = "requests" },
|
| 699 |
+
{ name = "rtree" },
|
| 700 |
+
{ name = "shapely" },
|
| 701 |
+
]
|
| 702 |
+
sdist = { url = "https://files.pythonhosted.org/packages/37/8b/5e8fb7284f5fbb8a79e07622ba5aaca59d3f8f336cacb7265dccb28d1e6d/gtfs_kit-12.0.4.tar.gz", hash = "sha256:d70ff519914bb90e28cec0ef3fece8931b9b83d050e1037fbfcf02a1e42edca1", size = 1104424, upload-time = "2026-05-08T03:32:15.869Z" }
|
| 703 |
+
wheels = [
|
| 704 |
+
{ url = "https://files.pythonhosted.org/packages/b9/af/cb0b05f4894dc048a740bb375a3d4ffe6250747c8fbfe0d58319729c1600/gtfs_kit-12.0.4-py3-none-any.whl", hash = "sha256:487739f3a9e69f798a3e544608f843cdc0932b9a24112327c5a61abda82cdf77", size = 57739, upload-time = "2026-05-08T03:32:18.588Z" },
|
| 705 |
+
]
|
| 706 |
+
|
| 707 |
[[package]]
|
| 708 |
name = "h11"
|
| 709 |
version = "0.16.0"
|
|
|
|
| 984 |
{ url = "https://files.pythonhosted.org/packages/7b/91/984aca2ec129e2757d1e4e3c81c3fcda9d0f85b74670a094cc443d9ee949/joblib-1.5.3-py3-none-any.whl", hash = "sha256:5fc3c5039fc5ca8c0276333a188bbd59d6b7ab37fe6632daa76bc7f9ec18e713", size = 309071, upload-time = "2025-12-15T08:41:44.973Z" },
|
| 985 |
]
|
| 986 |
|
| 987 |
+
[[package]]
|
| 988 |
+
name = "json2html"
|
| 989 |
+
version = "1.3.0"
|
| 990 |
+
source = { registry = "https://pypi.org/simple" }
|
| 991 |
+
sdist = { url = "https://files.pythonhosted.org/packages/01/d5/40b617ee19d2d79f606ed37f8a81e51158f126d2af67270c68f2b47ae0d5/json2html-1.3.0.tar.gz", hash = "sha256:8951a53662ae9cfd812685facdba693fc950ffc1c1fd1a8a2d3cf4c34600689c", size = 6977, upload-time = "2019-07-03T20:50:03.023Z" }
|
| 992 |
+
|
| 993 |
[[package]]
|
| 994 |
name = "jsonschema"
|
| 995 |
version = "4.26.0"
|
|
|
|
| 1469 |
{ name = "folium" },
|
| 1470 |
{ name = "geopandas" },
|
| 1471 |
{ name = "geopolars" },
|
| 1472 |
+
{ name = "gtfs-kit" },
|
| 1473 |
{ name = "ipyleaflet" },
|
| 1474 |
{ name = "mapclassify" },
|
| 1475 |
{ name = "marimo", extra = ["lsp", "recommended"] },
|
|
|
|
| 1493 |
{ name = "folium", specifier = ">=0.20.0" },
|
| 1494 |
{ name = "geopandas", specifier = ">=1.1.3" },
|
| 1495 |
{ name = "geopolars", specifier = ">=0.1.0a4" },
|
| 1496 |
+
{ name = "gtfs-kit", specifier = ">=12.0.4" },
|
| 1497 |
{ name = "ipyleaflet", specifier = ">=0.20.0" },
|
| 1498 |
{ name = "mapclassify", specifier = ">=2.10.0" },
|
| 1499 |
{ name = "marimo", extras = ["lsp", "recommended"], specifier = ">=0.23.5" },
|
|
|
|
| 2692 |
{ url = "https://files.pythonhosted.org/packages/d0/02/fa464cdfbe6b26e0600b62c528b72d8608f5cc49f96b8d6e38c95d60c676/rpds_py-0.30.0-cp314-cp314t-win_amd64.whl", hash = "sha256:27f4b0e92de5bfbc6f86e43959e6edd1425c33b5e69aab0984a72047f2bcf1e3", size = 226532, upload-time = "2025-11-30T20:24:14.634Z" },
|
| 2693 |
]
|
| 2694 |
|
| 2695 |
+
[[package]]
|
| 2696 |
+
name = "rtree"
|
| 2697 |
+
version = "1.4.1"
|
| 2698 |
+
source = { registry = "https://pypi.org/simple" }
|
| 2699 |
+
sdist = { url = "https://files.pythonhosted.org/packages/95/09/7302695875a019514de9a5dd17b8320e7a19d6e7bc8f85dcfb79a4ce2da3/rtree-1.4.1.tar.gz", hash = "sha256:c6b1b3550881e57ebe530cc6cffefc87cd9bf49c30b37b894065a9f810875e46", size = 52425, upload-time = "2025-08-13T19:32:01.413Z" }
|
| 2700 |
+
wheels = [
|
| 2701 |
+
{ url = "https://files.pythonhosted.org/packages/04/d9/108cd989a4c0954e60b3cdc86fd2826407702b5375f6dfdab2802e5fed98/rtree-1.4.1-py3-none-macosx_10_9_x86_64.whl", hash = "sha256:d672184298527522d4914d8ae53bf76982b86ca420b0acde9298a7a87d81d4a4", size = 468484, upload-time = "2025-08-13T19:31:50.593Z" },
|
| 2702 |
+
{ url = "https://files.pythonhosted.org/packages/f3/cf/2710b6fd6b07ea0aef317b29f335790ba6adf06a28ac236078ed9bd8a91d/rtree-1.4.1-py3-none-macosx_11_0_arm64.whl", hash = "sha256:a7e48d805e12011c2cf739a29d6a60ae852fb1de9fc84220bbcef67e6e595d7d", size = 436325, upload-time = "2025-08-13T19:31:52.367Z" },
|
| 2703 |
+
{ url = "https://files.pythonhosted.org/packages/55/e1/4d075268a46e68db3cac51846eb6a3ab96ed481c585c5a1ad411b3c23aad/rtree-1.4.1-py3-none-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:efa8c4496e31e9ad58ff6c7df89abceac7022d906cb64a3e18e4fceae6b77f65", size = 459789, upload-time = "2025-08-13T19:31:53.926Z" },
|
| 2704 |
+
{ url = "https://files.pythonhosted.org/packages/d1/75/e5d44be90525cd28503e7f836d077ae6663ec0687a13ba7810b4114b3668/rtree-1.4.1-py3-none-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:12de4578f1b3381a93a655846900be4e3d5f4cd5e306b8b00aa77c1121dc7e8c", size = 507644, upload-time = "2025-08-13T19:31:55.164Z" },
|
| 2705 |
+
{ url = "https://files.pythonhosted.org/packages/fd/85/b8684f769a142163b52859a38a486493b05bafb4f2fb71d4f945de28ebf9/rtree-1.4.1-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:b558edda52eca3e6d1ee629042192c65e6b7f2c150d6d6cd207ce82f85be3967", size = 1454478, upload-time = "2025-08-13T19:31:56.808Z" },
|
| 2706 |
+
{ url = "https://files.pythonhosted.org/packages/e9/a4/c2292b95246b9165cc43a0c3757e80995d58bc9b43da5cb47ad6e3535213/rtree-1.4.1-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:f155bc8d6bac9dcd383481dee8c130947a4866db1d16cb6dff442329a038a0dc", size = 1555140, upload-time = "2025-08-13T19:31:58.031Z" },
|
| 2707 |
+
{ url = "https://files.pythonhosted.org/packages/74/25/5282c8270bfcd620d3e73beb35b40ac4ab00f0a898d98ebeb41ef0989ec8/rtree-1.4.1-py3-none-win_amd64.whl", hash = "sha256:efe125f416fd27150197ab8521158662943a40f87acab8028a1aac4ad667a489", size = 389358, upload-time = "2025-08-13T19:31:59.247Z" },
|
| 2708 |
+
{ url = "https://files.pythonhosted.org/packages/3f/50/0a9e7e7afe7339bd5e36911f0ceb15fed51945836ed803ae5afd661057fd/rtree-1.4.1-py3-none-win_arm64.whl", hash = "sha256:3d46f55729b28138e897ffef32f7ce93ac335cb67f9120125ad3742a220800f0", size = 355253, upload-time = "2025-08-13T19:32:00.296Z" },
|
| 2709 |
+
]
|
| 2710 |
+
|
| 2711 |
[[package]]
|
| 2712 |
name = "ruff"
|
| 2713 |
version = "0.15.12"
|