Spaces:
Sleeping
Sleeping
dn commited on
Commit ·
91d8a03
1
Parent(s): 7af92cf
clean up sb79 and finish compute_dwelling_units
Browse files- shared/api/gtfs.py +9 -15
- shared/pipelines/sb79.py +91 -43
- shared/utils/constants.py +2 -6
- shared/utils/geoprocessing.py +6 -2
- tests/api/test_gtfs.py +3 -5
- tests/pipelines/test_sb79.py +110 -100
- tests/test_gtfs_to_parcels.py +0 -167
- tests/test_helpers.py +4 -2
- tests/utils/test_geoprocessing.py +5 -5
shared/api/gtfs.py
CHANGED
|
@@ -22,7 +22,7 @@ def parent_stations_from_gtfs(
|
|
| 22 |
pd.DataFrame
|
| 23 |
Parent stations with columns: stop_id, stop_name, stop_lat, stop_lon,
|
| 24 |
route_ids (list), route_types (list), agencies (list),
|
| 25 |
-
n_arrivals (list of avg trips/day per route
|
| 26 |
"""
|
| 27 |
all_dates = feed.get_dates(as_date_obj=True)
|
| 28 |
if days_of_week is not None:
|
|
@@ -32,17 +32,14 @@ def parent_stations_from_gtfs(
|
|
| 32 |
|
| 33 |
date_strings = [d.strftime("%Y%m%d") for d in all_dates]
|
| 34 |
|
| 35 |
-
# Get trip activity (which trips are active on which dates)
|
| 36 |
activity = feed.compute_trip_activity(date_strings)
|
| 37 |
|
| 38 |
-
# Melt activity into long format: trip_id, date, active
|
| 39 |
activity_long = activity.melt(
|
| 40 |
id_vars=["trip_id"],
|
| 41 |
var_name="date",
|
| 42 |
value_name="active",
|
| 43 |
)
|
| 44 |
|
| 45 |
-
# Keep only active trips and join with stop_times -> trips -> routes
|
| 46 |
active_trips = activity_long[activity_long["active"] > 0]
|
| 47 |
|
| 48 |
# Count trips per stop_id per route per date
|
|
@@ -51,10 +48,10 @@ def parent_stations_from_gtfs(
|
|
| 51 |
.merge(feed.stop_times[["trip_id", "stop_id"]], on="trip_id")
|
| 52 |
.merge(feed.trips[["trip_id", "route_id"]], on="trip_id")
|
| 53 |
.merge(
|
| 54 |
-
feed.routes[["route_id", "route_type"
|
| 55 |
on="route_id",
|
| 56 |
)
|
| 57 |
-
.groupby(["stop_id", "route_id", "route_type", "
|
| 58 |
.size()
|
| 59 |
.reset_index(name="num_trips")
|
| 60 |
)
|
|
@@ -62,15 +59,13 @@ def parent_stations_from_gtfs(
|
|
| 62 |
if route_trip_counts.empty:
|
| 63 |
return pd.DataFrame()
|
| 64 |
|
| 65 |
-
# Sum trips across all stops for the same route on each date,
|
| 66 |
-
# then average across active dates to get avg trips/day per route.
|
| 67 |
route_avg = (
|
| 68 |
-
route_trip_counts.groupby(["
|
| 69 |
.sum()
|
|
|
|
|
|
|
|
|
|
| 70 |
.reset_index()
|
| 71 |
-
.groupby(["route_id", "route_type", "agency_id"])["num_trips"]
|
| 72 |
-
.mean()
|
| 73 |
-
.reset_index(name="avg_trips")
|
| 74 |
)
|
| 75 |
|
| 76 |
stops_df = feed.stops
|
|
@@ -95,16 +90,15 @@ def parent_stations_from_gtfs(
|
|
| 95 |
# Map each stop to its parent, deduplicate by (parent_id, route_id),
|
| 96 |
# then aggregate into parallel lists per parent station.
|
| 97 |
parent_route_info = (
|
| 98 |
-
route_trip_counts[["stop_id", "route_id", "route_type"
|
| 99 |
.drop_duplicates()
|
| 100 |
.merge(stop_to_parent, on="stop_id")
|
| 101 |
-
.merge(route_avg, on=["route_id", "route_type"
|
| 102 |
.drop_duplicates(subset=["parent_id", "route_id"])
|
| 103 |
.groupby("parent_id")
|
| 104 |
.agg(
|
| 105 |
route_ids=("route_id", list),
|
| 106 |
route_types=("route_type", lambda x: [str(t) for t in x]),
|
| 107 |
-
agencies=("agency_id", list),
|
| 108 |
n_arrivals=("avg_trips", list),
|
| 109 |
)
|
| 110 |
.reset_index()
|
|
|
|
| 22 |
pd.DataFrame
|
| 23 |
Parent stations with columns: stop_id, stop_name, stop_lat, stop_lon,
|
| 24 |
route_ids (list), route_types (list), agencies (list),
|
| 25 |
+
n_arrivals (list of avg trips/day per route).
|
| 26 |
"""
|
| 27 |
all_dates = feed.get_dates(as_date_obj=True)
|
| 28 |
if days_of_week is not None:
|
|
|
|
| 32 |
|
| 33 |
date_strings = [d.strftime("%Y%m%d") for d in all_dates]
|
| 34 |
|
|
|
|
| 35 |
activity = feed.compute_trip_activity(date_strings)
|
| 36 |
|
|
|
|
| 37 |
activity_long = activity.melt(
|
| 38 |
id_vars=["trip_id"],
|
| 39 |
var_name="date",
|
| 40 |
value_name="active",
|
| 41 |
)
|
| 42 |
|
|
|
|
| 43 |
active_trips = activity_long[activity_long["active"] > 0]
|
| 44 |
|
| 45 |
# Count trips per stop_id per route per date
|
|
|
|
| 48 |
.merge(feed.stop_times[["trip_id", "stop_id"]], on="trip_id")
|
| 49 |
.merge(feed.trips[["trip_id", "route_id"]], on="trip_id")
|
| 50 |
.merge(
|
| 51 |
+
feed.routes[["route_id", "route_type"]],
|
| 52 |
on="route_id",
|
| 53 |
)
|
| 54 |
+
.groupby(["stop_id", "route_id", "route_type", "date"])
|
| 55 |
.size()
|
| 56 |
.reset_index(name="num_trips")
|
| 57 |
)
|
|
|
|
| 59 |
if route_trip_counts.empty:
|
| 60 |
return pd.DataFrame()
|
| 61 |
|
|
|
|
|
|
|
| 62 |
route_avg = (
|
| 63 |
+
route_trip_counts.groupby(["stop_id", "route_id", "route_type", "date"])["num_trips"]
|
| 64 |
.sum()
|
| 65 |
+
.groupby(["stop_id", "route_id", "route_type"])
|
| 66 |
+
.mean() # avg trips per day at this stop for this route
|
| 67 |
+
.rename("avg_trips")
|
| 68 |
.reset_index()
|
|
|
|
|
|
|
|
|
|
| 69 |
)
|
| 70 |
|
| 71 |
stops_df = feed.stops
|
|
|
|
| 90 |
# Map each stop to its parent, deduplicate by (parent_id, route_id),
|
| 91 |
# then aggregate into parallel lists per parent station.
|
| 92 |
parent_route_info = (
|
| 93 |
+
route_trip_counts[["stop_id", "route_id", "route_type"]]
|
| 94 |
.drop_duplicates()
|
| 95 |
.merge(stop_to_parent, on="stop_id")
|
| 96 |
+
.merge(route_avg, on=["route_id", "route_type"])
|
| 97 |
.drop_duplicates(subset=["parent_id", "route_id"])
|
| 98 |
.groupby("parent_id")
|
| 99 |
.agg(
|
| 100 |
route_ids=("route_id", list),
|
| 101 |
route_types=("route_type", lambda x: [str(t) for t in x]),
|
|
|
|
| 102 |
n_arrivals=("avg_trips", list),
|
| 103 |
)
|
| 104 |
.reset_index()
|
shared/pipelines/sb79.py
CHANGED
|
@@ -5,18 +5,11 @@ import geopandas as gpd
|
|
| 5 |
import gtfs_kit
|
| 6 |
import numpy as np
|
| 7 |
import pandas as pd
|
|
|
|
| 8 |
|
| 9 |
from shared.api.gtfs import parent_stations_from_gtfs
|
| 10 |
-
from shared.utils.constants import
|
| 11 |
-
|
| 12 |
-
ZONE_DENSITIES: dict[tuple[str, int], float] = {
|
| 13 |
-
("200ft", 1): 160,
|
| 14 |
-
("200ft", 2): 140,
|
| 15 |
-
("qtr_mi", 1): 120,
|
| 16 |
-
("qtr_mi", 2): 100,
|
| 17 |
-
("half_mi", 1): 100,
|
| 18 |
-
("half_mi", 2): 80,
|
| 19 |
-
}
|
| 20 |
|
| 21 |
|
| 22 |
def assign_tier_to_stops_from_gtfs(
|
|
@@ -29,7 +22,6 @@ def assign_tier_to_stops_from_gtfs(
|
|
| 29 |
if result_df.empty:
|
| 30 |
return _empty_result()
|
| 31 |
|
| 32 |
-
# --- Sum avg daily arrivals across train route types only (0, 1, 2) ---
|
| 33 |
exploded = result_df[["stop_id", "route_types", "n_arrivals"]].explode(["route_types", "n_arrivals"])
|
| 34 |
train_arrivals = exploded[exploded["route_types"].astype(int).isin([0, 1, 2])].groupby("stop_id")["n_arrivals"].sum()
|
| 35 |
result_df["total_train_arrivals"] = result_df["stop_id"].map(train_arrivals).fillna(0)
|
|
@@ -43,9 +35,9 @@ def assign_tier_to_stops_from_gtfs(
|
|
| 43 |
result_df["Tier"] = pd.Series(pd.NA, index=result_df.index).case_when(
|
| 44 |
[
|
| 45 |
(has_subway, 1),
|
| 46 |
-
((has_commuter
|
| 47 |
-
(has_commuter &
|
| 48 |
-
(has_light_rail
|
| 49 |
]
|
| 50 |
)
|
| 51 |
|
|
@@ -58,17 +50,16 @@ def assign_tier_to_stops_from_gtfs(
|
|
| 58 |
result_df = result_df.dropna(subset=["Tier"]).assign(
|
| 59 |
Tier=lambda df: df["Tier"].astype(int),
|
| 60 |
n_arrivals=lambda df: df["total_train_arrivals"],
|
| 61 |
-
agencies=lambda df: df["agencies"].apply(",".join),
|
| 62 |
route_ids=lambda df: df["route_ids"].apply(",".join),
|
| 63 |
route_types=lambda df: df["route_types"].apply(",".join),
|
| 64 |
-
)[["stop_id", "stop_name", "stop_lat", "stop_lon", "
|
| 65 |
|
| 66 |
if result_df.empty:
|
| 67 |
return _empty_result()
|
| 68 |
|
| 69 |
return gpd.GeoDataFrame(
|
| 70 |
result_df,
|
| 71 |
-
geometry=gpd.points_from_xy(result_df["stop_lon"], result_df["stop_lat"], crs=
|
| 72 |
).drop(columns=["stop_lat", "stop_lon"])
|
| 73 |
|
| 74 |
|
|
@@ -79,13 +70,12 @@ def _empty_result() -> gpd.GeoDataFrame:
|
|
| 79 |
"stop_id": pd.Series(dtype=str),
|
| 80 |
"stop_name": pd.Series(dtype=str),
|
| 81 |
"Tier": pd.Series(dtype=int),
|
| 82 |
-
"agencies": pd.Series(dtype=str),
|
| 83 |
"route_ids": pd.Series(dtype=str),
|
| 84 |
"route_types": pd.Series(dtype=str),
|
| 85 |
"n_arrivals": pd.Series(dtype=int),
|
| 86 |
},
|
| 87 |
geometry=pd.Series(dtype=object),
|
| 88 |
-
crs=
|
| 89 |
)
|
| 90 |
|
| 91 |
|
|
@@ -146,7 +136,7 @@ def compute_scag_density(scag_parcels: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
|
|
| 146 |
)
|
| 147 |
|
| 148 |
zn19_scag = df["ZN19_SCAG"].astype(str)
|
| 149 |
-
area_acres = df.to_crs(
|
| 150 |
scag_density = zn19_scag.case_when(
|
| 151 |
[
|
| 152 |
(zn19_scag == "1110", 1 / area_acres.replace(0, np.nan)),
|
|
@@ -180,28 +170,86 @@ def compute_scag_density(scag_parcels: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
|
|
| 180 |
return df
|
| 181 |
|
| 182 |
|
| 183 |
-
def
|
| 184 |
-
parcels_gdf: gpd.GeoDataFrame,
|
| 185 |
stops_gdf: gpd.GeoDataFrame,
|
| 186 |
-
|
| 187 |
) -> gpd.GeoDataFrame:
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
import gtfs_kit
|
| 6 |
import numpy as np
|
| 7 |
import pandas as pd
|
| 8 |
+
from shapely import unary_union
|
| 9 |
|
| 10 |
from shared.api.gtfs import parent_stations_from_gtfs
|
| 11 |
+
from shared.utils.constants import SCAG_FT_CRS, WGS84_GCS_CRS
|
| 12 |
+
from shared.utils.geoprocessing import clip_to_buffer_rings
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
|
| 15 |
def assign_tier_to_stops_from_gtfs(
|
|
|
|
| 22 |
if result_df.empty:
|
| 23 |
return _empty_result()
|
| 24 |
|
|
|
|
| 25 |
exploded = result_df[["stop_id", "route_types", "n_arrivals"]].explode(["route_types", "n_arrivals"])
|
| 26 |
train_arrivals = exploded[exploded["route_types"].astype(int).isin([0, 1, 2])].groupby("stop_id")["n_arrivals"].sum()
|
| 27 |
result_df["total_train_arrivals"] = result_df["stop_id"].map(train_arrivals).fillna(0)
|
|
|
|
| 35 |
result_df["Tier"] = pd.Series(pd.NA, index=result_df.index).case_when(
|
| 36 |
[
|
| 37 |
(has_subway, 1),
|
| 38 |
+
((has_commuter) & (arrivals >= 72), 1),
|
| 39 |
+
((has_commuter) & (arrivals >= 48), 2),
|
| 40 |
+
(has_light_rail, 2),
|
| 41 |
]
|
| 42 |
)
|
| 43 |
|
|
|
|
| 50 |
result_df = result_df.dropna(subset=["Tier"]).assign(
|
| 51 |
Tier=lambda df: df["Tier"].astype(int),
|
| 52 |
n_arrivals=lambda df: df["total_train_arrivals"],
|
|
|
|
| 53 |
route_ids=lambda df: df["route_ids"].apply(",".join),
|
| 54 |
route_types=lambda df: df["route_types"].apply(",".join),
|
| 55 |
+
)[["stop_id", "stop_name", "stop_lat", "stop_lon", "route_ids", "route_types", "Tier", "n_arrivals"]]
|
| 56 |
|
| 57 |
if result_df.empty:
|
| 58 |
return _empty_result()
|
| 59 |
|
| 60 |
return gpd.GeoDataFrame(
|
| 61 |
result_df,
|
| 62 |
+
geometry=gpd.points_from_xy(result_df["stop_lon"], result_df["stop_lat"], crs=WGS84_GCS_CRS),
|
| 63 |
).drop(columns=["stop_lat", "stop_lon"])
|
| 64 |
|
| 65 |
|
|
|
|
| 70 |
"stop_id": pd.Series(dtype=str),
|
| 71 |
"stop_name": pd.Series(dtype=str),
|
| 72 |
"Tier": pd.Series(dtype=int),
|
|
|
|
| 73 |
"route_ids": pd.Series(dtype=str),
|
| 74 |
"route_types": pd.Series(dtype=str),
|
| 75 |
"n_arrivals": pd.Series(dtype=int),
|
| 76 |
},
|
| 77 |
geometry=pd.Series(dtype=object),
|
| 78 |
+
crs=WGS84_GCS_CRS,
|
| 79 |
)
|
| 80 |
|
| 81 |
|
|
|
|
| 136 |
)
|
| 137 |
|
| 138 |
zn19_scag = df["ZN19_SCAG"].astype(str)
|
| 139 |
+
area_acres = df.to_crs(SCAG_FT_CRS).area / 43560
|
| 140 |
scag_density = zn19_scag.case_when(
|
| 141 |
[
|
| 142 |
(zn19_scag == "1110", 1 / area_acres.replace(0, np.nan)),
|
|
|
|
| 170 |
return df
|
| 171 |
|
| 172 |
|
| 173 |
+
def compute_dwelling_units(
|
|
|
|
| 174 |
stops_gdf: gpd.GeoDataFrame,
|
| 175 |
+
scag_density: gpd.GeoDataFrame,
|
| 176 |
) -> gpd.GeoDataFrame:
|
| 177 |
+
stops_trimmed = stops_gdf[["stop_id", "Tier", "geometry"]]
|
| 178 |
+
|
| 179 |
+
scag_clean = scag_density.drop(columns=["Tier"], errors="ignore")
|
| 180 |
+
|
| 181 |
+
buffer_distances = [200, 1320, 2640]
|
| 182 |
+
rings = clip_to_buffer_rings(
|
| 183 |
+
features_gdf=scag_clean,
|
| 184 |
+
sources_gdf=stops_trimmed,
|
| 185 |
+
buffer_distances=buffer_distances,
|
| 186 |
+
buffer_crs=SCAG_FT_CRS,
|
| 187 |
+
donut_how="difference",
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
for ring, distance in zip(rings, buffer_distances, strict=False):
|
| 191 |
+
ring["buffer_zone_id"] = f"{distance} ft"
|
| 192 |
+
|
| 193 |
+
buffed_parcels = gpd.GeoDataFrame(pd.concat(rings, ignore_index=True))
|
| 194 |
+
|
| 195 |
+
buffed_parcels["area_sqft"] = buffed_parcels.area
|
| 196 |
+
|
| 197 |
+
zone_densities_series = pd.Series(
|
| 198 |
+
{
|
| 199 |
+
("200 ft", 1): 160,
|
| 200 |
+
("200 ft", 2): 140,
|
| 201 |
+
("1320 ft", 1): 120,
|
| 202 |
+
("1320 ft", 2): 100,
|
| 203 |
+
("2640 ft", 1): 100,
|
| 204 |
+
("2640 ft", 2): 80,
|
| 205 |
+
}
|
| 206 |
+
)
|
| 207 |
+
buffed_parcels["zone_density"] = buffed_parcels.set_index(["buffer_zone_id", "Tier"]).index.map(zone_densities_series)
|
| 208 |
+
|
| 209 |
+
area_agg = buffed_parcels.groupby("APN20")["area_sqft"].sum().rename("area_sqft_total")
|
| 210 |
+
area_acres = area_agg / 43560
|
| 211 |
+
|
| 212 |
+
buffed_parcels["area_x_density"] = buffed_parcels["area_sqft"] * buffed_parcels["zone_density"]
|
| 213 |
+
weighted_sum = buffed_parcels.groupby("APN20")["area_x_density"].sum()
|
| 214 |
+
|
| 215 |
+
geom_agg = buffed_parcels.groupby("APN20")["geometry"].agg(unary_union)
|
| 216 |
+
|
| 217 |
+
first_agg = buffed_parcels.groupby("APN20").first()[
|
| 218 |
+
[
|
| 219 |
+
"current_density_du_per_ac",
|
| 220 |
+
"Tier",
|
| 221 |
+
"ZN19_CITY",
|
| 222 |
+
"ZN19_SCAG",
|
| 223 |
+
"COUNTY",
|
| 224 |
+
"CITY",
|
| 225 |
+
"buffer_zone_id",
|
| 226 |
+
]
|
| 227 |
+
]
|
| 228 |
+
weighted_density = np.where(
|
| 229 |
+
(area_agg > 0) & (first_agg["current_density_du_per_ac"].notna()), weighted_sum / area_agg, np.nan
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
by_apn = gpd.GeoDataFrame(
|
| 233 |
+
{
|
| 234 |
+
"APN20": area_agg.index,
|
| 235 |
+
"geometry": geom_agg.values,
|
| 236 |
+
"area_acres": area_acres.values,
|
| 237 |
+
"new_density_du_per_ac": weighted_density,
|
| 238 |
+
"new_dwelling_units": weighted_density * area_acres.values,
|
| 239 |
+
"current_dwelling_units": first_agg["current_density_du_per_ac"].values * area_acres.values,
|
| 240 |
+
"current_density_du_per_ac": first_agg["current_density_du_per_ac"].values,
|
| 241 |
+
"Tier": first_agg["Tier"].values,
|
| 242 |
+
"ZN19_CITY": first_agg["ZN19_CITY"].values,
|
| 243 |
+
"ZN19_SCAG": first_agg["ZN19_SCAG"].values,
|
| 244 |
+
"COUNTY": first_agg["COUNTY"].values,
|
| 245 |
+
"CITY": first_agg["CITY"].values,
|
| 246 |
+
"buffer_zone_id": first_agg["buffer_zone_id"].values,
|
| 247 |
+
},
|
| 248 |
+
geometry="geometry",
|
| 249 |
+
crs=buffed_parcels.crs,
|
| 250 |
+
)
|
| 251 |
+
by_apn["additional_du"] = np.maximum(
|
| 252 |
+
0,
|
| 253 |
+
by_apn.get("new_dwelling_units", 0) - by_apn.get("current_dwelling_units", 0),
|
| 254 |
+
)
|
| 255 |
+
return by_apn
|
shared/utils/constants.py
CHANGED
|
@@ -1,12 +1,8 @@
|
|
| 1 |
-
SCAG_PARCELS_URL = "https://rdp.scag.ca.gov/mapping/rest/services/Housing/2020_Annual_Land_Use/MapServer/0/query"
|
| 2 |
CA_PARCELS_URL = (
|
| 3 |
"https://services1.arcgis.com/jUJYIo9tSA7EHvfZ/ArcGIS/rest/services/"
|
| 4 |
"CA_Statewide_Parcels_Public_view/FeatureServer/0/query"
|
| 5 |
)
|
| 6 |
-
SCAG_OUT_FIELDS = (
|
| 7 |
-
"APN20,COUNTY,CITY,IL_RATIO,ZN19_CITY,ZN19_SCAG,TCAC_2024,"
|
| 8 |
-
"APPAREL1MI,EDUC1MI,GROCERY1MI,HOSPIT1MI,RESTAUR1MI,JOBS_30MIN,YEAR"
|
| 9 |
-
)
|
| 10 |
HALF_MI_M = 804.7
|
| 11 |
|
| 12 |
-
|
|
|
|
|
|
|
|
|
| 1 |
CA_PARCELS_URL = (
|
| 2 |
"https://services1.arcgis.com/jUJYIo9tSA7EHvfZ/ArcGIS/rest/services/"
|
| 3 |
"CA_Statewide_Parcels_Public_view/FeatureServer/0/query"
|
| 4 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
HALF_MI_M = 804.7
|
| 6 |
|
| 7 |
+
SCAG_FT_CRS = "EPSG:2229"
|
| 8 |
+
WGS84_GCS_CRS = "EPSG:4326"
|
shared/utils/geoprocessing.py
CHANGED
|
@@ -2,12 +2,14 @@ from typing import Literal
|
|
| 2 |
|
| 3 |
import geopandas as gpd
|
| 4 |
|
|
|
|
|
|
|
| 5 |
|
| 6 |
def clip_to_buffer_rings(
|
| 7 |
features_gdf: gpd.GeoDataFrame,
|
| 8 |
sources_gdf: gpd.GeoDataFrame,
|
| 9 |
buffer_distances: list[int | float],
|
| 10 |
-
buffer_crs: str =
|
| 11 |
donut_how: Literal["difference", "union"] = "difference",
|
| 12 |
) -> list[gpd.GeoDataFrame]:
|
| 13 |
"""Clip features to concentric donut rings buffered around source geometries.
|
|
@@ -58,7 +60,7 @@ def clip_to_buffer_rings(
|
|
| 58 |
clipped = {
|
| 59 |
dist: gpd.overlay(
|
| 60 |
gpd.sjoin(features_reproj, buf, how="inner", predicate="intersects"),
|
| 61 |
-
buf,
|
| 62 |
how="intersection",
|
| 63 |
)
|
| 64 |
for dist, buf in buffers.items()
|
|
@@ -69,6 +71,8 @@ def clip_to_buffer_rings(
|
|
| 69 |
outer_clip = clipped[outer]
|
| 70 |
if inner is None:
|
| 71 |
rings.append(outer_clip)
|
|
|
|
|
|
|
| 72 |
else:
|
| 73 |
rings.append(gpd.overlay(outer_clip, buffers[inner][["geometry"]], how=donut_how))
|
| 74 |
return rings
|
|
|
|
| 2 |
|
| 3 |
import geopandas as gpd
|
| 4 |
|
| 5 |
+
from shared.utils.constants import SCAG_FT_CRS
|
| 6 |
+
|
| 7 |
|
| 8 |
def clip_to_buffer_rings(
|
| 9 |
features_gdf: gpd.GeoDataFrame,
|
| 10 |
sources_gdf: gpd.GeoDataFrame,
|
| 11 |
buffer_distances: list[int | float],
|
| 12 |
+
buffer_crs: str = SCAG_FT_CRS,
|
| 13 |
donut_how: Literal["difference", "union"] = "difference",
|
| 14 |
) -> list[gpd.GeoDataFrame]:
|
| 15 |
"""Clip features to concentric donut rings buffered around source geometries.
|
|
|
|
| 60 |
clipped = {
|
| 61 |
dist: gpd.overlay(
|
| 62 |
gpd.sjoin(features_reproj, buf, how="inner", predicate="intersects"),
|
| 63 |
+
buf[["geometry"]],
|
| 64 |
how="intersection",
|
| 65 |
)
|
| 66 |
for dist, buf in buffers.items()
|
|
|
|
| 71 |
outer_clip = clipped[outer]
|
| 72 |
if inner is None:
|
| 73 |
rings.append(outer_clip)
|
| 74 |
+
elif outer_clip.empty:
|
| 75 |
+
rings.append(outer_clip)
|
| 76 |
else:
|
| 77 |
rings.append(gpd.overlay(outer_clip, buffers[inner][["geometry"]], how=donut_how))
|
| 78 |
return rings
|
tests/api/test_gtfs.py
CHANGED
|
@@ -101,7 +101,7 @@ class TestParentStationsFromGtfs:
|
|
| 101 |
assert result.iloc[0]["stop_id"] == "S1"
|
| 102 |
assert route1 in result.iloc[0]["route_ids"]
|
| 103 |
# n_arrivals is now a list of per-route averages (parallel to route_ids)
|
| 104 |
-
assert result.iloc[0]["n_arrivals"] == [
|
| 105 |
|
| 106 |
def test_no_parent_stations_falls_back_to_boarding_stops(self):
|
| 107 |
"""When no location_type=1 stops exist, boarding stops are treated as parents."""
|
|
@@ -177,8 +177,7 @@ class TestParentStationsFromGtfs:
|
|
| 177 |
|
| 178 |
# Assert
|
| 179 |
assert len(result) == 1
|
| 180 |
-
|
| 181 |
-
assert result.iloc[0]["n_arrivals"] == [6.0]
|
| 182 |
|
| 183 |
def test_routes_merged_across_children(self):
|
| 184 |
# Arrange
|
|
@@ -223,7 +222,6 @@ class TestParentStationsFromGtfs:
|
|
| 223 |
# route_ids is now a list (not a set)
|
| 224 |
assert result.iloc[0]["route_ids"] == [route1["route_id"], route2["route_id"]]
|
| 225 |
assert result.iloc[0]["route_types"] == [str(route1["route_type"]), str(route2["route_type"])]
|
| 226 |
-
assert result.iloc[0]["agencies"] == [route1["agency_id"], route2["agency_id"]]
|
| 227 |
|
| 228 |
def test_stop_with_no_trips_excluded(self):
|
| 229 |
"""Parent stations with no associated trips are excluded from the result."""
|
|
@@ -358,4 +356,4 @@ class TestParentStationsFromGtfs:
|
|
| 358 |
|
| 359 |
# Assert
|
| 360 |
assert len(result) == 1
|
| 361 |
-
assert result.iloc[0]["n_arrivals"] == [
|
|
|
|
| 101 |
assert result.iloc[0]["stop_id"] == "S1"
|
| 102 |
assert route1 in result.iloc[0]["route_ids"]
|
| 103 |
# n_arrivals is now a list of per-route averages (parallel to route_ids)
|
| 104 |
+
assert result.iloc[0]["n_arrivals"] == [1.0]
|
| 105 |
|
| 106 |
def test_no_parent_stations_falls_back_to_boarding_stops(self):
|
| 107 |
"""When no location_type=1 stops exist, boarding stops are treated as parents."""
|
|
|
|
| 177 |
|
| 178 |
# Assert
|
| 179 |
assert len(result) == 1
|
| 180 |
+
assert result.iloc[0]["n_arrivals"] == [3.0]
|
|
|
|
| 181 |
|
| 182 |
def test_routes_merged_across_children(self):
|
| 183 |
# Arrange
|
|
|
|
| 222 |
# route_ids is now a list (not a set)
|
| 223 |
assert result.iloc[0]["route_ids"] == [route1["route_id"], route2["route_id"]]
|
| 224 |
assert result.iloc[0]["route_types"] == [str(route1["route_type"]), str(route2["route_type"])]
|
|
|
|
| 225 |
|
| 226 |
def test_stop_with_no_trips_excluded(self):
|
| 227 |
"""Parent stations with no associated trips are excluded from the result."""
|
|
|
|
| 356 |
|
| 357 |
# Assert
|
| 358 |
assert len(result) == 1
|
| 359 |
+
assert result.iloc[0]["n_arrivals"] == [1.0]
|
tests/pipelines/test_sb79.py
CHANGED
|
@@ -6,7 +6,7 @@ from pathlib import Path
|
|
| 6 |
import numpy as np
|
| 7 |
import pytest
|
| 8 |
|
| 9 |
-
from shared.pipelines.sb79 import assign_tier_to_stops_from_gtfs,
|
| 10 |
from tests.test_helpers import _make_parcels_gdf, _make_stops_gdf
|
| 11 |
|
| 12 |
|
|
@@ -78,94 +78,6 @@ class TestParseGtfsZip:
|
|
| 78 |
finally:
|
| 79 |
path.unlink(missing_ok=True)
|
| 80 |
|
| 81 |
-
def test_tier1_light_rail_high_freq(self):
|
| 82 |
-
"""route_type=0 with n_arrivals >= 72 → Tier 1."""
|
| 83 |
-
gtfs_bytes = _make_gtfs_zip(
|
| 84 |
-
{
|
| 85 |
-
"routes": [{"route_id": "801", "route_type": "0", "agency_id": "metro"}],
|
| 86 |
-
"trips": [
|
| 87 |
-
{"route_id": "801", "trip_id": f"t{i}", "service_id": "wk", "direction_id": "0"} for i in range(40)
|
| 88 |
-
]
|
| 89 |
-
+ [{"route_id": "801", "trip_id": f"t{i}", "service_id": "wk", "direction_id": "1"} for i in range(40, 80)],
|
| 90 |
-
"stop_times": [
|
| 91 |
-
{"trip_id": f"t{i}", "stop_id": "801S", "arrival_time": "08:00:00", "departure_time": "08:01:00"}
|
| 92 |
-
for i in range(80)
|
| 93 |
-
],
|
| 94 |
-
"stops": [
|
| 95 |
-
{"stop_id": "801S", "stop_name": "Test", "stop_lat": "34.0", "stop_lon": "-118.0", "location_type": "1"},
|
| 96 |
-
],
|
| 97 |
-
"calendar": [
|
| 98 |
-
{
|
| 99 |
-
"service_id": "wk",
|
| 100 |
-
"monday": "1",
|
| 101 |
-
"tuesday": "1",
|
| 102 |
-
"wednesday": "1",
|
| 103 |
-
"thursday": "1",
|
| 104 |
-
"friday": "1",
|
| 105 |
-
"saturday": "0",
|
| 106 |
-
"sunday": "0",
|
| 107 |
-
"start_date": "20250101",
|
| 108 |
-
"end_date": "20251231",
|
| 109 |
-
}
|
| 110 |
-
],
|
| 111 |
-
}
|
| 112 |
-
)
|
| 113 |
-
path = Path(tempfile.gettempdir()) / "_test_gtfs2.zip"
|
| 114 |
-
|
| 115 |
-
path.write_bytes(gtfs_bytes)
|
| 116 |
-
try:
|
| 117 |
-
result = assign_tier_to_stops_from_gtfs(path)
|
| 118 |
-
assert len(result) == 1
|
| 119 |
-
# 80 trips / 1 weekday service = 80/day >= 72 → Tier 1
|
| 120 |
-
assert result.iloc[0]["Tier"] == 1
|
| 121 |
-
finally:
|
| 122 |
-
path.unlink(missing_ok=True)
|
| 123 |
-
|
| 124 |
-
def test_tier1_light_rail_high_freq_72plus(self):
|
| 125 |
-
"""route_type=0 with n_arrivals >= 72 → Tier 1."""
|
| 126 |
-
gtfs_bytes = _make_gtfs_zip(
|
| 127 |
-
{
|
| 128 |
-
"routes": [{"route_id": "801", "route_type": "0", "agency_id": "metro"}],
|
| 129 |
-
"trips": [
|
| 130 |
-
{"route_id": "801", "trip_id": f"t{i}", "service_id": "wk", "direction_id": "0"} for i in range(200)
|
| 131 |
-
]
|
| 132 |
-
+ [
|
| 133 |
-
{"route_id": "801", "trip_id": f"t{i}", "service_id": "wk", "direction_id": "1"} for i in range(200, 400)
|
| 134 |
-
],
|
| 135 |
-
"stop_times": [
|
| 136 |
-
{"trip_id": f"t{i}", "stop_id": "801S", "arrival_time": "08:00:00", "departure_time": "08:01:00"}
|
| 137 |
-
for i in range(400)
|
| 138 |
-
],
|
| 139 |
-
"stops": [
|
| 140 |
-
{"stop_id": "801S", "stop_name": "Test", "stop_lat": "34.0", "stop_lon": "-118.0", "location_type": "1"},
|
| 141 |
-
],
|
| 142 |
-
"calendar": [
|
| 143 |
-
{
|
| 144 |
-
"service_id": "wk",
|
| 145 |
-
"monday": "1",
|
| 146 |
-
"tuesday": "1",
|
| 147 |
-
"wednesday": "1",
|
| 148 |
-
"thursday": "1",
|
| 149 |
-
"friday": "1",
|
| 150 |
-
"saturday": "0",
|
| 151 |
-
"sunday": "0",
|
| 152 |
-
"start_date": "20250101",
|
| 153 |
-
"end_date": "20251231",
|
| 154 |
-
}
|
| 155 |
-
],
|
| 156 |
-
}
|
| 157 |
-
)
|
| 158 |
-
path = Path(tempfile.gettempdir()) / "_test_gtfs3.zip"
|
| 159 |
-
|
| 160 |
-
path.write_bytes(gtfs_bytes)
|
| 161 |
-
try:
|
| 162 |
-
result = assign_tier_to_stops_from_gtfs(path)
|
| 163 |
-
assert len(result) == 1
|
| 164 |
-
# 400 trips / 5 days = 80/day >= 72 → Tier 1
|
| 165 |
-
assert result.iloc[0]["Tier"] == 1
|
| 166 |
-
finally:
|
| 167 |
-
path.unlink(missing_ok=True)
|
| 168 |
-
|
| 169 |
def test_tier2_light_rail_low_freq(self):
|
| 170 |
"""route_type=0 with n_arrivals < 72 → Tier 2."""
|
| 171 |
gtfs_bytes = _make_gtfs_zip(
|
|
@@ -249,7 +161,6 @@ class TestParseGtfsZip:
|
|
| 249 |
try:
|
| 250 |
result = assign_tier_to_stops_from_gtfs(path)
|
| 251 |
assert len(result) == 1
|
| 252 |
-
# 60 trips, 48 <= 60 < 72 → Tier 2
|
| 253 |
assert result.iloc[0]["Tier"] == 2
|
| 254 |
finally:
|
| 255 |
path.unlink(missing_ok=True)
|
|
@@ -479,35 +390,134 @@ class TestComputeScagDensity:
|
|
| 479 |
assert np.isnan(result.iloc[0]["current_density_du_per_ac"])
|
| 480 |
|
| 481 |
|
| 482 |
-
class
|
| 483 |
-
def
|
| 484 |
stops = _make_stops_gdf(
|
| 485 |
[
|
| 486 |
{"stop_id": "A", "Tier": 1, "lat": 34.0, "lon": -118.0},
|
| 487 |
]
|
| 488 |
)
|
| 489 |
-
|
| 490 |
parcels = _make_parcels_gdf(
|
| 491 |
[
|
| 492 |
-
{
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 493 |
]
|
| 494 |
)
|
| 495 |
-
result =
|
| 496 |
assert len(result) >= 1
|
|
|
|
|
|
|
|
|
|
|
|
|
| 497 |
assert "buffer_zone_id" in result.columns
|
| 498 |
-
assert result["
|
| 499 |
|
| 500 |
-
def
|
| 501 |
stops = _make_stops_gdf(
|
| 502 |
[
|
| 503 |
{"stop_id": "A", "Tier": 1, "lat": 34.0, "lon": -118.0},
|
| 504 |
]
|
| 505 |
)
|
| 506 |
-
# Parcel far away
|
| 507 |
parcels = _make_parcels_gdf(
|
| 508 |
[
|
| 509 |
{"APN20": "1", "current_density_du_per_ac": 10, "Tier": 1, "bbox": (-117.0, 34.0, -116.99, 34.01)},
|
| 510 |
]
|
| 511 |
)
|
| 512 |
-
result =
|
| 513 |
-
assert len(result) == 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
import numpy as np
|
| 7 |
import pytest
|
| 8 |
|
| 9 |
+
from shared.pipelines.sb79 import assign_tier_to_stops_from_gtfs, compute_dwelling_units, compute_scag_density
|
| 10 |
from tests.test_helpers import _make_parcels_gdf, _make_stops_gdf
|
| 11 |
|
| 12 |
|
|
|
|
| 78 |
finally:
|
| 79 |
path.unlink(missing_ok=True)
|
| 80 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
def test_tier2_light_rail_low_freq(self):
|
| 82 |
"""route_type=0 with n_arrivals < 72 → Tier 2."""
|
| 83 |
gtfs_bytes = _make_gtfs_zip(
|
|
|
|
| 161 |
try:
|
| 162 |
result = assign_tier_to_stops_from_gtfs(path)
|
| 163 |
assert len(result) == 1
|
|
|
|
| 164 |
assert result.iloc[0]["Tier"] == 2
|
| 165 |
finally:
|
| 166 |
path.unlink(missing_ok=True)
|
|
|
|
| 390 |
assert np.isnan(result.iloc[0]["current_density_du_per_ac"])
|
| 391 |
|
| 392 |
|
| 393 |
+
class TestCreateBufferDonuts:
|
| 394 |
+
def test_basic_density(self):
|
| 395 |
stops = _make_stops_gdf(
|
| 396 |
[
|
| 397 |
{"stop_id": "A", "Tier": 1, "lat": 34.0, "lon": -118.0},
|
| 398 |
]
|
| 399 |
)
|
|
|
|
| 400 |
parcels = _make_parcels_gdf(
|
| 401 |
[
|
| 402 |
+
{
|
| 403 |
+
"APN20": "1",
|
| 404 |
+
"current_density_du_per_ac": 10,
|
| 405 |
+
"ZN19_CITY": "",
|
| 406 |
+
"ZN19_SCAG": 0,
|
| 407 |
+
"CITY": "Other",
|
| 408 |
+
"COUNTY": "LA",
|
| 409 |
+
"Tier": 1,
|
| 410 |
+
"bbox": (-118.001, 33.999, -117.999, 34.001),
|
| 411 |
+
},
|
| 412 |
]
|
| 413 |
)
|
| 414 |
+
result = compute_dwelling_units(stops, parcels)
|
| 415 |
assert len(result) >= 1
|
| 416 |
+
assert "new_density_du_per_ac" in result.columns
|
| 417 |
+
assert "new_dwelling_units" in result.columns
|
| 418 |
+
assert "current_dwelling_units" in result.columns
|
| 419 |
+
assert "additional_du" in result.columns
|
| 420 |
assert "buffer_zone_id" in result.columns
|
| 421 |
+
assert result["new_density_du_per_ac"].iloc[0] > 0
|
| 422 |
|
| 423 |
+
def test_no_intersection_empty(self):
|
| 424 |
stops = _make_stops_gdf(
|
| 425 |
[
|
| 426 |
{"stop_id": "A", "Tier": 1, "lat": 34.0, "lon": -118.0},
|
| 427 |
]
|
| 428 |
)
|
|
|
|
| 429 |
parcels = _make_parcels_gdf(
|
| 430 |
[
|
| 431 |
{"APN20": "1", "current_density_du_per_ac": 10, "Tier": 1, "bbox": (-117.0, 34.0, -116.99, 34.01)},
|
| 432 |
]
|
| 433 |
)
|
| 434 |
+
result = compute_dwelling_units(stops, parcels)
|
| 435 |
+
assert len(result) == 0
|
| 436 |
+
|
| 437 |
+
def test_tier_density_mapping(self):
|
| 438 |
+
stops_t1 = _make_stops_gdf(
|
| 439 |
+
[
|
| 440 |
+
{"stop_id": "A", "Tier": 1, "lat": 34.0, "lon": -118.0},
|
| 441 |
+
]
|
| 442 |
+
)
|
| 443 |
+
stops_t2 = _make_stops_gdf(
|
| 444 |
+
[
|
| 445 |
+
{"stop_id": "B", "Tier": 2, "lat": 34.0, "lon": -118.0},
|
| 446 |
+
]
|
| 447 |
+
)
|
| 448 |
+
parcels = _make_parcels_gdf(
|
| 449 |
+
[
|
| 450 |
+
{
|
| 451 |
+
"APN20": "1",
|
| 452 |
+
"current_density_du_per_ac": 10,
|
| 453 |
+
"ZN19_CITY": "",
|
| 454 |
+
"ZN19_SCAG": 0,
|
| 455 |
+
"CITY": "Other",
|
| 456 |
+
"COUNTY": "LA",
|
| 457 |
+
"Tier": 1,
|
| 458 |
+
"bbox": (-118.001, 33.999, -117.999, 34.001),
|
| 459 |
+
},
|
| 460 |
+
]
|
| 461 |
+
)
|
| 462 |
+
r1 = compute_dwelling_units(stops_t1, parcels)
|
| 463 |
+
r2 = compute_dwelling_units(stops_t2, parcels)
|
| 464 |
+
assert r1["new_density_du_per_ac"].iloc[0] > r2["new_density_du_per_ac"].iloc[0]
|
| 465 |
+
|
| 466 |
+
def test_multiple_apn_aggregation(self):
|
| 467 |
+
stops = _make_stops_gdf(
|
| 468 |
+
[
|
| 469 |
+
{"stop_id": "A", "Tier": 1, "lat": 34.0, "lon": -118.0},
|
| 470 |
+
]
|
| 471 |
+
)
|
| 472 |
+
parcels = _make_parcels_gdf(
|
| 473 |
+
[
|
| 474 |
+
{
|
| 475 |
+
"APN20": "1",
|
| 476 |
+
"current_density_du_per_ac": 10,
|
| 477 |
+
"ZN19_CITY": "",
|
| 478 |
+
"ZN19_SCAG": 0,
|
| 479 |
+
"CITY": "Other",
|
| 480 |
+
"COUNTY": "LA",
|
| 481 |
+
"Tier": 1,
|
| 482 |
+
"bbox": (-118.0001, 33.9999, -117.9999, 34.0001),
|
| 483 |
+
},
|
| 484 |
+
{
|
| 485 |
+
"APN20": "2",
|
| 486 |
+
"current_density_du_per_ac": 20,
|
| 487 |
+
"ZN19_CITY": "",
|
| 488 |
+
"ZN19_SCAG": 0,
|
| 489 |
+
"CITY": "Other",
|
| 490 |
+
"COUNTY": "LA",
|
| 491 |
+
"Tier": 1,
|
| 492 |
+
"bbox": (-118.00015, 33.99985, -117.99985, 34.00015),
|
| 493 |
+
},
|
| 494 |
+
]
|
| 495 |
+
)
|
| 496 |
+
result = compute_dwelling_units(stops, parcels)
|
| 497 |
+
assert len(result) >= 1
|
| 498 |
+
apns = set(result["APN20"])
|
| 499 |
+
assert "1" in apns or "2" in apns
|
| 500 |
+
assert "area_acres" in result.columns
|
| 501 |
+
|
| 502 |
+
def test_additional_du_nonnegative(self):
|
| 503 |
+
stops = _make_stops_gdf(
|
| 504 |
+
[
|
| 505 |
+
{"stop_id": "A", "Tier": 1, "lat": 34.0, "lon": -118.0},
|
| 506 |
+
]
|
| 507 |
+
)
|
| 508 |
+
parcels = _make_parcels_gdf(
|
| 509 |
+
[
|
| 510 |
+
{
|
| 511 |
+
"APN20": "1",
|
| 512 |
+
"current_density_du_per_ac": 10,
|
| 513 |
+
"ZN19_CITY": "",
|
| 514 |
+
"ZN19_SCAG": 0,
|
| 515 |
+
"CITY": "Other",
|
| 516 |
+
"COUNTY": "LA",
|
| 517 |
+
"Tier": 1,
|
| 518 |
+
"bbox": (-118.001, 33.999, -117.999, 34.001),
|
| 519 |
+
},
|
| 520 |
+
]
|
| 521 |
+
)
|
| 522 |
+
result = compute_dwelling_units(stops, parcels)
|
| 523 |
+
assert result["additional_du"].iloc[0] >= 0
|
tests/test_gtfs_to_parcels.py
DELETED
|
@@ -1,167 +0,0 @@
|
|
| 1 |
-
from __future__ import annotations
|
| 2 |
-
|
| 3 |
-
import geopandas as gpd
|
| 4 |
-
from shapely.geometry import Point, box
|
| 5 |
-
|
| 6 |
-
from notebooks.sb79map import (
|
| 7 |
-
aggregate_parcels_to_stops,
|
| 8 |
-
assign_nearest_stop,
|
| 9 |
-
create_buffer_donuts,
|
| 10 |
-
join_scag_ca_parcels,
|
| 11 |
-
)
|
| 12 |
-
from shared.utils.constants import HALF_MI_M
|
| 13 |
-
from tests.test_helpers import _make_parcels_gdf, _make_stops_gdf
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
def _make_half_mi_buffer_gdf(stops: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
|
| 17 |
-
"""Create a GeoDataFrame of half-mile buffers around stops."""
|
| 18 |
-
return gpd.GeoDataFrame(
|
| 19 |
-
{"stop_id": stops["stop_id"].values},
|
| 20 |
-
geometry=stops.to_crs("EPSG:3310").geometry.buffer(HALF_MI_M, resolution=8),
|
| 21 |
-
crs="EPSG:3310",
|
| 22 |
-
)
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
# ---------------------------------------------------------------------------
|
| 26 |
-
# Tests: compute_scag_density
|
| 27 |
-
# ---------------------------------------------------------------------------
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
# ---------------------------------------------------------------------------
|
| 31 |
-
# Tests: trim_around_stations
|
| 32 |
-
# ---------------------------------------------------------------------------
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
# ---------------------------------------------------------------------------
|
| 36 |
-
# Tests: create_buffer_donuts
|
| 37 |
-
# ---------------------------------------------------------------------------
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
class TestCreateBufferDonuts:
|
| 41 |
-
def test_weighted_density(self):
|
| 42 |
-
stops = _make_stops_gdf(
|
| 43 |
-
[
|
| 44 |
-
{"stop_id": "A", "Tier": 1, "lat": 34.0, "lon": -118.0},
|
| 45 |
-
]
|
| 46 |
-
)
|
| 47 |
-
parcels = _make_parcels_gdf(
|
| 48 |
-
[
|
| 49 |
-
{
|
| 50 |
-
"APN20": "1",
|
| 51 |
-
"current_density_du_per_ac": 10,
|
| 52 |
-
"ZN19_CITY": "",
|
| 53 |
-
"ZN19_SCAG": 0,
|
| 54 |
-
"CITY": "Other",
|
| 55 |
-
"COUNTY": "LA",
|
| 56 |
-
"Tier": 1,
|
| 57 |
-
"bbox": (-118.001, 33.999, -117.999, 34.001),
|
| 58 |
-
},
|
| 59 |
-
]
|
| 60 |
-
)
|
| 61 |
-
result = create_buffer_donuts(stops, parcels)
|
| 62 |
-
assert len(result) >= 1
|
| 63 |
-
assert "new_density_du_per_ac" in result.columns
|
| 64 |
-
assert "new_dwelling_units" in result.columns
|
| 65 |
-
assert "current_dwelling_units" in result.columns
|
| 66 |
-
assert result["new_density_du_per_ac"].iloc[0] > 0
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
# ---------------------------------------------------------------------------
|
| 70 |
-
# Tests: join_scag_ca_parcels
|
| 71 |
-
# ---------------------------------------------------------------------------
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
class TestJoinScagCaParcels:
|
| 75 |
-
def test_outer_join(self):
|
| 76 |
-
scag = _make_parcels_gdf(
|
| 77 |
-
[
|
| 78 |
-
{"APN20": "1", "current_density_du_per_ac": 10, "new_density_du_per_ac": 20, "bbox": (0, 0, 1, 1)},
|
| 79 |
-
]
|
| 80 |
-
)
|
| 81 |
-
ca = gpd.GeoDataFrame(
|
| 82 |
-
{"PARCEL_APN": ["1", "2"], "SITE_CITY": ["LA", "SF"], "COUNTYNAME": ["Los Angeles", "San Francisco"]},
|
| 83 |
-
geometry=[box(0, 0, 1, 1), box(2, 2, 3, 3)],
|
| 84 |
-
crs="EPSG:4326",
|
| 85 |
-
)
|
| 86 |
-
result = join_scag_ca_parcels(scag, ca)
|
| 87 |
-
assert len(result) == 2
|
| 88 |
-
assert "city" in result.columns
|
| 89 |
-
assert "county" in result.columns
|
| 90 |
-
assert "apn" in result.columns
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
# ---------------------------------------------------------------------------
|
| 94 |
-
# Tests: assign_nearest_stop
|
| 95 |
-
# ---------------------------------------------------------------------------
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
class TestAssignNearestStop:
|
| 99 |
-
def test_single_stop(self):
|
| 100 |
-
stops = _make_stops_gdf(
|
| 101 |
-
[
|
| 102 |
-
{"stop_id": "A", "Tier": 1, "lat": 34.0, "lon": -118.0},
|
| 103 |
-
]
|
| 104 |
-
)
|
| 105 |
-
buffers = _make_half_mi_buffer_gdf(stops)
|
| 106 |
-
parcels = gpd.GeoDataFrame(
|
| 107 |
-
{"PARCEL_APN": ["1"]},
|
| 108 |
-
geometry=[Point(-118.0005, 34.0005).buffer(0.001)],
|
| 109 |
-
crs="EPSG:4326",
|
| 110 |
-
)
|
| 111 |
-
result = assign_nearest_stop(parcels, stops, buffers)
|
| 112 |
-
assert len(result) == 1
|
| 113 |
-
assert "clipped_geom" in result.columns
|
| 114 |
-
assert result["stop_id"].iloc[0] == "A"
|
| 115 |
-
|
| 116 |
-
def test_multi_buffer_nearest(self):
|
| 117 |
-
"""Parcel intersecting two stop buffers should be assigned to the nearest."""
|
| 118 |
-
stops = _make_stops_gdf(
|
| 119 |
-
[
|
| 120 |
-
{"stop_id": "A", "Tier": 1, "lat": 34.0, "lon": -118.0},
|
| 121 |
-
{"stop_id": "B", "Tier": 1, "lat": 34.01, "lon": -118.0},
|
| 122 |
-
]
|
| 123 |
-
)
|
| 124 |
-
buffers = _make_half_mi_buffer_gdf(stops)
|
| 125 |
-
# Parcel closer to stop A
|
| 126 |
-
parcels = gpd.GeoDataFrame(
|
| 127 |
-
{"PARCEL_APN": ["1"]},
|
| 128 |
-
geometry=[Point(-118.0001, 34.0001).buffer(0.001)],
|
| 129 |
-
crs="EPSG:4326",
|
| 130 |
-
)
|
| 131 |
-
result = assign_nearest_stop(parcels, stops, buffers)
|
| 132 |
-
assert len(result) == 1
|
| 133 |
-
assert result["stop_id"].iloc[0] == "A"
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
# ---------------------------------------------------------------------------
|
| 137 |
-
# Tests: aggregate_parcels_to_stops
|
| 138 |
-
# ---------------------------------------------------------------------------
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
class TestAggregateParcelsToStops:
|
| 142 |
-
def test_basic_aggregation(self):
|
| 143 |
-
stops = _make_stops_gdf(
|
| 144 |
-
[
|
| 145 |
-
{"stop_id": "A", "Tier": 1, "lat": 34.0, "lon": -118.0},
|
| 146 |
-
]
|
| 147 |
-
)
|
| 148 |
-
parcels = gpd.GeoDataFrame(
|
| 149 |
-
{
|
| 150 |
-
"stop_id": ["A"],
|
| 151 |
-
"clipped_geom": [box(-118.001, 33.999, -117.999, 34.001)],
|
| 152 |
-
"new_dwelling_units": [100],
|
| 153 |
-
"current_dwelling_units": [50],
|
| 154 |
-
"additional_du": [50],
|
| 155 |
-
"CITY": ["LOS ANGELES"],
|
| 156 |
-
"COUNTY": ["LOS ANGELES"],
|
| 157 |
-
"geometry": [box(-118.001, 33.999, -117.999, 34.001)],
|
| 158 |
-
},
|
| 159 |
-
crs="EPSG:4326",
|
| 160 |
-
)
|
| 161 |
-
|
| 162 |
-
result = aggregate_parcels_to_stops(parcels, stops)
|
| 163 |
-
assert len(result) == 1
|
| 164 |
-
assert result["parcel_acres"].iloc[0] > 0
|
| 165 |
-
assert result["additional_dwelling_units"].iloc[0] == 50 # 100 - 50
|
| 166 |
-
assert result["city"].iloc[0] == "LOS ANGELES"
|
| 167 |
-
assert result["county"].iloc[0] == "LOS ANGELES"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
tests/test_helpers.py
CHANGED
|
@@ -1,6 +1,8 @@
|
|
| 1 |
import geopandas as gpd
|
| 2 |
from shapely.geometry import Point, box
|
| 3 |
|
|
|
|
|
|
|
| 4 |
|
| 5 |
def _make_parcels_gdf(parcels_data: list[dict]) -> gpd.GeoDataFrame:
|
| 6 |
records = []
|
|
@@ -20,7 +22,7 @@ def _make_parcels_gdf(parcels_data: list[dict]) -> gpd.GeoDataFrame:
|
|
| 20 |
if k not in rec and k != "bbox":
|
| 21 |
rec[k] = v
|
| 22 |
records.append(rec)
|
| 23 |
-
return gpd.GeoDataFrame(records, crs=
|
| 24 |
|
| 25 |
|
| 26 |
def _make_stops_gdf(stops_data: list[dict]) -> gpd.GeoDataFrame:
|
|
@@ -35,4 +37,4 @@ def _make_stops_gdf(stops_data: list[dict]) -> gpd.GeoDataFrame:
|
|
| 35 |
"geometry": Point(s["lon"], s["lat"]),
|
| 36 |
}
|
| 37 |
)
|
| 38 |
-
return gpd.GeoDataFrame(records, crs=
|
|
|
|
| 1 |
import geopandas as gpd
|
| 2 |
from shapely.geometry import Point, box
|
| 3 |
|
| 4 |
+
from shared.utils.constants import WGS84_GCS_CRS
|
| 5 |
+
|
| 6 |
|
| 7 |
def _make_parcels_gdf(parcels_data: list[dict]) -> gpd.GeoDataFrame:
|
| 8 |
records = []
|
|
|
|
| 22 |
if k not in rec and k != "bbox":
|
| 23 |
rec[k] = v
|
| 24 |
records.append(rec)
|
| 25 |
+
return gpd.GeoDataFrame(records, crs=WGS84_GCS_CRS)
|
| 26 |
|
| 27 |
|
| 28 |
def _make_stops_gdf(stops_data: list[dict]) -> gpd.GeoDataFrame:
|
|
|
|
| 37 |
"geometry": Point(s["lon"], s["lat"]),
|
| 38 |
}
|
| 39 |
)
|
| 40 |
+
return gpd.GeoDataFrame(records, crs=WGS84_GCS_CRS)
|
tests/utils/test_geoprocessing.py
CHANGED
|
@@ -2,7 +2,7 @@ import geopandas as gpd
|
|
| 2 |
import pytest
|
| 3 |
from shapely.geometry import LineString, Point, Polygon, box
|
| 4 |
|
| 5 |
-
from shared.utils.constants import
|
| 6 |
from shared.utils.geoprocessing import clip_to_buffer_rings
|
| 7 |
|
| 8 |
# EPSG:2229 coordinates for a point in central LA
|
|
@@ -13,7 +13,7 @@ def _source(x: float = LA_X, y: float = LA_Y) -> gpd.GeoDataFrame:
|
|
| 13 |
return gpd.GeoDataFrame(
|
| 14 |
{"source_id": ["S1"]},
|
| 15 |
geometry=[Point(x, y)],
|
| 16 |
-
crs=
|
| 17 |
)
|
| 18 |
|
| 19 |
|
|
@@ -21,7 +21,7 @@ def _point_feature(x: float, y: float) -> gpd.GeoDataFrame:
|
|
| 21 |
return gpd.GeoDataFrame(
|
| 22 |
{"feature_id": ["F1"]},
|
| 23 |
geometry=[Point(x, y)],
|
| 24 |
-
crs=
|
| 25 |
)
|
| 26 |
|
| 27 |
|
|
@@ -29,7 +29,7 @@ def _line_feature(x0: float, y0: float, x1: float, y1: float) -> gpd.GeoDataFram
|
|
| 29 |
return gpd.GeoDataFrame(
|
| 30 |
{"feature_id": ["F1"]},
|
| 31 |
geometry=[LineString([(x0, y0), (x1, y1)])],
|
| 32 |
-
crs=
|
| 33 |
)
|
| 34 |
|
| 35 |
|
|
@@ -37,7 +37,7 @@ def _polygon_feature(cx: float, cy: float, half: float = 50) -> gpd.GeoDataFrame
|
|
| 37 |
return gpd.GeoDataFrame(
|
| 38 |
{"feature_id": ["F1"]},
|
| 39 |
geometry=[box(cx - half, cy - half, cx + half, cy + half)],
|
| 40 |
-
crs=
|
| 41 |
)
|
| 42 |
|
| 43 |
|
|
|
|
| 2 |
import pytest
|
| 3 |
from shapely.geometry import LineString, Point, Polygon, box
|
| 4 |
|
| 5 |
+
from shared.utils.constants import SCAG_FT_CRS
|
| 6 |
from shared.utils.geoprocessing import clip_to_buffer_rings
|
| 7 |
|
| 8 |
# EPSG:2229 coordinates for a point in central LA
|
|
|
|
| 13 |
return gpd.GeoDataFrame(
|
| 14 |
{"source_id": ["S1"]},
|
| 15 |
geometry=[Point(x, y)],
|
| 16 |
+
crs=SCAG_FT_CRS,
|
| 17 |
)
|
| 18 |
|
| 19 |
|
|
|
|
| 21 |
return gpd.GeoDataFrame(
|
| 22 |
{"feature_id": ["F1"]},
|
| 23 |
geometry=[Point(x, y)],
|
| 24 |
+
crs=SCAG_FT_CRS,
|
| 25 |
)
|
| 26 |
|
| 27 |
|
|
|
|
| 29 |
return gpd.GeoDataFrame(
|
| 30 |
{"feature_id": ["F1"]},
|
| 31 |
geometry=[LineString([(x0, y0), (x1, y1)])],
|
| 32 |
+
crs=SCAG_FT_CRS,
|
| 33 |
)
|
| 34 |
|
| 35 |
|
|
|
|
| 37 |
return gpd.GeoDataFrame(
|
| 38 |
{"feature_id": ["F1"]},
|
| 39 |
geometry=[box(cx - half, cy - half, cx + half, cy + half)],
|
| 40 |
+
crs=SCAG_FT_CRS,
|
| 41 |
)
|
| 42 |
|
| 43 |
|