Spaces:
Sleeping

dn commited on
Commit
efd0240
·
1 Parent(s): cbe7012

optimize clip_to_buffer_rings, compute_dwelling_units, compute_scag_density

Browse files
shared/pipelines/sb79.py CHANGED
@@ -22,31 +22,35 @@ 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)
28
-
29
- # --- Tier assignment (priority order: subway > high-freq rail > medium commuter > low light rail) ---
30
- has_subway = result_df["route_types"].apply(lambda rts: "1" in rts)
31
- has_commuter = result_df["route_types"].apply(lambda rts: "2" in rts)
32
- has_light_rail = result_df["route_types"].apply(lambda rts: "0" in rts)
 
 
 
 
 
 
 
33
  arrivals = result_df["total_train_arrivals"]
 
 
 
34
 
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
 
44
- # --- Apply route-level overrides ---
45
- if tier_overrides:
46
- for rid, tier in tier_overrides.items():
47
- mask = result_df["route_ids"].apply(lambda rids, rid=rid: rid in rids)
48
- result_df.loc[mask, "Tier"] = tier
49
-
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"],
@@ -57,6 +61,10 @@ def assign_tier_to_stops_from_gtfs(
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),
@@ -80,8 +88,7 @@ def _empty_result() -> gpd.GeoDataFrame:
80
 
81
 
