diff --git a/CHANGELOG.md b/CHANGELOG.md index f6cd3df..7ef45ad 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- **GRB road-crossings level evidence (`build_grb_road_crossings`).** + `prepare_grb` now also publishes `road_crossings.geoparquet` (one row per + road unit, EPSG:31370: footprint, a second `axis` geometry column, + `road_id`, `structure` = `ground` / `grade_separated` / `unknown`, + `complex_crossing`, provenance), `road_crossings_coverage.geoparquet` + (where the artifact is complete) and `road_crossings_exclusions.geoparquet` + (every area left out of coverage, with its reason). `ground` comes only + from WBN elements — captured by the GRB only where the corridor is visible + at ground level — never as a default; the footprint is the whole corridor; + fragments of one carriageway share a `road_id` (never across a junction). `grade_separated` needs carriageway axes crossing without a node + inside a KNW bridge/tunnel group, all of them taking part and none ending + inside; any other structure is `unknown`. Coverage excludes `unknown` + footprints, structures and WBN elements left unproven by an unresolved axis + (`MORF` 120, 125, −8, not in service; only a buffer around it inside a + `ground` element), footprints leaving the bbox, and a `crossing_exclusion_buffer_m` + (default 15 m) around drivable axes no unit accounts for and around + node-less crossings outside structures. `complex_crossing` comes from + `MORF` 101 autosnelweg. + ### Fixed - **`gispulse_src_osm.read_pbf_roads` works against real PBF extracts.** It diff --git a/plugins/gispulse-src-grb/README.md b/plugins/gispulse-src-grb/README.md index 9cd8397..19c76e5 100644 --- a/plugins/gispulse-src-grb/README.md +++ b/plugins/gispulse-src-grb/README.md @@ -511,6 +511,128 @@ drillable at grade without a separate check. No KNW polygon in this bbox is typed `tunnel` (12), so that path is exercised only by the unit tests' synthetic geometry. +## Road crossings: level evidence + +`build_grb_road_crossings` +(`src/gispulse/capabilities/vector/grb_road_crossings.py`), wired into +`prepare_grb`, publishes three files next to the classification (it reads +WBN, Wegsegment and KNW directly, never the classification): + +- `road_crossings.geoparquet` — one row per physical road unit, EPSG:31370: + + | column | content | + |---|---| + | geometry (active) | footprint, `Polygon`/`MultiPolygon` | + | `axis` | second geometry column, `LineString`/`MultiLineString`, clipped to the footprint | + | `road_id` | `GRB:WBN:` or `GRB:KNW:+…` | + | `structure` | `ground`, `grade_separated` or `unknown` | + | `complex_crossing` | `MORF` in `complex_morf_codes` (default 101 autosnelweg) | + | `structure_evidence`, `source`, `source_layer`, `source_ids`, `axis_ids`, `morf_codes` | provenance | + +- `road_crossings_coverage.geoparquet` — one polygon: where the artifact is + complete; +- `road_crossings_exclusions.geoparquet` — every area removed from that + coverage, with its reason. + +Axes are sorted by `MORF`/`STATUS` only. In-service (`STATUS` 4) 101–112 +are carriageways (the classification's gate). 113 voetgangerszone, 114 +wandel- of fietsweg, 116 tramweg and 130 veer, documented as closed to +general motor traffic, are not. Everything else — 120 dienstweg and 125 +aardeweg (bare labels in the domain), −8, a carriageway not in service — is +**unresolved**. + +**`ground` comes from a WBN element, never from a default.** The +objectenhandboek page *wegbaan*: "enkel de aan het maaiveld zichtbare +wegcorridor wordt opgenomen als wegbaan. Waar de wegcorridor ingetunneld is, +op een overbrugging gelegen is of door een overbrugging wordt afgedekt, wordt +geen wegbaan (Wbn) opgenomen." WBN elements carrying a carriageway axis are +therefore positive evidence of a ground-level corridor. **The footprint is +the whole WBN corridor** (sidewalks and verges inside it), not a +carriageway-only surface. Touching `wegsegment`-type elements sharing a +carriageway axis and the same `complex_crossing` are fragments of one +carriageway: one `road_id`, footprints united, the original axes clipped +against the union so they stay continuous across arbitrary element cuts. A +`kruispuntzone` (WBN `TYPE` 1), an element holding an axis end that is not a +plain pass-through node — three or more ends (a junction not mapped as a +kruispuntzone: a side street, a parking entrance) or a single one (a dead +end, possibly another street reaching into the corridor) — and an element +with an undocumented `TYPE` are never merged. Where such a rule blocks a +genuine continuation, the boundary behaves element by element (a crossing +very close to the cut is bored a little short). + +**`grade_separated` needs a level relation, not a bridge polygon.** Touching +KNW `overbrugging` (1) / `tunnelmond` (12) polygons form one structure. It +is `grade_separated` when at least two carriageway axes cross inside it +without a node, every such axis takes part in such a crossing, and none ends +inside. The OSLO Wegenregister profile defines a Wegknoop as the object +describing connectivity between two segments: axes crossing with no node are +not connected there, and the KNW polygon documents the structure separating +them. This is an **inference from two official facts**, not a stated rule +(the Wegenregister `OngelijkgrondseKruising` relation states it directly +and is not exposed by any WFS). Measured on a Gand sample: 91 of the 101 +node-less crossings of carriageway axes lie inside a KNW 1/12 polygon. + +**`unknown`**: any other structure carrying a carriageway axis — +`single_axis` (a road over water, or under a railway bridge: KNW alone +cannot tell which), `axis_ends_inside` (a junction or dead end on or under +the structure), `axis_not_crossed`. + +**Coverage** starts from the bbox and excludes: + +| reason | what | +|---|---| +| `structure_` | every `unknown` footprint | +| `structure_axes_unresolved` | every structure carrying an unresolved axis (it could change the verdict) | +| `wbn_axes_unresolved` | a WBN element carrying only unresolved axes; inside a `ground` element, a buffer around the unresolved axis only (a trench crossing that axis alone would see none) | +| `wbn_without_axis` | a WBN element with no axis at all | +| `footprint_crosses_bounds` | every footprint leaving the bbox: axes entirely outside were never acquired, so its verdict cannot be trusted | +| `axis_without_unit` | a `crossing_exclusion_buffer_m` buffer (default 15 m) around drivable axis length no unit accounts for: a road with no footprint (a private road the GRB did not capture, a tunnel body) or one lying exactly on a boundary | +| `nodeless_crossing_outside_structure` | the same buffer around node-less crossings and self-crossings of drivable axes outside every structure: level evidence contradicting the ground rule | + +A structure with no drivable axis is no road and stays covered; a WBN +element carrying only documented non-motor axes stays covered without a +row. Footprints are never claimed twice: structures take priority over WBN +("een wegbaanelement houdt op ter hoogte van een kunstwerk"), then the lower +WBN `OIDN`. + +**Validated live** on three bboxes (Gand 5.5 × 6.5 km, two 6 × 6 km tiles +near Oudenaarde and Leuven), 1.4–2.0 s each, with 9, 2 and 5 merged +units: + +| bbox | ground units (elements) | grade_separated | unknown: single / ends inside / not crossed | ground elements with an unresolved axis + unresolved-only elements | drivable axis without unit | coverage | +|---|---|---|---|---|---|---| +| Gand | 2 405 (2 414) | 21 | 8 / 7 / 3 | 87 + 19 | 61.1 km | 93.3 % | +| Oudenaarde | 1 793 (1 795) | 6 | 11 / 3 / 2 | 33 + 2 | 35.9 km | 96.3 % | +| Leuven | 1 790 (1 795) | 8 | 12 / 4 / 0 | 146 + 19 | 87.2 km | 91.4 % | + +No WBN element overlaps a KNW 1/12 polygon and no two WBN elements overlap +(above 0.01 m²); every axis is simple. Most axes without a unit are local +access roads the GRB maps with no WBN (in Gand, 57 of 85 sampled were +private) and aardewegen. + +**Known limits.** + +- KNW completeness: `ground` relies on the GRB not having missed a + structure; the node-less-crossing exclusion catches part of these. +- Up/down is never resolved. `grade_separated` holds for an excavation that + follows one of the crossing roads through the structure; an excavation dug + at ground level under a deck, off any mapped road, would cross the lower + road there and is not represented. `single_axis` structures stay + `unknown` even when the road is plainly on the deck. +- `complex_crossing` is per unit: a corridor carrying an autosnelweg and its + parallelweg is complex as a whole. +- The footprint is the whole corridor. A consumer that bores "the full + length inside the footprint" over-bores a trench that runs *along* a road + inside its corridor and wavers across its axis: run against 25 real MILOU + tracés, that accounts for 36 such "crossings" totalling 7.35 km (up to + 922 m). Telling a longitudinal run from a crossing belongs to the consumer. +- `road_id` is stable for one acquisition only; bundles from different + bounds must be deduplicated on `source_ids`, never concatenated. +- An axis piece ending within floating-point distance of a footprint + boundary, or at a self-crossing split, is a measure-zero consumer edge case. +- The exclusion buffer has no source basis; it is an explicit, reported + parameter. Flanders only: PICC/UrbIS level evidence is not wired here. + ## Validation 2026-09-08, the Gand bbox above, page size 5: 52 WBN (11 pages), 139 WGO diff --git a/plugins/gispulse-src-grb/gispulse_src_grb/prepare.py b/plugins/gispulse-src-grb/gispulse_src_grb/prepare.py index ab07b2c..0acf321 100644 --- a/plugins/gispulse-src-grb/gispulse_src_grb/prepare.py +++ b/plugins/gispulse-src-grb/gispulse_src_grb/prepare.py @@ -15,6 +15,7 @@ from gispulse.adapters.rest.offset_pages import OffsetPagination from gispulse.capabilities.vector.classify_faces import validate_functional_faces from gispulse.capabilities.vector.classify_grb_faces import classify_grb_faces +from gispulse.capabilities.vector.grb_road_crossings import build_grb_road_crossings from gispulse.capabilities.vector.polygon_partition import partition_polygons from gispulse.capabilities.vector.reconcile_knw_structures import reconcile_knw_structures from gispulse.core.io.geoparquet import write_geoparquet @@ -28,8 +29,9 @@ "grb-kunstwerk-vl", ) -# GeoJSON empties omit property schemas; the classification reads these codes. +# GeoJSON empties omit property schemas; classification and crossings read these codes. _CLASSIFIED_FIELDS = { + "grb-wegbaan-vl": ("TYPE",), "grb-wegopdeling-vl": ("TYPE",), "grb-wegsegment-vl": ("WS_OIDN", "VERH", "STATUS", "MORF"), "grb-kunstwerk-vl": ("TYPE",), @@ -51,12 +53,16 @@ def prepare_grb( axis_min_extent_m: float = 5.0, unsplit_max_width_m: float = 12.0, dienstweg_unpaved_evidence: bool = False, + crossing_exclusion_buffer_m: float = 15.0, ) -> dict: """Publish raw layers, unclassified candidate faces and an evidence-based classification. Tolerances account for numerical residuals only; no snapping or simplification. Limits apply per layer. The bbox is in the native EPSG:31370 CRS. The classification thresholds are explicit and recorded in the report. + ``crossing_exclusion_buffer_m`` is the half-width the road-crossings + coverage removes around a drivable axis with no footprint (see + ``grb_road_crossings``). """ if ( len(bbox) != 4 @@ -77,6 +83,8 @@ def prepare_grb( ) or not math.isfinite(unsplit_max_width_m) or unsplit_max_width_m <= 0 + or not math.isfinite(crossing_exclusion_buffer_m) + or crossing_exclusion_buffer_m <= 0 ): raise ValueError("GRB_TOLERANCE_INVALID: nonnegative finite tolerances required") if not math.isfinite(axis_coverage_ratio_min) or not 0.0 <= axis_coverage_ratio_min <= 1.0: @@ -109,6 +117,7 @@ def prepare_grb( "axis_min_extent_m": axis_min_extent_m, "unsplit_max_width_m": unsplit_max_width_m, "dienstweg_unpaved_evidence": dienstweg_unpaved_evidence, + "crossing_exclusion_buffer_m": crossing_exclusion_buffer_m, "ready_for_costing": False, } if not write: @@ -153,6 +162,32 @@ def prepare_grb( write_geoparquet( diagnostics, str(staging / "partition_diagnostics.geoparquet"), compression="zstd" ) + # Level evidence for road crossings reads WBN, Wegsegment and KNW + # directly, never the classification: a defect in one of them degrades + # this artifact alone, like the classification below. + try: + crossings, coverage, exclusions, crossings_report = build_grb_road_crossings( + frames["grb-wegbaan-vl"], + frames["grb-wegsegment-vl"], + frames["grb-kunstwerk-vl"], + coverage_bounds=bbox, + length_tolerance_m=length_tolerance_m, + area_tolerance_m2=area_tolerance_m2, + boundary_tolerance_m=boundary_tolerance_m, + exclusion_buffer_m=crossing_exclusion_buffer_m, + ) + except ValueError as exc: + if not str(exc).startswith("GRB_CROSSINGS_"): + raise + crossings_report = {"status": "failed", "error": str(exc)} + else: + for name, frame in [ + ("road_crossings", crossings), + ("road_crossings_coverage", coverage), + ("road_crossings_exclusions", exclusions), + ]: + write_geoparquet(frame, str(staging / f"{name}.geoparquet"), compression="zstd") + crossings_report = {"status": "prepared", **crossings_report} try: classified, classification = classify_grb_faces( faces, @@ -219,6 +254,7 @@ def prepare_grb( candidate_faces=len(faces), topology=diagnostics.status.value_counts().sort_index().to_dict(), classification=classification_report, + road_crossings=crossings_report, ) (staging / "report.json").write_text(json.dumps(report, indent=2) + "\n") if output.exists(): @@ -249,6 +285,7 @@ def main() -> int: action="store_true", help="also count MORF=120 (dienstweg) axes coded VERH=2 as unpaved evidence", ) + parser.add_argument("--crossing-exclusion-buffer-m", type=float, default=15.0) args = parser.parse_args() try: report = prepare_grb( @@ -265,6 +302,7 @@ def main() -> int: axis_min_extent_m=args.axis_min_extent_m, unsplit_max_width_m=args.unsplit_max_width_m, dienstweg_unpaved_evidence=args.dienstweg_unpaved_evidence, + crossing_exclusion_buffer_m=args.crossing_exclusion_buffer_m, ) except Exception as exc: # noqa: BLE001 - CLI boundary print( diff --git a/src/gispulse/capabilities/vector/grb_road_crossings.py b/src/gispulse/capabilities/vector/grb_road_crossings.py new file mode 100644 index 0000000..f423800 --- /dev/null +++ b/src/gispulse/capabilities/vector/grb_road_crossings.py @@ -0,0 +1,655 @@ +"""Build the road-crossings level-evidence artifact from GRB corridors, axes and structures. + +Output contract (one row per physical road unit, EPSG:31370): the footprint +polygon is the active geometry, ``axis`` is a second geometry column, plus +``road_id``, ``structure`` (``ground`` / ``grade_separated`` / ``unknown``) and +``complex_crossing``. A separate coverage polygon declares where the artifact +is complete. Level and category only, each from a cited source rule: no price, +no cost class, no paving material. + +Evidence rules: + +- ``ground``: WBN (wegbaan) elements carrying an in-service motor-traffic + Wegsegment axis. The GRB objectenhandboek captures only the corridor visible + at ground level as wegbaan — "enkel de aan het maaiveld zichtbare + wegcorridor wordt opgenomen als wegbaan. Waar de wegcorridor ingetunneld is, + op een overbrugging gelegen is of door een overbrugging wordt afgedekt, wordt + geen wegbaan (Wbn) opgenomen." — so a WBN element is positive evidence of a + ground-level corridor. A road with no WBN element is never ``ground``. The + footprint is the whole WBN corridor (kerb to kerb and beyond: sidewalks and + verges inside it), not a carriageway-only surface. Touching + ``wegsegment``-type elements that share a carriageway axis (and the same + category) are fragments of one carriageway: one ``road_id``, footprints + united, axes joined. A ``kruispuntzone`` (WBN ``TYPE`` 1), an element + holding an axis end that is not a plain pass-through node (where three or + more ends meet: a junction the GRB did not map as a kruispuntzone; a single + end: a dead end reaching into it), and an element with an undocumented + ``TYPE`` always stay units of their own. ``road_id`` is the unit's first WBN ``OIDN``: stable + for a given acquisition, but a unit cut by the bounds of another acquisition + can get another id — never concatenate bundles without deduplicating on + ``source_ids``. +- ``grade_separated``: a group of touching KNW ``overbrugging`` (1) / + ``tunnelmond`` (12) polygons inside which at least two in-service + motor-traffic axes cross without a node, every such axis takes part in such + a crossing, and none ends inside. The OSLO Wegenregister profile defines a + Wegknoop as the object describing connectivity between two segments; two + axes crossing with no node are not connected there, and the KNW footprint + documents the structure that separates them. This is a level relation + between two roads, not a bare bridge tag — an inference from those two + official facts, not a rule the source states (the Wegenregister + ``OngelijkgrondseKruising`` relation would state it, and is not acquired). + Which road is on top is not resolved: the label holds for an excavation + that follows one of the crossing roads through the structure, not for one + dug at ground level under a deck off any mapped road. Measured on a Gand + sample: 91 of 101 node-less crossings of motor-traffic axes lie inside a + KNW 1/12 footprint. +- ``unknown``: any other structure group carrying a motor-traffic axis — a + single axis (a road over water, or under a railway bridge: KNW alone cannot + tell which), an axis ending inside (a junction or dead end on or under the + structure), or an axis that crosses no other one. + +Axes are sorted by ``MORF``/``STATUS`` only: in-service 101-112 are +carriageways; 113 (voetgangerszone), 114 (wandel- of fietsweg), 116 (tramweg) +and 130 (veer), documented as closed to general motor traffic, are not; +everything else — 120 dienstweg and 125 aardeweg (bare labels in the domain), +-8, a carriageway not in service — is unresolved. + +``complex_crossing`` is true when an axis of the unit has a motorway +morphology (default ``MORF`` 101 autosnelweg, defined by the Wegenregister +catalogue as two physically separated carriageways with no at-grade +crossing), never derived from material. It is per unit: a corridor carrying +an autosnelweg and its parallelweg is complex as a whole. + +Coverage starts from the acquisition bounds and excludes: + +- every ``unknown`` footprint; +- every structure group carrying an unresolved axis (it could change the + verdict), every WBN element carrying only unresolved axes or no axis at + all, and a buffer around an unresolved axis inside a ``ground`` element (the + element is ground either way; a trench crossing that axis alone would go + unseen). A structure with no drivable axis is no road and stays covered; +- every footprint that leaves the bounds: axes entirely outside were not + acquired, so its verdict cannot be trusted; +- a buffer around any drivable (carriageway or unresolved) axis length that + no unit accounts for: a road with no footprint (a private road the GRB did + not capture, a tunnel body) or one running exactly on a boundary; +- a buffer around any node-less crossing of drivable axes, or self-crossing, + outside every structure (level evidence that contradicts the ground rule). + +A WBN element carrying only documented non-motor axes stays covered without a +row: it is documented as not being a carriageway. + +Sources: +https://www.vlaanderen.be/digitaal-vlaanderen/onze-diensten-en-platformen/basiskaart-vlaanderen-grb/objectenhandboek-basiskaart-vlaanderen-grb/wegbaan-wbn +https://www.vlaanderen.be/digitaal-vlaanderen/onze-diensten-en-platformen/basiskaart-vlaanderen-grb/objectenhandboek-basiskaart-vlaanderen-grb/kunstwerk-knw +https://data.vlaanderen.be/doc/applicatieprofiel/wegenregister/ +https://metadata.dev-vlaanderen.be/srv/api/records/aff2c639-28cf-4bee-8fa8-9213663a5ef4 +""" + +from __future__ import annotations + +import math +from collections import Counter +from collections.abc import Iterable + +import geopandas as gpd +import pandas as pd +import shapely +from shapely import STRtree +from shapely.geometry import LineString, MultiLineString, MultiPolygon, Point, Polygon, box +from shapely.ops import linemerge, unary_union + +from gispulse.capabilities.vector.reconcile_knw_structures import _code, _nonempty_id_column + +_STRUCTURE_CODES = frozenset({1, 12}) # KNW overbrugging, tunnelmond +_KRUISPUNTZONE, _WEGSEGMENT = 1, 2 # WBN TYPE +_IN_SERVICE = 4 # Wegsegment STATUS +# Wegsegment MORF 101-112: documented motor-traffic ways and junctions (same +# gate as classify_grb_faces). +_CARRIAGEWAY_MORF = frozenset(range(101, 113)) +# Documented as closed to general motor traffic: voetgangerszone, wandel- of +# fietsweg, tramweg, veer. 120 dienstweg and 125 aardeweg are bare labels: unresolved. +_NON_CARRIAGEWAY_MORF = frozenset({113, 114, 116, 130}) +_COMPLEX_MORF = (101,) # autosnelweg +_CARRIAGEWAY, _NON_CARRIAGEWAY, _UNRESOLVED = "carriageway", "non_carriageway", "unresolved" +_COLUMNS = ( + "road_id", + "structure", + "complex_crossing", + "structure_evidence", + "source", + "source_layer", + "source_ids", + "axis_ids", + "morf_codes", +) + + +def _lines(geometry) -> list[LineString]: + if geometry is None or geometry.is_empty: + return [] + if isinstance(geometry, LineString): + return [geometry] + return [line for part in getattr(geometry, "geoms", ()) for line in _lines(part)] + + +def _points(geometry) -> list[Point]: + if geometry is None or geometry.is_empty: + return [] + if isinstance(geometry, Point): + return [geometry] + return [point for part in getattr(geometry, "geoms", ()) for point in _points(part)] + + +def _polygonal(geometry) -> Polygon | MultiPolygon | None: + parts = [ + polygon + for part in getattr(geometry, "geoms", [geometry]) + for polygon in getattr(part, "geoms", [part]) + if isinstance(polygon, Polygon) and not polygon.is_empty + ] + if not parts: + return None + return parts[0] if len(parts) == 1 else MultiPolygon(parts) + + +def _endpoints(geometry) -> list[Point]: + return [Point(line.coords[i]) for line in _lines(geometry) for i in (0, -1)] + + +def _pieces_inside(line, polygon, tolerance: float) -> list[LineString]: + """Axis pieces genuinely inside ``polygon``. + + A tangent contact yields a point and a run along the boundary has its + midpoint on the boundary: neither is a piece of this footprint's axis. + """ + return [ + piece + for piece in _lines(line.intersection(polygon)) + if piece.length > tolerance and polygon.contains(piece.interpolate(0.5, normalized=True)) + ] + + +def _simple_axes(pieces: Iterable[LineString]) -> list[LineString]: + """Join contiguous pieces (degree-2 nodes only, junctions stay split); + never emit a self-intersecting line.""" + merged = _lines(linemerge(list(pieces))) + out: list[LineString] = [] + for line in merged: + out.extend([line] if line.is_simple else _lines(shapely.node(line))) + return out + + +def _self_crossings(line) -> list[Point]: + """Points where a non-simple axis crosses itself (not its own ends).""" + if line.is_simple: + return [] + ends = {(p.x, p.y) for p in _endpoints(line)} + return [ + p + for p in {(q.x, q.y): q for q in _endpoints(shapely.node(line))}.values() + if (p.x, p.y) not in ends + ] + + +class _DisjointSets: + def __init__(self, size: int) -> None: + self.parent = list(range(size)) + + def find(self, item: int) -> int: + while self.parent[item] != item: + self.parent[item] = self.parent[self.parent[item]] + item = self.parent[item] + return item + + def union(self, left: int, right: int) -> None: + self.parent[self.find(left)] = self.find(right) + + +def _validate( + wbn, + wegsegment, + knw, + *, + wbn_fields, + knw_type_field, + axis_fields, + coverage_bounds, + numbers, +): + if any(frame.crs is None or frame.crs.to_epsg() != 31370 for frame in (wbn, wegsegment, knw)): + raise ValueError("GRB_CROSSINGS_CRS_INVALID: EPSG:31370 required on every layer") + if ( + len(coverage_bounds) != 4 + or not all(math.isfinite(v) for v in coverage_bounds) + or coverage_bounds[0] >= coverage_bounds[2] + or coverage_bounds[1] >= coverage_bounds[3] + ): + raise ValueError("GRB_CROSSINGS_EXTENT_INVALID: ordered finite EPSG:31370 bounds required") + if any(not math.isfinite(v) or v < 0 for v in numbers.values()) or not ( + numbers["exclusion_buffer_m"] > 0 + ): + raise ValueError( + "GRB_CROSSINGS_TOLERANCE_INVALID: nonnegative finite tolerances and a positive " + "exclusion buffer required" + ) + for frame, fields in [(wbn, wbn_fields), (wegsegment, axis_fields), (knw, (knw_type_field,))]: + missing = [field for field in fields if field not in frame] + if missing: + raise ValueError(f"GRB_CROSSINGS_FIELD_MISSING: {missing}") + for frame, allowed in [ + (wbn, (Polygon, MultiPolygon)), + (wegsegment, (LineString, MultiLineString)), + ]: + if any(not isinstance(g, allowed) or g.is_empty or not g.is_valid for g in frame.geometry): + raise ValueError( + "GRB_CROSSINGS_GEOMETRY_INVALID: repair source geometries explicitly first" + ) + for frame, field in [(wbn, wbn_fields[0]), (wegsegment, axis_fields[0])]: + if _nonempty_id_column(frame, field, "GRB_CROSSINGS_ID_INVALID").duplicated().any(): + raise ValueError("GRB_CROSSINGS_ID_INVALID: unique nonempty IDs required") + + +def build_grb_road_crossings( + wbn: gpd.GeoDataFrame, + wegsegment: gpd.GeoDataFrame, + knw: gpd.GeoDataFrame, + *, + coverage_bounds: tuple, + length_tolerance_m: float, + area_tolerance_m2: float, + boundary_tolerance_m: float, + exclusion_buffer_m: float, + wbn_id: str = "OIDN", + wbn_type_field: str = "TYPE", + knw_id: str = "OIDN", + knw_type_field: str = "TYPE", + axis_id: str = "WS_OIDN", + axis_status_field: str = "STATUS", + axis_morphology_field: str = "MORF", + complex_morf_codes: Iterable[int] = _COMPLEX_MORF, +) -> tuple[gpd.GeoDataFrame, gpd.GeoDataFrame, gpd.GeoDataFrame, dict]: + """Return ``(crossings, coverage, exclusions, report)`` — see the module docstring. + + Tolerances absorb numerical residuals only (no snapping): ``length_tolerance_m`` + drops degenerate axis pieces, ``area_tolerance_m2`` ignores sliver overlaps, + ``boundary_tolerance_m`` groups touching polygons and absorbs the rounding + between an axis and its clipped pieces. ``exclusion_buffer_m`` is the + half-width removed from coverage around an axis length no unit accounts for, + or around a node-less crossing outside any structure: an explicit, reported + choice, since the missing corridor's real width is unknown. ``exclusions`` + lists every area removed from coverage with its reason. Reported lengths and + counts are measured inside ``coverage_bounds`` only. + """ + axis_fields = (axis_id, axis_status_field, axis_morphology_field) + numbers = { + "length_tolerance_m": length_tolerance_m, + "area_tolerance_m2": area_tolerance_m2, + "boundary_tolerance_m": boundary_tolerance_m, + "exclusion_buffer_m": exclusion_buffer_m, + } + _validate( + wbn, + wegsegment, + knw, + wbn_fields=(wbn_id, wbn_type_field), + knw_type_field=knw_type_field, + axis_fields=axis_fields, + coverage_bounds=coverage_bounds, + numbers=numbers, + ) + crs = wbn.crs + bounds = box(*coverage_bounds) + inside_bounds = bounds.buffer(boundary_tolerance_m) + shapely.prepare(inside_bounds) + complex_codes = frozenset(int(c) for c in complex_morf_codes) + exclusions: list[tuple[str, object]] = [] + + def exclude(reason, geometry): + exclusions.append((reason, geometry)) + + # --- Axes --------------------------------------------------------------- + axis_ids = _nonempty_id_column(wegsegment, axis_id, "GRB_CROSSINGS_ID_INVALID").tolist() + axis_morf = [_code(v) for v in wegsegment[axis_morphology_field]] + axis_kind = [] + for morf, status in zip(axis_morf, (_code(v) for v in wegsegment[axis_status_field])): + if morf in _NON_CARRIAGEWAY_MORF: + axis_kind.append(_NON_CARRIAGEWAY) + elif morf in _CARRIAGEWAY_MORF and status == _IN_SERVICE: + axis_kind.append(_CARRIAGEWAY) + else: + axis_kind.append(_UNRESOLVED) + axis_geoms = list(wegsegment.geometry) + axis_tree = STRtree(axis_geoms) + # Axis pieces some unit accounts for (a row, or an excluded footprint); + # whatever drivable length is left over gets a coverage hole. + accounted: dict[int, list[LineString]] = {} + + def pieces_by_kind(footprint): + found: dict[str, dict[int, list[LineString]]] = { + _CARRIAGEWAY: {}, + _NON_CARRIAGEWAY: {}, + _UNRESOLVED: {}, + } + for j in sorted(int(i) for i in axis_tree.query(footprint)): + pieces = _pieces_inside(axis_geoms[j], footprint, length_tolerance_m) + if pieces: + found[axis_kind[j]][j] = pieces + return found + + def account(found_kind): + for j, pieces in found_kind.items(): + accounted.setdefault(j, []).extend(pieces) + + rows: list[dict] = [] + + def add_row(road_id, structure, layer, source_ids, footprint, pieces, evidence): + axes = _simple_axes(line for j in sorted(pieces) for line in pieces[j]) + morfs = sorted({axis_morf[j] for j in pieces if axis_morf[j] is not None}) + rows.append( + { + "road_id": road_id, + "structure": structure, + "complex_crossing": any(m in complex_codes for m in morfs), + "structure_evidence": evidence, + "source": "GRB", + "source_layer": layer, + "source_ids": "+".join(source_ids), + "axis_ids": ",".join(sorted({axis_ids[j] for j in pieces})), + "morf_codes": ",".join(str(m) for m in morfs), + "geometry": footprint, + "axis": axes[0] if len(axes) == 1 else MultiLineString(axes), + } + ) + account(pieces) + + # --- Structures (KNW 1/12), grouped when they touch ---------------------- + structure_codes = knw[knw_type_field].map(_code) + structures = knw[structure_codes.isin(_STRUCTURE_CODES).to_numpy()] + if len(structures) and knw_id not in structures: + raise ValueError(f"GRB_CROSSINGS_FIELD_MISSING: ['{knw_id}' (on structure-typed KNW)]") + if any( + not isinstance(g, (Polygon, MultiPolygon)) or g.is_empty or not g.is_valid + for g in structures.geometry + ): + raise ValueError( + "GRB_CROSSINGS_GEOMETRY_INVALID: repair source geometries explicitly first" + ) + structure_ids: list[str] = [] + if len(structures): + structure_column = _nonempty_id_column(structures, knw_id, "GRB_CROSSINGS_ID_INVALID") + if structure_column.duplicated().any(): + raise ValueError("GRB_CROSSINGS_ID_INVALID: unique nonempty IDs required") + structure_ids = structure_column.tolist() + structure_geoms = list(structures.geometry) + structure_tree = STRtree(structure_geoms) + groups = _DisjointSets(len(structure_geoms)) + if structure_geoms: + left, right = structure_tree.query( + structure_geoms, predicate="dwithin", distance=boundary_tolerance_m + ) + for a, b in zip(left, right): + groups.union(int(a), int(b)) + members: dict[int, list[int]] = {} + for position in range(len(structure_geoms)): + members.setdefault(groups.find(position), []).append(position) + structure_report = { + "groups": len(members), + "grade_separated": 0, + "unknown": {}, + "without_carriageway": 0, + "unresolved": 0, + "with_unresolved_axes": 0, + } + + for positions in sorted(members.values(), key=lambda ps: sorted(structure_ids[p] for p in ps)): + ids = sorted(structure_ids[p] for p in positions) + footprint = _polygonal(unary_union([structure_geoms[p] for p in positions])) + if not inside_bounds.contains(footprint): + exclude("footprint_crosses_bounds", footprint) + found = pieces_by_kind(footprint) + carriageway, unresolved = found[_CARRIAGEWAY], found[_UNRESOLVED] + if unresolved: + exclude("structure_axes_unresolved", footprint) + account(unresolved) + if not carriageway: + structure_report["unresolved" if unresolved else "without_carriageway"] += 1 + continue + if unresolved: + structure_report["with_unresolved_axes"] += 1 + ends_inside = any( + footprint.contains(point) for j in carriageway for point in _endpoints(axis_geoms[j]) + ) + crossed: set[int] = set() + pairs = [] + ordered = sorted(carriageway) + for n, a in enumerate(ordered): + for b in ordered[n + 1 :]: + meeting = unary_union(carriageway[a]).intersection(unary_union(carriageway[b])) + if any(footprint.contains(p) for p in _points(meeting)): + crossed.update((a, b)) + pairs.append(f"{axis_ids[a]}x{axis_ids[b]}") + if ends_inside: + reason = "axis_ends_inside" + elif len(carriageway) < 2: + reason = "single_axis" + elif crossed != set(carriageway): + reason = "axis_not_crossed" + else: + reason = None + road_id = "GRB:KNW:" + "+".join(ids) + if reason is None: + structure_report["grade_separated"] += 1 + evidence = "KNW " + "+".join(ids) + " node-less axis crossings " + ",".join(pairs) + add_row(road_id, "grade_separated", "KNW", ids, footprint, carriageway, evidence) + else: + counts = structure_report["unknown"] + counts[reason] = counts.get(reason, 0) + 1 + evidence = f"KNW {'+'.join(ids)} {reason}" + add_row(road_id, "unknown", "KNW", ids, footprint, carriageway, evidence) + exclude(f"structure_{reason}", footprint) + + # --- WBN elements: trim, sort, then group the fragments of one carriageway - + wbn_ids = _nonempty_id_column(wbn, wbn_id, "GRB_CROSSINGS_ID_INVALID").tolist() + wbn_geoms = list(wbn.geometry) + wbn_types = [_code(v) for v in wbn[wbn_type_field]] + # Only a node where exactly two axis ends meet merely carries a road on. + # Three or more ends make a junction even when not mapped as a + # kruispuntzone; a single end is a dead end, possibly another street + # reaching into this corridor. An element holding either, or whose TYPE is + # not a documented code, is never assumed a fragment. + degree = Counter((round(p.x, 3), round(p.y, 3)) for g in axis_geoms for p in _endpoints(g)) + stop_nodes = [Point(xy) for xy, count in degree.items() if count != 2] + stop_tree = STRtree(stop_nodes) + order = sorted(range(len(wbn_geoms)), key=lambda i: (len(wbn_ids[i]), wbn_ids[i])) + wbn_tree = STRtree(wbn_geoms) + claimed: set[int] = set() + wbn_report = { + "elements": len(wbn_geoms), + "ground_elements": 0, + "ground_units": 0, + "non_carriageway": 0, + "unresolved": 0, + "with_unresolved_axes": 0, + "without_axis": 0, + "overlap_trimmed": 0, + "unrecognised_type": sum(t not in (_KRUISPUNTZONE, _WEGSEGMENT) for t in wbn_types), + } + # element -> (trimmed footprint, carriageway axis positions, complex flag, + # whether it may be merged as a fragment) + ground: dict[int, tuple] = {} + for i in order: + footprint = wbn_geoms[i] + # Structures take priority ("een wegbaanelement houdt op ter hoogte van een + # kunstwerk"), then the earlier element: no area is ever claimed twice. + overlapping = [structure_geoms[int(k)] for k in structure_tree.query(footprint)] + [ + wbn_geoms[j] for j in (int(k) for k in wbn_tree.query(footprint)) if j in claimed + ] + trimmed = footprint + for other in overlapping: + if trimmed.intersection(other).area > area_tolerance_m2: + trimmed = trimmed.difference(other) + claimed.add(i) + if trimmed is not footprint: + wbn_report["overlap_trimmed"] += 1 + trimmed = _polygonal(trimmed) + if trimmed is None or trimmed.area <= area_tolerance_m2: + continue + if not inside_bounds.contains(trimmed): + exclude("footprint_crosses_bounds", trimmed) + found = pieces_by_kind(trimmed) + if found[_UNRESOLVED]: + account(found[_UNRESOLVED]) + if found[_CARRIAGEWAY]: + # Ground either way: only a trench crossing the unresolved branch + # alone would go unseen, so only that branch's surroundings go. + for pieces in found[_UNRESOLVED].values(): + for piece in pieces: + exclude("wbn_axes_unresolved", piece.buffer(exclusion_buffer_m)) + else: + exclude("wbn_axes_unresolved", trimmed) + if found[_CARRIAGEWAY]: + wbn_report["ground_elements"] += 1 + wbn_report["with_unresolved_axes"] += bool(found[_UNRESOLVED]) + complex_flag = any(axis_morf[j] in complex_codes for j in found[_CARRIAGEWAY]) + mergeable = wbn_types[i] == _WEGSEGMENT and not any( + trimmed.contains(stop_nodes[int(k)]) for k in stop_tree.query(trimmed) + ) + ground[i] = (trimmed, frozenset(found[_CARRIAGEWAY]), complex_flag, mergeable) + elif found[_UNRESOLVED]: + wbn_report["unresolved"] += 1 + elif found[_NON_CARRIAGEWAY]: + wbn_report["non_carriageway"] += 1 + else: + wbn_report["without_axis"] += 1 + exclude("wbn_without_axis", trimmed) + + elements = sorted(ground, key=lambda i: (len(wbn_ids[i]), wbn_ids[i])) + position = {i: n for n, i in enumerate(elements)} + fragments = _DisjointSets(len(elements)) + if elements: + ground_geoms = [ground[i][0] for i in elements] + left, right = STRtree(ground_geoms).query( + ground_geoms, predicate="dwithin", distance=boundary_tolerance_m + ) + for a, b in zip(left, right): + i, k = elements[int(a)], elements[int(b)] + if ( + i < k + and ground[i][3] + and ground[k][3] + and ground[i][2] == ground[k][2] + and ground[i][1] & ground[k][1] + ): + fragments.union(position[i], position[k]) + units: dict[int, list[int]] = {} + for i in elements: + units.setdefault(fragments.find(position[i]), []).append(i) + for unit in units.values(): + ids = [wbn_ids[i] for i in unit] # already in (len, id) order + footprint = _polygonal(unary_union([ground[i][0] for i in unit])) + # Clip the original axes against the united footprint, so a carriageway + # crossing a fragment boundary keeps one continuous axis. + found = pieces_by_kind(footprint) + wbn_report["ground_units"] += 1 + add_row( + f"GRB:WBN:{ids[0]}", + "ground", + "WBN", + ids, + footprint, + found[_CARRIAGEWAY], + f"WBN {'+'.join(ids)} maaiveld", + ) + + # --- Drivable axes and level conflicts no unit vouches for ---------------- + drivable = [j for j, kind in enumerate(axis_kind) if kind != _NON_CARRIAGEWAY] + unaccounted_length = 0.0 + for j in drivable: + done = accounted.get(j) + rest = axis_geoms[j] + if done: + rest = rest.difference(unary_union(done).buffer(boundary_tolerance_m)) + for piece in _lines(rest): + if piece.length > max(length_tolerance_m, boundary_tolerance_m): + unaccounted_length += piece.intersection(bounds).length + exclude("axis_without_unit", piece.buffer(exclusion_buffer_m)) + structure_guard = ( + unary_union(structure_geoms).buffer(boundary_tolerance_m) if structure_geoms else None + ) + if structure_guard is not None: + shapely.prepare(structure_guard) + conflict_points: list[Point] = [] + drivable_geoms = [axis_geoms[j] for j in drivable] + if drivable_geoms: + left, right = STRtree(drivable_geoms).query(drivable_geoms, predicate="crosses") + for a, b in zip(left, right): + if a >= b: + continue + nodes = _endpoints(drivable_geoms[a]) + _endpoints(drivable_geoms[b]) + for point in _points(drivable_geoms[a].intersection(drivable_geoms[b])): + if not any(point.distance(node) <= length_tolerance_m for node in nodes): + conflict_points.append(point) + for geometry in drivable_geoms: + conflict_points.extend(_self_crossings(geometry)) + conflicts = 0 + for point in conflict_points: + if structure_guard is not None and structure_guard.contains(point): + continue + conflicts += bounds.contains(point) + exclude("nodeless_crossing_outside_structure", point.buffer(exclusion_buffer_m)) + + # --- Assemble ----------------------------------------------------------- + if rows: + table = pd.DataFrame(rows).sort_values("road_id", kind="stable").reset_index(drop=True) + crossings = gpd.GeoDataFrame( + table[list(_COLUMNS)], geometry=gpd.GeoSeries(table.geometry, crs=crs), crs=crs + ) + crossings["axis"] = gpd.GeoSeries(table.axis, crs=crs, index=crossings.index) + else: + crossings = gpd.GeoDataFrame( + { + column: pd.Series(dtype=bool if column == "complex_crossing" else object) + for column in _COLUMNS + }, + geometry=gpd.GeoSeries([], crs=crs), + crs=crs, + ) + crossings["axis"] = gpd.GeoSeries([], crs=crs, index=crossings.index) + crossings["complex_crossing"] = crossings["complex_crossing"].astype(bool) + + kept = [ + (reason, area) + for reason, geometry in exclusions + if (area := _polygonal(geometry.intersection(bounds))) is not None + ] + excluded = gpd.GeoDataFrame( + {"reason": [reason for reason, _ in kept]}, + geometry=gpd.GeoSeries([area for _, area in kept], crs=crs), + crs=crs, + ) + covered = _polygonal(bounds.difference(unary_union([area for _, area in kept]))) + coverage = gpd.GeoDataFrame( + {"source": ["GRB"], "region": ["VL"]}, + geometry=gpd.GeoSeries([covered if covered is not None else Polygon()], crs=crs), + crs=crs, + ) + by_reason = excluded.dissolve("reason").area.to_dict() if len(excluded) else {} + report = { + "rows": len(crossings), + "structure_counts": { + str(k): int(v) for k, v in crossings.structure.value_counts().to_dict().items() + }, + "complex_rows": int(crossings.complex_crossing.sum()), + "wbn": wbn_report, + "structures": structure_report, + "coverage": { + "bounds_area_m2": float(bounds.area), + "covered_area_m2": float(covered.area) if covered is not None else 0.0, + "excluded_area_m2_by_reason": {str(k): float(v) for k, v in by_reason.items()}, + }, + "axis_without_unit_m": float(unaccounted_length), + "nodeless_crossings_outside_structures": int(conflicts), + "thresholds": {**numbers, "complex_morf_codes": sorted(complex_codes)}, + } + return crossings, coverage, excluded, report diff --git a/tests/unit/test_grb_road_crossings.py b/tests/unit/test_grb_road_crossings.py new file mode 100644 index 0000000..3ba10ac --- /dev/null +++ b/tests/unit/test_grb_road_crossings.py @@ -0,0 +1,557 @@ +import geopandas as gpd +import pandas as pd +import pytest +from shapely.geometry import LineString, Point, Polygon, box + +from gispulse.capabilities.vector.grb_road_crossings import build_grb_road_crossings + +BOUNDS = (-100, -100, 100, 100) +KRUISPUNTZONE, WEGSEGMENT = 1, 2 + + +def wbn(*specs): + """``(oidn, polygon)`` or ``(oidn, polygon, type)``; type defaults to wegsegment.""" + return gpd.GeoDataFrame( + { + "OIDN": [s[0] for s in specs], + "TYPE": [s[2] if len(s) > 2 else WEGSEGMENT for s in specs], + }, + geometry=[s[1] for s in specs], + crs=31370, + ) + + +def axes(*specs): + """``(ws_id, line)`` or ``(ws_id, line, morf)`` or ``(ws_id, line, morf, status)``.""" + rows = [(*spec, 103, 4)[:4] if len(spec) == 2 else (*spec, 4)[:4] for spec in specs] + return gpd.GeoDataFrame( + { + "WS_OIDN": [r[0] for r in rows], + "MORF": [r[2] for r in rows], + "STATUS": [r[3] for r in rows], + }, + geometry=[r[1] for r in rows], + crs=31370, + ) + + +def knw(*specs): + """``(oidn, type, polygon)``.""" + return gpd.GeoDataFrame( + {"OIDN": [s[0] for s in specs], "TYPE": [s[1] for s in specs]}, + geometry=[s[2] for s in specs], + crs=31370, + ) + + +NO_KNW = gpd.GeoDataFrame(pd.DataFrame({"OIDN": [], "TYPE": []}), geometry=[], crs=31370) + + +def build(wbn_frame, axis_frame, knw_frame=NO_KNW, **overrides): + options = { + "coverage_bounds": BOUNDS, + "length_tolerance_m": 1e-6, + "area_tolerance_m2": 1e-6, + "boundary_tolerance_m": 1e-3, + "exclusion_buffer_m": 15.0, + **overrides, + } + return build_grb_road_crossings(wbn_frame, axis_frame, knw_frame, **options) + + +def by_id(crossings): + return {row.road_id: row for row in crossings.itertuples()} + + +def lines_of(axis): + return list(getattr(axis, "geoms", [axis])) + + +def covers(coverage, x, y): + return coverage.geometry.iloc[0].contains(Point(x, y)) + + +# --- ground needs a WBN element: never a default ---------------------------- + + +def test_wbn_element_carrying_a_motor_traffic_axis_is_ground(): + crossings, coverage, exclusions, report = build( + wbn((1, box(0, 0, 10, 10))), axes((9, LineString([(0, 5), (10, 5)]))) + ) + row = by_id(crossings)["GRB:WBN:1"] + assert row.structure == "ground" + assert not row.complex_crossing + assert "maaiveld" in row.structure_evidence + assert row.axis_ids == "9" and row.morf_codes == "103" + assert covers(coverage, 5, 5) and exclusions.empty + assert report["structure_counts"] == {"ground": 1} + assert report["axis_without_unit_m"] == 0 + + +def test_fragments_of_one_carriageway_share_one_road_id_and_one_axis(): + # A straight road cut into arbitrary WBN elements is one physical carriageway. + crossings, coverage, _, report = build( + wbn((0, box(-10, 0, 0, 10)), (1, box(0, 0, 10, 10)), (2, box(10, 0, 20, 10))), + axes((9, LineString([(-10, 5), (20, 5)]))), + ) + (row,) = crossings.itertuples() + assert row.road_id == "GRB:WBN:0" and row.source_ids == "0+1+2" + assert row.geometry.area == pytest.approx(300) + # Clipped against the united footprint: one continuous axis whose ends sit + # on the boundary, never strictly inside, and no break at a fragment cut. + (axis,) = lines_of(row.axis) + assert axis.length == pytest.approx(30) + assert not any(row.geometry.contains(Point(c)) for c in (axis.coords[0], axis.coords[-1])) + assert report["wbn"]["ground_elements"] == 3 and report["wbn"]["ground_units"] == 1 + assert covers(coverage, 5, 5) + + +def test_an_element_holding_a_junction_node_is_never_merged(): + # A side street joins without a mapped kruispuntzone: its axis enters the + # main element up to the node, yet the two are different streets. + crossings, *_ = build( + wbn((1, box(0, 0, 30, 10)), (2, box(10, 10, 20, 30))), + axes( + (11, LineString([(0, 5), (15, 5)])), + (12, LineString([(15, 5), (30, 5)])), + (13, LineString([(15, 5), (15, 30)])), + ), + ) + assert set(crossings.road_id) == {"GRB:WBN:1", "GRB:WBN:2"} + + +def test_an_element_reached_by_a_dead_end_street_is_never_merged(): + # Street 13 ends 3 m inside the main corridor without joining it: sharing + # that stub must not merge the two streets. + crossings, *_ = build( + wbn((1, box(0, 0, 30, 10)), (2, box(10, 10, 20, 30))), + axes((11, LineString([(0, 3), (30, 3)])), (13, LineString([(15, 7), (15, 30)]))), + ) + assert set(crossings.road_id) == {"GRB:WBN:1", "GRB:WBN:2"} + + +def test_an_element_of_undocumented_type_is_never_merged(): + crossings, _, _, report = build( + wbn((1, box(0, 0, 10, 10), "kruispuntzone"), (2, box(10, 0, 20, 10))), + axes((9, LineString([(0, 5), (20, 5)]))), + ) + assert set(crossings.road_id) == {"GRB:WBN:1", "GRB:WBN:2"} + assert report["wbn"]["unrecognised_type"] == 1 + + +def test_fragments_are_not_grouped_across_categories(): + crossings, *_ = build( + wbn((1, box(0, 0, 10, 10)), (2, box(10, 0, 20, 10))), + axes((9, LineString([(0, 5), (10, 5)]), 101), (8, LineString([(10, 5), (20, 5)]), 107)), + ) + assert set(crossings.road_id) == {"GRB:WBN:1", "GRB:WBN:2"} + + +def test_an_axis_with_no_wbn_is_never_ground_and_leaves_a_coverage_hole(): + crossings, coverage, exclusions, report = build( + wbn((1, box(0, 0, 10, 10))), + axes((9, LineString([(-5, 5), (15, 5)])), (8, LineString([(50, -50), (50, 50)]))), + ) + assert "8" not in ",".join(crossings.axis_ids) + assert not covers(coverage, 50, 0) + assert set(exclusions.reason) == {"axis_without_unit"} + # The 5 m stubs of axis 9 beyond the WBN element are unaccounted for as well + # (less the boundary tolerance absorbed at each cut). + assert report["axis_without_unit_m"] == pytest.approx(100 + 10, abs=0.01) + + +def test_reported_lengths_stop_at_the_bounds(): + _, _, _, report = build( + wbn((1, box(0, 0, 10, 10))), + axes((9, LineString([(0, 5), (10, 5)])), (8, LineString([(50, -500), (50, 500)]))), + ) + assert report["axis_without_unit_m"] == pytest.approx(200) + + +@pytest.mark.parametrize( + "morf, status", + [(-8, 4), (103, 3), (120, 4), (125, 4)], # unknown, not in service, dienstweg, aardeweg +) +def test_wbn_element_with_unresolved_axes_has_no_row_and_is_excluded(morf, status): + crossings, coverage, exclusions, report = build( + wbn((1, box(0, 0, 10, 10))), axes((9, LineString([(0, 5), (10, 5)]), morf, status)) + ) + assert crossings.empty + assert set(exclusions.reason) == {"wbn_axes_unresolved"} + assert not covers(coverage, 5, 5) + assert report["wbn"]["unresolved"] == 1 + + +def test_an_unresolved_branch_in_a_ground_element_is_kept_out_of_coverage(): + # The carriageway is still ground, but a trench crossing only the dienstweg + # branch would see no axis: the branch's surroundings leave coverage. + crossings, coverage, exclusions, report = build( + wbn((1, box(0, 0, 100, 10))), + axes((9, LineString([(0, 5), (100, 5)])), (7, LineString([(50, 5), (50, 10)]), 120)), + ) + row = by_id(crossings)["GRB:WBN:1"] + assert row.structure == "ground" and row.axis_ids == "9" + assert set(exclusions.reason) == {"wbn_axes_unresolved"} + assert not covers(coverage, 50, 8) + assert covers(coverage, 90, 5) # the verdict does not depend on the branch + assert report["wbn"]["with_unresolved_axes"] == 1 + + +def test_wbn_element_without_any_axis_has_no_row_and_is_excluded(): + crossings, coverage, exclusions, report = build(wbn((1, box(0, 0, 10, 10))), axes()) + assert crossings.empty + assert set(exclusions.reason) == {"wbn_without_axis"} + assert not covers(coverage, 5, 5) + assert report["wbn"]["without_axis"] == 1 + + +def test_documented_non_motor_corridor_stays_covered_without_a_row(): + crossings, coverage, exclusions, report = build( + wbn((1, box(0, 0, 10, 10))), axes((9, LineString([(0, 5), (10, 5)]), 114)) + ) + assert crossings.empty + assert exclusions.empty + assert covers(coverage, 5, 5) + assert report["wbn"]["non_carriageway"] == 1 + + +def test_a_footprint_leaving_the_bounds_is_excluded(): + # Axes entirely outside the bounds were never acquired: the verdict of a + # footprint reaching out there cannot be trusted inside either. + crossings, coverage, exclusions, _ = build( + wbn((1, box(90, 0, 110, 10))), axes((9, LineString([(90, 5), (110, 5)]))) + ) + assert list(crossings.road_id) == ["GRB:WBN:1"] + assert "footprint_crosses_bounds" in set(exclusions.reason) + assert not covers(coverage, 95, 5) + + +# --- axis geometry: tangent, collinear, cut at the crossroads ---------------- + + +def test_an_axis_tangent_to_a_footprint_is_not_its_axis(): + road = wbn((1, box(0, 0, 10, 10))) + lines = axes( + (9, LineString([(0, 5), (10, 5)])), + (7, LineString([(-5, 15), (0, 10), (5, 15)])), # touches the (0, 10) corner only + (6, LineString([(5, 10), (5, 30)])), # ends on the boundary, from outside + ) + crossings, *_ = build(road, lines) + assert by_id(crossings)["GRB:WBN:1"].axis_ids == "9" + + +def test_an_axis_on_a_shared_boundary_belongs_to_neither_element_and_leaves_a_hole(): + road = wbn((1, box(0, 0, 10, 10)), (2, box(0, 10, 10, 20))) + lines = axes( + (9, LineString([(0, 5), (10, 5)])), + (8, LineString([(0, 15), (10, 15)])), + (7, LineString([(0, 10), (10, 10)])), # exactly on the shared edge + ) + crossings, coverage, exclusions, _ = build(road, lines) + rows = by_id(crossings) + assert rows["GRB:WBN:1"].axis_ids == "9" + assert rows["GRB:WBN:2"].axis_ids == "8" + assert "axis_without_unit" in set(exclusions.reason) + assert not covers(coverage, 5, 10) + + +def test_axes_cut_at_the_crossroads_end_at_the_junction_node_only(): + # Kruispuntzone 2 between arms 1 and 3, with side arm 4; junction node (15, 5). + road = wbn( + (1, box(0, 0, 10, 10)), + (2, box(10, 0, 20, 10), KRUISPUNTZONE), + (3, box(20, 0, 30, 10)), + (4, box(10, 10, 20, 20)), + ) + lines = axes( + (11, LineString([(0, 5), (15, 5)])), + (12, LineString([(15, 5), (30, 5)])), + (13, LineString([(15, 5), (15, 20)])), + ) + crossings, *_ = build(road, lines) + rows = by_id(crossings) + # A kruispuntzone is never merged with the carriageways meeting there. + assert set(rows) == {"GRB:WBN:1", "GRB:WBN:2", "GRB:WBN:3", "GRB:WBN:4"} + junction = rows["GRB:WBN:2"] + assert junction.axis_ids == "11,12,13" + branches = lines_of(junction.axis) + assert len(branches) == 3 # degree-3 node: never merged across a junction + inner_ends = [ + Point(c) + for line in branches + for c in (line.coords[0], line.coords[-1]) + if junction.geometry.contains(Point(c)) + ] + assert inner_ends and all(p.equals(Point(15, 5)) for p in inner_ends) + + +def test_contiguous_axis_pieces_are_joined_at_a_degree_two_node(): + crossings, *_ = build( + wbn((1, box(0, 0, 20, 10))), + axes((11, LineString([(0, 5), (10, 5)])), (12, LineString([(10, 5), (20, 5)]))), + ) + (axis,) = lines_of(by_id(crossings)["GRB:WBN:1"].axis) + assert axis.length == pytest.approx(20) + + +# --- structures: a level relation, grouped by road_id ------------------------ + + +def _overpass(): + """U crosses L at (5, 5) with no node, inside bridge polygon 77.""" + return axes(("U", LineString([(-20, 5), (30, 5)])), ("L", LineString([(5, -20), (5, 30)]))) + + +def _corridors(): + """WBN on both sides of bridge 77 for U and L: the structure is the only gap.""" + return wbn( + (1, box(-20, 0, 0, 10)), + (2, box(10, 0, 30, 10)), + (3, box(0, -20, 10, 0)), + (4, box(0, 10, 10, 30)), + ) + + +def test_node_less_crossing_inside_a_bridge_is_grade_separated(): + crossings, coverage, exclusions, report = build( + _corridors(), _overpass(), knw((77, 1, box(0, 0, 10, 10))) + ) + row = by_id(crossings)["GRB:KNW:77"] + assert row.structure == "grade_separated" + assert "UxL" in row.structure_evidence + assert covers(coverage, 5, 5) and exclusions.empty + assert report["structures"]["grade_separated"] == 1 + assert report["axis_without_unit_m"] == 0 + + +def test_bridge_with_a_single_axis_is_unknown_never_ground(): + lines = axes(("U", LineString([(-20, 5), (30, 5)]))) + crossings, coverage, exclusions, report = build( + wbn((1, box(-20, 0, 0, 10)), (2, box(10, 0, 30, 10))), + lines, + knw((77, 1, box(0, 0, 10, 10))), + ) + row = by_id(crossings)["GRB:KNW:77"] + assert row.structure == "unknown" + assert "single_axis" in row.structure_evidence + assert set(exclusions.reason) == {"structure_single_axis"} + assert not covers(coverage, 5, 5) + assert report["structures"]["unknown"] == {"single_axis": 1} + + +def test_an_axis_ending_inside_a_structure_makes_it_unknown(): + lines = axes( + ("U", LineString([(-20, 5), (30, 5)])), + ("L", LineString([(5, -20), (5, 5)])), # ends on the deck: a junction or dead end + ("M", LineString([(8, -20), (8, 30)])), + ) + crossings, *_ = build(wbn((1, box(-20, 0, 0, 10))), lines, knw((77, 12, box(0, 0, 10, 10)))) + assert "axis_ends_inside" in by_id(crossings)["GRB:KNW:77"].structure_evidence + + +def test_an_axis_crossing_nothing_inside_a_structure_makes_it_unknown(): + lines = axes( + ("U", LineString([(-20, 5), (30, 5)])), + ("L", LineString([(5, -20), (5, 30)])), + ("P", LineString([(-20, 8), (30, 8)])), # parallel to U, crosses L + ("Q", LineString([(-20, 2), (30, 2)])), + ) + # Q and P both cross L, so every axis takes part: grade separated. + crossings, *_ = build(wbn((1, box(-20, 0, 0, 10))), lines, knw((77, 1, box(0, 0, 10, 10)))) + assert by_id(crossings)["GRB:KNW:77"].structure == "grade_separated" + lonely = axes( + ("U", LineString([(-20, 5), (30, 5)])), + ("L", LineString([(5, -20), (5, 30)])), + ("P", LineString([(-20, 8), (2, 8), (2, 30)])), # inside, crosses neither U nor L + ) + crossings, *_ = build(wbn((1, box(-20, 0, 0, 10))), lonely, knw((77, 1, box(0, 0, 10, 10)))) + assert "axis_not_crossed" in by_id(crossings)["GRB:KNW:77"].structure_evidence + + +def test_an_unresolved_axis_on_a_structure_keeps_it_out_of_coverage(): + lines = axes( + ("U", LineString([(-20, 5), (30, 5)])), + ("L", LineString([(5, -20), (5, 30)])), + ("D", LineString([(8, -20), (8, 8)]), 120), # a dienstweg ending on the deck + ) + crossings, coverage, exclusions, report = build( + _corridors(), lines, knw((77, 1, box(0, 0, 10, 10))) + ) + assert by_id(crossings)["GRB:KNW:77"].structure == "grade_separated" + assert "structure_axes_unresolved" in set(exclusions.reason) + assert not covers(coverage, 8, 8) + assert report["structures"]["with_unresolved_axes"] == 1 + + +def test_touching_structure_polygons_are_one_road_id_with_one_footprint(): + # The deck is split in two KNW polygons; L only crosses the second one. + # Evaluated alone, polygon 1 would be a single-axis `unknown`. + crossings, *_ = build( + wbn((1, box(-20, 0, 0, 10))), + axes(("U", LineString([(-20, 5), (30, 5)])), ("L", LineString([(8, -20), (8, 30)]))), + knw((501, 1, box(0, 0, 5, 10)), (502, 1, box(5, 0, 10, 10))), + ) + knw_rows = crossings[crossings.source_layer == "KNW"] + assert list(knw_rows.road_id) == ["GRB:KNW:501+502"] + assert knw_rows.geometry.iloc[0].area == pytest.approx(100) + assert knw_rows.structure.iloc[0] == "grade_separated" + assert crossings.road_id.is_unique + + +def test_structure_without_any_drivable_axis_is_no_road_and_stays_covered(): + crossings, coverage, _, report = build( + wbn((1, box(-20, 0, 0, 10))), + axes(("U", LineString([(-20, 5), (0, 5)])), ("F", LineString([(5, -20), (5, 30)]), 114)), + knw((77, 1, box(0, 0, 10, 10)), (78, 1, box(40, 40, 50, 50))), + ) + assert not set(by_id(crossings)) & {"GRB:KNW:77", "GRB:KNW:78"} + assert covers(coverage, 5, 5) and covers(coverage, 45, 45) + assert report["structures"]["without_carriageway"] == 2 + + +def test_non_structure_knw_codes_are_ignored(): + crossings, *_ = build( + wbn((1, box(-20, 0, 0, 10))), _overpass(), knw((77, 5, box(0, 0, 10, 10))) + ) # 5 = pijler + assert list(crossings.source_layer) == ["WBN"] + + +# --- no spatial duplicate ---------------------------------------------------- + + +def test_structures_take_priority_over_overlapping_wbn(): + crossings, _, _, report = build( + wbn((1, box(-20, 0, 2, 10))), _overpass(), knw((77, 1, box(0, 0, 10, 10))) + ) + rows = by_id(crossings) + assert rows["GRB:WBN:1"].geometry.area == pytest.approx(200) + assert rows["GRB:WBN:1"].geometry.intersection(rows["GRB:KNW:77"].geometry).area == 0 + assert report["wbn"]["overlap_trimmed"] == 1 + + +def test_overlapping_wbn_elements_never_claim_the_same_area_twice(): + # Distinct carriageways: two rows, the later element trimmed. + crossings, *_ = build( + wbn((1, box(0, 0, 10, 10)), (2, box(8, 0, 20, 10))), + axes((9, LineString([(0, 5), (5, 5)])), (8, LineString([(12, 5), (20, 5)]))), + ) + rows = by_id(crossings) + assert rows["GRB:WBN:1"].geometry.area == pytest.approx(100) + assert rows["GRB:WBN:2"].geometry.area == pytest.approx(100) + assert rows["GRB:WBN:1"].geometry.intersection(rows["GRB:WBN:2"].geometry).area == 0 + # Fragments of one carriageway: one row whose area is counted once. + crossings, *_ = build( + wbn((1, box(0, 0, 10, 10)), (2, box(8, 0, 20, 10))), + axes((9, LineString([(0, 5), (20, 5)]))), + ) + (row,) = crossings.itertuples() + assert row.source_ids == "1+2" and row.geometry.area == pytest.approx(200) + + +# --- category and level consistency ----------------------------------------- + + +def test_complex_crossing_comes_from_the_motorway_morphology_only(): + crossings, *_ = build( + wbn((1, box(0, 0, 10, 10)), (2, box(0, 20, 10, 30))), + axes((9, LineString([(0, 5), (10, 5)]), 101), (8, LineString([(0, 25), (10, 25)]), 102)), + ) + rows = by_id(crossings) + assert bool(rows["GRB:WBN:1"].complex_crossing) is True + assert bool(rows["GRB:WBN:2"].complex_crossing) is False + crossings, _, _, report = build( + wbn((2, box(0, 20, 10, 30))), + axes((8, LineString([(0, 25), (10, 25)]), 102)), + complex_morf_codes=(101, 102), + ) + assert bool(crossings.complex_crossing.iloc[0]) is True + assert report["thresholds"]["complex_morf_codes"] == [101, 102] + + +def test_node_less_crossing_outside_any_structure_is_excluded_from_coverage(): + _, coverage, exclusions, report = build( + wbn((1, box(-20, 0, 30, 10)), (2, box(0, -20, 10, 0)), (3, box(0, 10, 10, 30))), + _overpass(), + ) + assert report["nodeless_crossings_outside_structures"] == 1 + assert "nodeless_crossing_outside_structure" in set(exclusions.reason) + assert not covers(coverage, 5, 5) + + +def test_a_self_crossing_axis_outside_any_structure_is_excluded_from_coverage(): + spiral = LineString([(0, 2), (20, 2), (20, 8), (10, 8), (10, 0)]) # crosses itself at (10, 2) + _, coverage, exclusions, report = build(wbn((1, box(0, 0, 20, 10))), axes((9, spiral, 107))) + assert report["nodeless_crossings_outside_structures"] == 1 + assert "nodeless_crossing_outside_structure" in set(exclusions.reason) + assert not covers(coverage, 10, 2) + + +# --- output contract --------------------------------------------------------- + + +def test_artifact_round_trips_through_geoparquet_with_both_crs(tmp_path): + from gispulse.core.io.geoparquet import write_geoparquet + from gispulse.persistence.io import read_geoparquet + + crossings, coverage, *_ = build(_corridors(), _overpass(), knw((77, 1, box(0, 0, 10, 10)))) + path = tmp_path / "road_crossings.geoparquet" + write_geoparquet(crossings, str(path)) + frame = read_geoparquet(str(path)) + assert {"road_id", "axis", "structure", "complex_crossing"} <= set(frame.columns) + assert frame.crs.to_epsg() == 31370 + assert frame["axis"].crs == frame.crs + assert set(frame.geom_type) <= {"Polygon", "MultiPolygon"} + assert set(frame["axis"].geom_type) <= {"LineString", "MultiLineString"} + assert set(frame.structure) <= {"ground", "grade_separated", "unknown"} + assert frame.complex_crossing.dtype == bool + assert not frame.road_id.isna().any() and frame.road_id.is_unique + assert all(line.is_simple for axis in frame["axis"] for line in lines_of(axis)) + assert coverage.crs.to_epsg() == 31370 and len(coverage) == 1 + + +def test_exclusions_are_polygonal_even_when_they_only_touch_the_bounds(): + _, _, exclusions, _ = build(wbn((1, box(100, 0, 110, 10))), axes()) + assert set(exclusions.geom_type) <= {"Polygon", "MultiPolygon"} + + +def test_empty_inputs_give_an_empty_but_typed_artifact_and_full_coverage(): + crossings, coverage, exclusions, report = build( + gpd.GeoDataFrame({"OIDN": [], "TYPE": []}, geometry=[], crs=31370), + axes(), + gpd.GeoDataFrame({"TYPE": []}, geometry=[], crs=31370), # no KNW id column at all + ) + assert crossings.empty and exclusions.empty + assert crossings["axis"].crs == crossings.crs + assert coverage.geometry.iloc[0].equals(box(*BOUNDS)) + assert report["rows"] == 0 + + +@pytest.mark.parametrize( + "mutate, code", + [ + (lambda w, a, k: (w.to_crs(3812), a, k), "GRB_CROSSINGS_CRS_INVALID"), + (lambda w, a, k: (w, a.drop(columns="MORF"), k), "GRB_CROSSINGS_FIELD_MISSING"), + (lambda w, a, k: (w.drop(columns="TYPE"), a, k), "GRB_CROSSINGS_FIELD_MISSING"), + (lambda w, a, k: (w, a, k.drop(columns="OIDN")), "GRB_CROSSINGS_FIELD_MISSING"), + (lambda w, a, k: (w, pd.concat([a, a]), k), "GRB_CROSSINGS_ID_INVALID"), + (lambda w, a, k: (w, a.assign(WS_OIDN=[None, "L"]), k), "GRB_CROSSINGS_ID_INVALID"), + (lambda w, a, k: (w, a, pd.concat([k, k])), "GRB_CROSSINGS_ID_INVALID"), + ( + lambda w, a, k: (wbn((1, Polygon([(0, 0), (1, 1), (1, 0), (0, 1)]))), a, k), + "GRB_CROSSINGS_GEOMETRY_INVALID", + ), + ], +) +def test_data_defects_raise_dedicated_codes(mutate, code): + w, a, k = mutate(wbn((1, box(-20, 0, 0, 10))), _overpass(), knw((77, 1, box(0, 0, 10, 10)))) + with pytest.raises(ValueError, match=code): + build(w, a, k) + + +@pytest.mark.parametrize( + "overrides", + [{"exclusion_buffer_m": 0}, {"length_tolerance_m": -1}, {"coverage_bounds": (1, 0, 0, 1)}], +) +def test_invalid_parameters_are_rejected(overrides): + with pytest.raises(ValueError, match="GRB_CROSSINGS_"): + build(wbn((1, box(0, 0, 10, 10))), axes(), **overrides) diff --git a/tests/unit/test_src_grb.py b/tests/unit/test_src_grb.py index 2f0a95d..50bb45b 100644 --- a/tests/unit/test_src_grb.py +++ b/tests/unit/test_src_grb.py @@ -141,7 +141,9 @@ def _grb_wfs_stub(monkeypatch, *, wegsegment, knw=None): pd.DataFrame({"OIDN": [], "TYPE": []}), geometry=gpd.GeoSeries([], crs=31370) ) layers = { - "GRB:WBN": gpd.GeoDataFrame({"OIDN": [1]}, geometry=[box(0, 0, 10, 10)], crs=31370), + "GRB:WBN": gpd.GeoDataFrame( + {"OIDN": [1], "TYPE": [2]}, geometry=[box(0, 0, 10, 10)], crs=31370 + ), "GRB:WGO": gpd.GeoDataFrame( {"OIDN": [1], "TYPE": [1]}, geometry=[LineString([(0, 8), (10, 8)])], crs=31370 ), @@ -357,6 +359,10 @@ def test_grb_bundle_survives_a_broken_wegsegment_layer_and_degrades_classificati assert (output / "partition_diagnostics.geoparquet").exists() assert (output / "grb-wegsegment-vl.geoparquet").exists() assert not (output / "classified_faces.geoparquet").exists() + # The same defect (no MORF either) degrades road crossings the same way. + assert report["road_crossings"]["status"] == "failed" + assert "GRB_CROSSINGS_FIELD_MISSING" in report["road_crossings"]["error"] + assert not (output / "road_crossings.geoparquet").exists() def test_a_genuine_classifier_bug_is_never_relabelled_as_a_data_defect(tmp_path, monkeypatch): @@ -394,3 +400,43 @@ def buggy_classify(faces, *_args, **_kwargs): output = tmp_path / "bundle" with pytest.raises(ValueError, match="GRB_FUNCTION_CLASS_UNKNOWN"): prepare_module.prepare_grb(bbox=(-1, -1, 11, 11), output=output, write=True) + + +def test_grb_bundle_publishes_road_crossings_with_a_separate_coverage(tmp_path, monkeypatch): + import geopandas as gpd + from gispulse_src_grb.prepare import prepare_grb + from shapely.geometry import LineString, Point + + from gispulse.persistence.io import read_geoparquet + + road = gpd.GeoDataFrame( + {"OIDN": [1], "WS_OIDN": ["9"], "VERH": [1], "STATUS": [4], "MORF": [103]}, + geometry=[LineString([(0, 4), (10, 4)])], + crs=31370, + ) + _grb_wfs_stub(monkeypatch, wegsegment=road) + output = tmp_path / "bundle" + report = prepare_grb(bbox=(-1, -1, 11, 11), output=output, write=True) + + crossings_report = report["road_crossings"] + assert crossings_report["status"] == "prepared" + assert crossings_report["structure_counts"] == {"ground": 1} + assert crossings_report["thresholds"]["exclusion_buffer_m"] == 15.0 + assert report["crossing_exclusion_buffer_m"] == 15.0 + crossings = read_geoparquet(str(output / "road_crossings.geoparquet")) + assert list(crossings.road_id) == ["GRB:WBN:1"] + assert crossings["axis"].crs == crossings.crs and crossings.crs.to_epsg() == 31370 + coverage = gpd.read_parquet(output / "road_crossings_coverage.geoparquet") + assert coverage.geometry.iloc[0].contains(Point(5, 4)) + assert (output / "road_crossings_exclusions.geoparquet").exists() + assert {"road_crossings.geoparquet", "road_crossings_coverage.geoparquet"} <= set( + report["sha256"] + ) + + +def test_grb_plan_rejects_a_nonpositive_crossing_buffer_up_front(tmp_path): + from gispulse_src_grb.prepare import prepare_grb + + with pytest.raises(ValueError, match="GRB_TOLERANCE_INVALID"): + prepare_grb(bbox=(0, 0, 1, 1), output=tmp_path / "b", crossing_exclusion_buffer_m=0) + assert list(tmp_path.iterdir()) == []