Spaces:
Sleeping

dn commited on
Commit
7af92cf
·
1 Parent(s): 5320d41

create_buffer_donuts refactor WIP.

Browse files
shared/pipelines/sb79.py CHANGED
@@ -7,6 +7,16 @@ import numpy as np
7
  import pandas as pd
8
 
9
  from shared.api.gtfs import parent_stations_from_gtfs
 
 
 
 
 
 
 
 
 
 
10
 
11
 
12
  def assign_tier_to_stops_from_gtfs(
@@ -136,7 +146,7 @@ def compute_scag_density(scag_parcels: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
136
  )
137
 
138
  zn19_scag = df["ZN19_SCAG"].astype(str)
139
- area_acres = df.to_crs("EPSG:2229").area / 43560
140
  scag_density = zn19_scag.case_when(
141
  [
142
  (zn19_scag == "1110", 1 / area_acres.replace(0, np.nan)),
@@ -168,3 +178,30 @@ def compute_scag_density(scag_parcels: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
168
  df.loc[is_la, "current_density_du_per_ac"] = la_density
169
  df["current_density_du_per_ac"] = pd.to_numeric(df["current_density_du_per_ac"], errors="coerce")
170
  return df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  import pandas as pd
8
 
9
  from shared.api.gtfs import parent_stations_from_gtfs
10
+ from shared.utils.constants import SCAG_FT_CSR
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(
 
146
  )
147
 
148
  zn19_scag = df["ZN19_SCAG"].astype(str)
149
+ area_acres = df.to_crs(SCAG_FT_CSR).area / 43560
150
  scag_density = zn19_scag.case_when(
151
  [
152
  (zn19_scag == "1110", 1 / area_acres.replace(0, np.nan)),
 
178
  df.loc[is_la, "current_density_du_per_ac"] = la_density
179
  df["current_density_du_per_ac"] = pd.to_numeric(df["current_density_du_per_ac"], errors="coerce")
180
  return df
181
+
182
+
183
+ def trim_around_stations(
184
+ parcels_gdf: gpd.GeoDataFrame,
185
+ stops_gdf: gpd.GeoDataFrame,
186
+ buffer_dist_ft: int,
187
+ ) -> gpd.GeoDataFrame:
188
+ zone_map = {200: "200ft", 1320: "qtr_mi", 2640: "half_mi"}
189
+
190
+ buffer_df = gpd.GeoDataFrame(
191
+ {"stop_id": stops_gdf["stop_id"].values, "Tier": stops_gdf["Tier"].values},
192
+ geometry=stops_gdf.to_crs(SCAG_FT_CSR).geometry.buffer(buffer_dist_ft),
193
+ crs=SCAG_FT_CSR,
194
+ ).to_crs("EPSG:4326")
195
+
196
+ joined = gpd.sjoin(
197
+ parcels_gdf.to_crs("EPSG:4326"),
198
+ buffer_df[["stop_id", "Tier", "geometry"]],
199
+ how="inner",
200
+ predicate="intersects",
201
+ ).assign(Tier=lambda df: df["Tier_right"])
202
+
203
+ joined = joined.drop(columns=[c for c in ["Tier_left", "Tier_right"] if c in joined.columns])
204
+
205
+ trimmed = gpd.overlay(joined, buffer_df[["stop_id", "geometry"]], how="intersection")
206
+ trimmed["buffer_zone_id"] = zone_map.get(buffer_dist_ft, f"{buffer_dist_ft}ft")
207
+ return trimmed
shared/utils/constants.py CHANGED
@@ -9,11 +9,4 @@ SCAG_OUT_FIELDS = (
9
  )
10
  HALF_MI_M = 804.7
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
- }
 
9
  )
10
  HALF_MI_M = 804.7
11
 
12
+ SCAG_FT_CSR = "EPSG:2229"
 
 
 
 
 
 
 
shared/utils/geoprocessing.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 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 = "EPSG:2229",
11
+ donut_how: Literal["difference", "union"] = "difference",
12
+ ) -> list[gpd.GeoDataFrame]:
13
+ """Clip features to concentric donut rings buffered around source geometries.
14
+
15
+ Parameters
16
+ ----------
17
+ features_gdf:
18
+ Features to clip.
19
+ sources_gdf:
20
+ Source geometries to buffer. All non-geometry columns are carried
21
+ through to the result.
22
+ buffer_distances:
23
+ Buffer distances in the units of ``buffer_crs``. Rings are built
24
+ from smallest to largest — e.g. ``[200, 1320, 2640]`` produces a
25
+ 200ft disc, a 200–1320ft donut, and a 1320–2640ft donut.
26
+ buffer_crs:
27
+ CRS to reproject into before buffering and spatial operations.
28
+ Defaults to EPSG:2229 (California State Plane, feet).
29
+ donut_how:
30
+ How to subtract the inner buffer from the outer clip when forming
31
+ donuts. ``"difference"`` produces smooth donut rings clipped to the
32
+ buffer boundary; ``"union"`` retains the full parcel geometry within
33
+ the outer ring without cutting at the inner boundary.
34
+
35
+ Returns
36
+ -------
37
+ list[gpd.GeoDataFrame]
38
+ One GeoDataFrame per distance in ``buffer_distances``, in ascending
39
+ order. The first entry is the innermost disc; subsequent entries are
40
+ donuts. Results are returned in ``buffer_crs``.
41
+ """
42
+ distances = sorted(buffer_distances)
43
+ ring_definitions = [(dist, distances[i - 1] if i > 0 else None) for i, dist in enumerate(distances)]
44
+
45
+ sources_reprojected = sources_gdf.to_crs(buffer_crs).geometry
46
+
47
+ buffers = {
48
+ dist: gpd.GeoDataFrame(
49
+ sources_gdf.drop(columns="geometry"),
50
+ geometry=sources_reprojected.buffer(dist),
51
+ crs=buffer_crs,
52
+ )
53
+ for dist in distances
54
+ }
55
+
56
+ features_reproj = features_gdf.to_crs(buffer_crs)
57
+
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()
65
+ }
66
+
67
+ rings = []
68
+ for outer, inner in ring_definitions:
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
tests/{test_arcgis.py → api/test_arcgis.py} RENAMED
File without changes
tests/{test_gtfs.py → api/test_gtfs.py} RENAMED
File without changes
tests/{test_sb79.py → pipelines/test_sb79.py} RENAMED
@@ -3,7 +3,11 @@ import tempfile
3
  import zipfile
4
  from pathlib import Path
5
 
6
- from shared.pipelines.sb79 import assign_tier_to_stops_from_gtfs
 
 
 
 
7
 
8
 
9
  def _make_gtfs_zip(
@@ -440,3 +444,70 @@ class TestParseGtfsZip:
440
  assert "1" in result.iloc[0]["route_types"]
441
  finally:
442
  path.unlink(missing_ok=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  import zipfile
4
  from pathlib import Path
5
 
6
+ import numpy as np
7
+ import pytest
8
+
9
+ from shared.pipelines.sb79 import assign_tier_to_stops_from_gtfs, compute_scag_density, trim_around_stations
10
+ from tests.test_helpers import _make_parcels_gdf, _make_stops_gdf
11
 
12
 
13
  def _make_gtfs_zip(
 
444
  assert "1" in result.iloc[0]["route_types"]
445
  finally:
446
  path.unlink(missing_ok=True)
447
+
448
+
449
+ class TestComputeScagDensity:
450
+ def test_la_density(self):
451
+ parcels = _make_parcels_gdf(
452
+ [
453
+ {"APN20": "1", "ZN19_CITY": "RD1.5", "CITY": "Los Angeles", "bbox": (0, 0, 100, 100)},
454
+ ]
455
+ )
456
+ result = compute_scag_density(parcels)
457
+ assert "current_density_du_per_ac" in result.columns
458
+ # RD1.5 → 43560 / 1500 = 29.04
459
+ assert result.iloc[0]["current_density_du_per_ac"] == pytest.approx(29.04, rel=0.01)
460
+
461
+ def test_non_la_density(self):
462
+ parcels = _make_parcels_gdf(
463
+ [
464
+ {"APN20": "1", "ZN19_SCAG": 1111, "CITY": "Other", "bbox": (-118.3, 34.0, -118.2, 34.1)},
465
+ ]
466
+ )
467
+ result = compute_scag_density(parcels)
468
+ # 1111 → 1 / area_acres (area-dependent)
469
+ assert result.iloc[0]["current_density_du_per_ac"] > 0
470
+
471
+ def test_non_la_density_zero_default(self):
472
+ """Unrecognized ZN19_SCAG codes should get NaN (excluded downstream)."""
473
+ parcels = _make_parcels_gdf(
474
+ [
475
+ {"APN20": "1", "ZN19_SCAG": 9999, "CITY": "Other", "bbox": (-118.3, 34.0, -118.2, 34.1)},
476
+ ]
477
+ )
478
+ result = compute_scag_density(parcels)
479
+ assert np.isnan(result.iloc[0]["current_density_du_per_ac"])
480
+
481
+
482
+ class TestTrimAroundStations:
483
+ def test_parcel_within_buffer(self):
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
+ {"APN20": "1", "current_density_du_per_ac": 10, "Tier": 1, "bbox": (-118.001, 33.999, -117.999, 34.001)},
493
+ ]
494
+ )
495
+ result = trim_around_stations(parcels, stops, 200)
496
+ assert len(result) >= 1
497
+ assert "buffer_zone_id" in result.columns
498
+ assert result["buffer_zone_id"].iloc[0] == "200ft"
499
+
500
+ def test_parcel_far_from_stop(self):
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 = trim_around_stations(parcels, stops, 200)
513
+ assert len(result) == 0 # no intersection
tests/test_gtfs_to_parcels.py CHANGED
@@ -1,8 +1,6 @@
1
  from __future__ import annotations
2
 
3
  import geopandas as gpd
4
- import numpy as np
5
- import pytest
6
  from shapely.geometry import Point, box
7
 
8
  from notebooks.sb79map import (
@@ -10,25 +8,9 @@ from notebooks.sb79map import (
10
  assign_nearest_stop,
11
  create_buffer_donuts,
12
  join_scag_ca_parcels,
13
- trim_around_stations,
14
  )
15
- from shared.pipelines.sb79 import compute_scag_density
16
  from shared.utils.constants import HALF_MI_M
17
-
18
-
19
- def _make_stops_gdf(stops_data: list[dict]) -> gpd.GeoDataFrame:
20
- """Create a stops GeoDataFrame from a list of dicts."""
21
- records = []
22
- for s in stops_data:
23
- records.append(
24
- {
25
- "stop_id": s["stop_id"],
26
- "stop_name": s.get("stop_name", ""),
27
- "Tier": s["Tier"],
28
- "geometry": Point(s["lon"], s["lat"]),
29
- }
30
- )
31
- return gpd.GeoDataFrame(records, crs="EPSG:4326")
32
 
33
 
34
  def _make_half_mi_buffer_gdf(stops: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
@@ -40,105 +22,16 @@ def _make_half_mi_buffer_gdf(stops: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
40
  )
41
 
42
 
43
- def _make_parcels_gdf(parcels_data: list[dict]) -> gpd.GeoDataFrame:
44
- """Create a parcels GeoDataFrame from a list of dicts."""
45
- records = []
46
- for p in parcels_data:
47
- rec = {
48
- "APN20": p["APN20"],
49
- "current_density_du_per_ac": p.get("current_density_du_per_ac", 0),
50
- "ZN19_CITY": p.get("ZN19_CITY", ""),
51
- "ZN19_SCAG": p.get("ZN19_SCAG", 0),
52
- "CITY": p.get("CITY", ""),
53
- "COUNTY": p.get("COUNTY", ""),
54
- "Tier": p.get("Tier", 1),
55
- "geometry": box(*p["bbox"]),
56
- }
57
- # Include any extra columns passed in the dict
58
- for k, v in p.items():
59
- if k not in rec and k != "bbox":
60
- rec[k] = v
61
- records.append(rec)
62
- return gpd.GeoDataFrame(records, crs="EPSG:4326")
63
-
64
-
65
  # ---------------------------------------------------------------------------
66
  # Tests: compute_scag_density
67
  # ---------------------------------------------------------------------------
68
 
69
 
70
- class TestComputeScagDensity:
71
- def test_la_density(self):
72
- parcels = _make_parcels_gdf(
73
- [
74
- {"APN20": "1", "ZN19_CITY": "RD1.5", "CITY": "Los Angeles", "bbox": (0, 0, 100, 100)},
75
- ]
76
- )
77
- result = compute_scag_density(parcels)
78
- assert "current_density_du_per_ac" in result.columns
79
- # RD1.5 → 43560 / 1500 = 29.04
80
- assert result.iloc[0]["current_density_du_per_ac"] == pytest.approx(29.04, rel=0.01)
81
-
82
- def test_non_la_density(self):
83
- parcels = _make_parcels_gdf(
84
- [
85
- {"APN20": "1", "ZN19_SCAG": 1111, "CITY": "Other", "bbox": (-118.3, 34.0, -118.2, 34.1)},
86
- ]
87
- )
88
- result = compute_scag_density(parcels)
89
- # 1111 → 1 / area_acres (area-dependent)
90
- assert result.iloc[0]["current_density_du_per_ac"] > 0
91
-
92
- def test_non_la_density_zero_default(self):
93
- """Unrecognized ZN19_SCAG codes should get NaN (excluded downstream)."""
94
- parcels = _make_parcels_gdf(
95
- [
96
- {"APN20": "1", "ZN19_SCAG": 9999, "CITY": "Other", "bbox": (-118.3, 34.0, -118.2, 34.1)},
97
- ]
98
- )
99
- result = compute_scag_density(parcels)
100
- assert np.isnan(result.iloc[0]["current_density_du_per_ac"])
101
-
102
-
103
  # ---------------------------------------------------------------------------
104
  # Tests: trim_around_stations
105
  # ---------------------------------------------------------------------------
106
 
107
 
108
- class TestTrimAroundStations:
109
- def test_parcel_within_buffer(self):
110
- stops = _make_stops_gdf(
111
- [
112
- {"stop_id": "A", "Tier": 1, "lat": 34.0, "lon": -118.0},
113
- ]
114
- )
115
- # Parcel right next to the stop
116
- parcels = _make_parcels_gdf(
117
- [
118
- {"APN20": "1", "current_density_du_per_ac": 10, "Tier": 1, "bbox": (-118.001, 33.999, -117.999, 34.001)},
119
- ]
120
- )
121
- result = trim_around_stations(parcels, stops, 200)
122
- assert len(result) >= 1
123
- assert "buffer_zone_id" in result.columns
124
- assert result["buffer_zone_id"].iloc[0] == "200ft"
125
-
126
- def test_parcel_far_from_stop(self):
127
- stops = _make_stops_gdf(
128
- [
129
- {"stop_id": "A", "Tier": 1, "lat": 34.0, "lon": -118.0},
130
- ]
131
- )
132
- # Parcel far away
133
- parcels = _make_parcels_gdf(
134
- [
135
- {"APN20": "1", "current_density_du_per_ac": 10, "Tier": 1, "bbox": (-117.0, 34.0, -116.99, 34.01)},
136
- ]
137
- )
138
- result = trim_around_stations(parcels, stops, 200)
139
- assert len(result) == 0 # no intersection
140
-
141
-
142
  # ---------------------------------------------------------------------------
143
  # Tests: create_buffer_donuts
144
  # ---------------------------------------------------------------------------
 
1
  from __future__ import annotations
2
 
3
  import geopandas as gpd
 
 
4
  from shapely.geometry import Point, box
5
 
6
  from notebooks.sb79map import (
 
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:
 
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
  # ---------------------------------------------------------------------------
tests/test_helpers.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 = []
7
+ for p in parcels_data:
8
+ rec = {
9
+ "APN20": p["APN20"],
10
+ "current_density_du_per_ac": p.get("current_density_du_per_ac", 0),
11
+ "ZN19_CITY": p.get("ZN19_CITY", ""),
12
+ "ZN19_SCAG": p.get("ZN19_SCAG", 0),
13
+ "CITY": p.get("CITY", ""),
14
+ "COUNTY": p.get("COUNTY", ""),
15
+ "Tier": p.get("Tier", 1),
16
+ "geometry": box(*p["bbox"]),
17
+ }
18
+ # Include any extra columns passed in the dict
19
+ for k, v in p.items():
20
+ if k not in rec and k != "bbox":
21
+ rec[k] = v
22
+ records.append(rec)
23
+ return gpd.GeoDataFrame(records, crs="EPSG:4326")
24
+
25
+
26
+ def _make_stops_gdf(stops_data: list[dict]) -> gpd.GeoDataFrame:
27
+ """Create a stops GeoDataFrame from a list of dicts."""
28
+ records = []
29
+ for s in stops_data:
30
+ records.append(
31
+ {
32
+ "stop_id": s["stop_id"],
33
+ "stop_name": s.get("stop_name", ""),
34
+ "Tier": s["Tier"],
35
+ "geometry": Point(s["lon"], s["lat"]),
36
+ }
37
+ )
38
+ return gpd.GeoDataFrame(records, crs="EPSG:4326")
tests/utils/test_geoprocessing.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import geopandas as gpd
2
+ import pytest
3
+ from shapely.geometry import LineString, Point, Polygon, box
4
+
5
+ from shared.utils.constants import SCAG_FT_CSR
6
+ from shared.utils.geoprocessing import clip_to_buffer_rings
7
+
8
+ # EPSG:2229 coordinates for a point in central LA
9
+ LA_X, LA_Y = 6_490_000, 2_040_000
10
+
11
+
12
+ 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=SCAG_FT_CSR,
17
+ )
18
+
19
+
20
+ def _point_feature(x: float, y: float) -> gpd.GeoDataFrame:
21
+ return gpd.GeoDataFrame(
22
+ {"feature_id": ["F1"]},
23
+ geometry=[Point(x, y)],
24
+ crs=SCAG_FT_CSR,
25
+ )
26
+
27
+
28
+ def _line_feature(x0: float, y0: float, x1: float, y1: float) -> gpd.GeoDataFrame:
29
+ return gpd.GeoDataFrame(
30
+ {"feature_id": ["F1"]},
31
+ geometry=[LineString([(x0, y0), (x1, y1)])],
32
+ crs=SCAG_FT_CSR,
33
+ )
34
+
35
+
36
+ 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=SCAG_FT_CSR,
41
+ )
42
+
43
+
44
+ class TestClipToBufferRingsInclusion:
45
+ """Features inside / outside buffer rings are included / excluded correctly."""
46
+
47
+ def test_point_inside_inner_ring_is_included(self):
48
+ # Arrange
49
+ features = _point_feature(LA_X + 100, LA_Y)
50
+
51
+ # Act
52
+ inner, *_ = clip_to_buffer_rings(features, _source(), [200, 1320])
53
+
54
+ # Asser
55
+ assert len(inner) == 1
56
+
57
+ def test_point_outside_outer_ring_is_excluded(self):
58
+ # Arrange
59
+ features = _point_feature(LA_X + 3000, LA_Y)
60
+
61
+ # Act
62
+ inner, outer = clip_to_buffer_rings(features, _source(), [200, 2640])
63
+
64
+ # Asser
65
+ assert len(inner) == 0
66
+ assert len(outer) == 0
67
+
68
+ def test_point_in_donut_excluded_from_inner_ring(self):
69
+ # Arrange
70
+ features = _point_feature(LA_X + 500, LA_Y)
71
+
72
+ # Act
73
+ inner, donut = clip_to_buffer_rings(features, _source(), [200, 1320])
74
+
75
+ # Asser
76
+ assert len(inner) == 0
77
+ assert len(donut) == 1
78
+
79
+ def test_line_crossing_buffer_boundary_is_clipped(self):
80
+ # Arrange
81
+ features = _line_feature(LA_X, LA_Y, LA_X + 1000, LA_Y)
82
+
83
+ # Act
84
+ inner, *_ = clip_to_buffer_rings(features, _source(), [200, 1320])
85
+
86
+ # Assert
87
+ original_length = features.geometry.length.iloc[0]
88
+ assert len(inner) == 1
89
+ assert inner.geometry.length.iloc[0] < original_length
90
+
91
+ def test_line_fully_outside_all_rings_excluded(self):
92
+ # Arrange
93
+ features = _line_feature(LA_X + 3000, LA_Y, LA_X + 4000, LA_Y)
94
+
95
+ # Act
96
+ inner, outer = clip_to_buffer_rings(features, _source(), [200, 2640])
97
+
98
+ # Asser
99
+ assert len(inner) == 0
100
+ assert len(outer) == 0
101
+
102
+ def test_polygon_inside_inner_ring_fully_included(self):
103
+ # Arrange
104
+ features = _polygon_feature(LA_X + 50, LA_Y, half=10)
105
+
106
+ # Act
107
+ inner, *_ = clip_to_buffer_rings(features, _source(), [200, 1320])
108
+
109
+ # Asser
110
+ assert len(inner) == 1
111
+ assert inner.geometry.area.iloc[0] == pytest.approx(features.geometry.area.iloc[0], rel=0.01)
112
+
113
+ def test_polygon_straddling_inner_boundary_is_clipped(self):
114
+ # Arrange
115
+ features = _polygon_feature(LA_X, LA_Y, half=500)
116
+
117
+ # Act
118
+ inner, *_ = clip_to_buffer_rings(features, _source(), [200, 1320])
119
+
120
+ # Assert
121
+ assert inner.geometry.area.iloc[0] < features.geometry.area.iloc[0]
122
+
123
+ def test_polygon_outside_all_rings_excluded(self):
124
+ # Arrange
125
+ features = _polygon_feature(LA_X + 5000, LA_Y, half=100)
126
+
127
+ # Act
128
+ inner, outer = clip_to_buffer_rings(features, _source(), [200, 2640])
129
+
130
+ # Asser
131
+ assert len(inner) == 0
132
+ assert len(outer) == 0
133
+
134
+
135
+ class TestClipToBufferRingsDonutShape:
136
+ """Donut rings have boundaries at the expected distances."""
137
+
138
+ def test_inner_ring_radius_matches_buffer_distance(self):
139
+ # Arrange
140
+ features = _polygon_feature(LA_X, LA_Y, half=3000)
141
+
142
+ # Act
143
+ inner, *_ = clip_to_buffer_rings(features, _source(), [200, 1320, 2640])
144
+
145
+ # Assert
146
+ expected_area = 3.14159 * 200**2
147
+ assert inner.geometry.area.iloc[0] == pytest.approx(expected_area, rel=0.01)
148
+
149
+ def test_donut_excludes_inner_buffer_area(self):
150
+ # Arrange
151
+ features = _polygon_feature(LA_X, LA_Y, half=3000)
152
+
153
+ # Act
154
+ inner, donut, *_ = clip_to_buffer_rings(features, _source(), [200, 1320, 2640])
155
+
156
+ # Assert
157
+ donut_union = donut.geometry.unary_union
158
+ inner_union = inner.geometry.unary_union
159
+ assert donut_union.intersection(inner_union).area == pytest.approx(0, abs=1)
160
+
161
+ def test_donut_outer_boundary_matches_buffer_distance(self):
162
+ # Arrange
163
+ features = _polygon_feature(LA_X, LA_Y, half=3000)
164
+
165
+ # Act
166
+ inner, donut, *_ = clip_to_buffer_rings(features, _source(), [200, 1320, 2640])
167
+
168
+ # Assert
169
+ expected_area = 3.14159 * 1320**2
170
+ combined_area = inner.geometry.area.sum() + donut.geometry.area.sum()
171
+ assert combined_area == pytest.approx(expected_area, rel=0.01)
172
+
173
+ def test_three_rings_are_non_overlapping_and_contiguous(self):
174
+ # Arrange
175
+ features = _polygon_feature(LA_X, LA_Y, half=3000)
176
+
177
+ # Act
178
+ inner, qtr, half = clip_to_buffer_rings(features, _source(), [200, 1320, 2640])
179
+
180
+ # Assert
181
+ inner_u = inner.geometry.unary_union
182
+ qtr_u = qtr.geometry.unary_union
183
+ half_u = half.geometry.unary_union
184
+ assert inner_u.intersection(qtr_u).area == pytest.approx(0, abs=1)
185
+ assert inner_u.intersection(half_u).area == pytest.approx(0, abs=1)
186
+ assert qtr_u.intersection(half_u).area == pytest.approx(0, abs=1)
187
+
188
+ # Assert
189
+ expected_area = 3.14159 * 2640**2
190
+ total_area = inner_u.area + qtr_u.area + half_u.area
191
+ assert total_area == pytest.approx(expected_area, rel=0.01)