82
  def compute_scag_density(scag_parcels: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
83
- df = scag_parcels.copy()
84
- is_la = df["CITY"] == "Los Angeles"
85
 
86
  SCAG_FIXED = {
87
  "1123": 18,
@@ -115,12 +122,12 @@ def compute_scag_density(scag_parcels: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
115
  }
116
  SCAG_AREA_BASED = {"1110": 1, "1111": 1, "1112": 1, "1113": 1, "1121": 3, "1122": 3, "1140": 3}
117
 
118
- zn19_scag = df["ZN19_SCAG"].astype(str)
119
  scag_density = zn19_scag.map(SCAG_FIXED)
120
 
121
  area_mask = zn19_scag.isin(SCAG_AREA_BASED)
122
  if area_mask.any():
123
- area_acres = df.loc[area_mask].to_crs(SCAG_FT_CRS).area / 43560
124
  area_acres = area_acres.replace(0, np.nan)
125
  scag_density.loc[area_mask] = zn19_scag[area_mask].map(SCAG_AREA_BASED) / area_acres
126
 
@@ -158,7 +165,7 @@ def compute_scag_density(scag_parcels: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
158
  ]
159
 
160
  if is_la.any():
161
- la_zones = df.loc[is_la, "ZN19_CITY"]
162
  la_density = pd.Series(np.nan, index=la_zones.index)
163
  for code, density in LA_ZONES:
164
  unmatched = la_density.isna()
@@ -168,18 +175,12 @@ def compute_scag_density(scag_parcels: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
168
  la_density.loc[mask] = density
169
  scag_density.loc[is_la] = la_density
170
 
171
- df["current_density_du_per_ac"] = pd.to_numeric(scag_density, errors="coerce")
172
- return df
173
 
174
 
175
- def compute_dwelling_units(
176
- stops_gdf: gpd.GeoDataFrame,
177
- scag_density: gpd.GeoDataFrame,
178
- ) -> gpd.GeoDataFrame:
179
- stops_trimmed = stops_gdf[["stop_id", "Tier", "geometry"]]
180
- scag_clean = scag_density.drop(columns=["Tier"], errors="ignore")
181
-
182
- zone_densities = {
183
  ("200 ft", 1): 160,
184
  ("200 ft", 2): 140,
185
  ("1320 ft", 1): 120,
@@ -187,24 +188,36 @@ def compute_dwelling_units(
187
  ("2640 ft", 1): 100,
188
  ("2640 ft", 2): 80,
189
  }
190
- buffer_distances = [200, 1320, 2640]
 
 
 
 
 
 
 
 
 
 
 
 
 
191
 
192
  rings = clip_to_buffer_rings(
193
  features_gdf=scag_clean,
194
  sources_gdf=stops_trimmed,
195
- buffer_distances=buffer_distances,
196
  buffer_crs=SCAG_FT_CRS,
197
  donut_how="difference",
198
  )
199
 
200
- for ring, distance in zip(rings, buffer_distances, strict=False):
201
  ring["buffer_zone_id"] = f"{distance} ft"
202
 
203
  buffed_parcels = gpd.GeoDataFrame(pd.concat(rings, ignore_index=True))
 
204
  buffed_parcels["area_sqft"] = buffed_parcels.area
205
- buffed_parcels["zone_density"] = buffed_parcels.set_index(["buffer_zone_id", "Tier"]).index.map(
206
- pd.Series(zone_densities)
207
- )
208
  buffed_parcels["area_x_density"] = buffed_parcels["area_sqft"] * buffed_parcels["zone_density"]
209
 
210
  agg = buffed_parcels.groupby("APN20").agg(
@@ -217,10 +230,9 @@ def compute_dwelling_units(
217
  COUNTY=("COUNTY", "first"),
218
  CITY=("CITY", "first"),
219
  buffer_zone_id=("buffer_zone_id", "first"),
 
220
  )
221
 
222
- geom_agg = buffed_parcels[["APN20", "geometry"]].dissolve(by="APN20")["geometry"]
223
-
224
  area_acres = agg["area_sqft_total"] / 43560
225
  weighted_density = np.where(
226
  (agg["area_sqft_total"] > 0) & (agg["current_density_du_per_ac"].notna()),
@@ -231,7 +243,7 @@ def compute_dwelling_units(
231
  by_apn = gpd.GeoDataFrame(
232
  {
233
  "APN20": agg.index,
234
- "geometry": geom_agg.values,
235
  "area_acres": area_acres.values,
236
  "new_density_du_per_ac": weighted_density,
237
  "new_dwelling_units": weighted_density * area_acres.values,
@@ -247,6 +259,7 @@ def compute_dwelling_units(
247
  geometry="geometry",
248
  crs=buffed_parcels.crs,
249
  )
 
250
  by_apn["additional_du"] = np.maximum(
251
  0,
252
  by_apn.get("new_dwelling_units", 0) - by_apn.get("current_dwelling_units", 0),
 
22
  if result_df.empty:
23
  return _empty_result()
24
 
25
+ exploded = (
26
+ result_df[["stop_id", "route_types", "n_arrivals"]]
27
+ .explode(["route_types", "n_arrivals"])
28
+ .assign(route_type_int=lambda df: df["route_types"].astype(int))
29
+ )
30
+ train = exploded[exploded["route_type_int"].isin([0, 1, 2])]
31
+
32
+ train_arrivals = train.groupby("stop_id")["n_arrivals"].sum()
33
+ type_sets = train.groupby("stop_id")["route_type_int"].agg(set)
34
+
35
+ result_df = result_df.assign(
36
+ total_train_arrivals=result_df["stop_id"].map(train_arrivals).fillna(0),
37
+ _types=result_df["stop_id"].map(type_sets).fillna("").apply(lambda s: s if isinstance(s, set) else set()),
38
+ )
39
+
40
  arrivals = result_df["total_train_arrivals"]
41
+ has_subway = result_df["_types"].map(lambda s: 1 in s)
42
+ has_commuter = result_df["_types"].map(lambda s: 2 in s)
43
+ has_light_rail = result_df["_types"].map(lambda s: 0 in s)
44
 
45
  result_df["Tier"] = pd.Series(pd.NA, index=result_df.index).case_when(
46
  [
47
  (has_subway, 1),
48
+ (has_commuter & (arrivals >= 72), 1),
49
+ (has_commuter & (arrivals >= 48), 2),
50
  (has_light_rail, 2),
51
  ]
52
  )
53
 
 
 
 
 
 
 
54
  result_df = result_df.dropna(subset=["Tier"]).assign(
55
  Tier=lambda df: df["Tier"].astype(int),
56
  n_arrivals=lambda df: df["total_train_arrivals"],
 
61
  if result_df.empty:
62
  return _empty_result()
63
 
64
+ if tier_overrides:
65
+ for rid, tier in tier_overrides.items():
66
+ result_df.loc[result_df["route_ids"].str.contains(rid, regex=False), "Tier"] = tier
67
+
68
  return gpd.GeoDataFrame(
69
  result_df,
70
  geometry=gpd.points_from_xy(result_df["stop_lon"], result_df["stop_lat"], crs=WGS84_GCS_CRS),
 
88
 
89
 
90
  def compute_scag_density(scag_parcels: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
91
+ is_la = scag_parcels["CITY"] == "Los Angeles"
 
92
 
93
  SCAG_FIXED = {
94
  "1123": 18,
 
122
  }
123
  SCAG_AREA_BASED = {"1110": 1, "1111": 1, "1112": 1, "1113": 1, "1121": 3, "1122": 3, "1140": 3}
124
 
125
+ zn19_scag = scag_parcels["ZN19_SCAG"].astype(str)
126
  scag_density = zn19_scag.map(SCAG_FIXED)
127
 
128
  area_mask = zn19_scag.isin(SCAG_AREA_BASED)
129
  if area_mask.any():
130
+ area_acres = scag_parcels.loc[area_mask].to_crs(SCAG_FT_CRS).area / 43560
131
  area_acres = area_acres.replace(0, np.nan)
132
  scag_density.loc[area_mask] = zn19_scag[area_mask].map(SCAG_AREA_BASED) / area_acres
133
 
 
165
  ]
166
 
167
  if is_la.any():
168
+ la_zones = scag_parcels.loc[is_la, "ZN19_CITY"]
169
  la_density = pd.Series(np.nan, index=la_zones.index)
170
  for code, density in LA_ZONES:
171
  unmatched = la_density.isna()
 
175
  la_density.loc[mask] = density
176
  scag_density.loc[is_la] = la_density
177
 
178
+ scag_parcels["current_density_du_per_ac"] = pd.to_numeric(scag_density, errors="coerce")
179
+ return scag_parcels
180
 
181
 
182
+ _ZONE_DENSITIES = pd.Series(
183
+ {
 
 
 
 
 
 
184
  ("200 ft", 1): 160,
185
  ("200 ft", 2): 140,
186
  ("1320 ft", 1): 120,
 
188
  ("2640 ft", 1): 100,
189
  ("2640 ft", 2): 80,
190
  }
191
+ )
192
+
193
+ _BUFFER_DISTANCES = [200, 1320, 2640]
194
+
195
+ _KEEP_COLS = ["APN20", "current_density_du_per_ac", "ZN19_CITY", "ZN19_SCAG", "COUNTY", "CITY", "geometry"]
196
+
197
+
198
+ def compute_dwelling_units(
199
+ stops_gdf: gpd.GeoDataFrame,
200
+ scag_density: gpd.GeoDataFrame,
201
+ ) -> gpd.GeoDataFrame:
202
+ stops_trimmed = stops_gdf[["stop_id", "Tier", "geometry"]]
203
+
204
+ scag_clean = scag_density.drop(columns=["Tier"], errors="ignore")[[c for c in _KEEP_COLS if c in scag_density.columns]]
205
 
206
  rings = clip_to_buffer_rings(
207
  features_gdf=scag_clean,
208
  sources_gdf=stops_trimmed,
209
+ buffer_distances=_BUFFER_DISTANCES,
210
  buffer_crs=SCAG_FT_CRS,
211
  donut_how="difference",
212
  )
213
 
214
+ for ring, distance in zip(rings, _BUFFER_DISTANCES, strict=False):
215
  ring["buffer_zone_id"] = f"{distance} ft"
216
 
217
  buffed_parcels = gpd.GeoDataFrame(pd.concat(rings, ignore_index=True))
218
+
219
  buffed_parcels["area_sqft"] = buffed_parcels.area
220
+ buffed_parcels["zone_density"] = buffed_parcels.set_index(["buffer_zone_id", "Tier"]).index.map(_ZONE_DENSITIES)
 
 
221
  buffed_parcels["area_x_density"] = buffed_parcels["area_sqft"] * buffed_parcels["zone_density"]
222
 
223
  agg = buffed_parcels.groupby("APN20").agg(
 
230
  COUNTY=("COUNTY", "first"),
231
  CITY=("CITY", "first"),
232
  buffer_zone_id=("buffer_zone_id", "first"),
233
+ geometry=("geometry", unary_union),
234
  )
235
 
 
 
236
  area_acres = agg["area_sqft_total"] / 43560
237
  weighted_density = np.where(
238
  (agg["area_sqft_total"] > 0) & (agg["current_density_du_per_ac"].notna()),
 
243
  by_apn = gpd.GeoDataFrame(
244
  {
245
  "APN20": agg.index,
246
+ "geometry": agg["geometry"].values,
247
  "area_acres": area_acres.values,
248
  "new_density_du_per_ac": weighted_density,
249
  "new_dwelling_units": weighted_density * area_acres.values,
 
259
  geometry="geometry",
260
  crs=buffed_parcels.crs,
261
  )
262
+
263
  by_apn["additional_du"] = np.maximum(
264
  0,
265
  by_apn.get("new_dwelling_units", 0) - by_apn.get("current_dwelling_units", 0),
shared/utils/geoprocessing.py CHANGED
@@ -14,23 +14,31 @@ def clip_to_buffer_rings(
14
  ) -> list[gpd.GeoDataFrame]:
15
  distances = sorted(buffer_distances)
16
  ring_definitions = [(dist, distances[i - 1] if i > 0 else None) for i, dist in enumerate(distances)]
17
- sources_reprojected = sources_gdf.to_crs(buffer_crs).geometry
18
 
19
- buffers = {
 
 
 
20
  dist: gpd.GeoDataFrame(
21
- sources_gdf.drop(columns="geometry"),
22
- geometry=sources_reprojected.buffer(dist),
23
  crs=buffer_crs,
24
  )
25
  for dist in distances
26
  }
 
27
 
28
  features_reproj = features_gdf.to_crs(buffer_crs)
29
 
30
- largest = buffers[distances[-1]]
31
- candidates = gpd.sjoin(features_reproj, largest, how="inner", predicate="intersects")
 
32
 
33
- clipped = {dist: gpd.overlay(candidates, buf[["geometry"]], how="intersection") for dist, buf in buffers.items()}
 
 
 
 
34
 
35
  rings = []
36
  for outer, inner in ring_definitions:
@@ -38,5 +46,5 @@ def clip_to_buffer_rings(
38
  if inner is None or outer_clip.empty:
39
  rings.append(outer_clip)
40
  else:
41
- rings.append(gpd.overlay(outer_clip, buffers[inner][["geometry"]], how=donut_how))
42
  return rings
 
14
  ) -> list[gpd.GeoDataFrame]:
15
  distances = sorted(buffer_distances)
16
  ring_definitions = [(dist, distances[i - 1] if i > 0 else None) for i, dist in enumerate(distances)]
 
17
 
18
+ sources_reproj = sources_gdf.to_crs(buffer_crs)
19
+ source_geom = sources_reproj.geometry
20
+
21
+ attr_buffers = {
22
  dist: gpd.GeoDataFrame(
23
+ sources_reproj.drop(columns="geometry"),
24
+ geometry=source_geom.buffer(dist),
25
  crs=buffer_crs,
26
  )
27
  for dist in distances
28
  }
29
+ geom_buffers = {dist: gpd.GeoDataFrame(geometry=source_geom.buffer(dist), crs=buffer_crs) for dist in distances}
30
 
31
  features_reproj = features_gdf.to_crs(buffer_crs)
32
 
33
+ candidates = gpd.sjoin(features_reproj, attr_buffers[distances[-1]], how="inner", predicate="intersects").drop(
34
+ columns=["index_right"], errors="ignore"
35
+ )
36
 
37
+ clipped = {}
38
+ current = candidates
39
+ for dist in reversed(distances):
40
+ current = gpd.overlay(current, geom_buffers[dist], how="intersection")
41
+ clipped[dist] = current
42
 
43
  rings = []
44
  for outer, inner in ring_definitions:
 
46
  if inner is None or outer_clip.empty:
47
  rings.append(outer_clip)
48
  else:
49
+ rings.append(gpd.overlay(outer_clip, geom_buffers[inner], how=donut_how))
50
  return rings