python-osw-validation 0.3.7__py3-none-any.whl → 0.4.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- python_osw_validation/__init__.py +160 -4
- python_osw_validation/geometry_mapping_validator.py +374 -0
- python_osw_validation/helpers.py +24 -0
- python_osw_validation/version.py +1 -1
- {python_osw_validation-0.3.7.dist-info → python_osw_validation-0.4.1.dist-info}/METADATA +5 -1
- {python_osw_validation-0.3.7.dist-info → python_osw_validation-0.4.1.dist-info}/RECORD +9 -8
- {python_osw_validation-0.3.7.dist-info → python_osw_validation-0.4.1.dist-info}/WHEEL +0 -0
- {python_osw_validation-0.3.7.dist-info → python_osw_validation-0.4.1.dist-info}/licenses/LICENSE +0 -0
- {python_osw_validation-0.3.7.dist-info → python_osw_validation-0.4.1.dist-info}/top_level.txt +0 -0
|
@@ -2,7 +2,6 @@ import os
|
|
|
2
2
|
import gc
|
|
3
3
|
import json
|
|
4
4
|
import math
|
|
5
|
-
import traceback
|
|
6
5
|
from typing import Dict, Any, Optional, List, Tuple
|
|
7
6
|
import geopandas as gpd
|
|
8
7
|
import jsonschema_rs
|
|
@@ -15,6 +14,7 @@ from .helpers import (
|
|
|
15
14
|
_err_kind,
|
|
16
15
|
_feature_index_from_error,
|
|
17
16
|
_pretty_message,
|
|
17
|
+
_read_geojson_without_ext,
|
|
18
18
|
)
|
|
19
19
|
|
|
20
20
|
SCHEMA_PATH = os.path.join(os.path.dirname(__file__), 'schema')
|
|
@@ -112,6 +112,156 @@ class OSWValidation:
|
|
|
112
112
|
self.log_errors(f"Could not create set for column '{col}' in {filekey}.", filekey, None)
|
|
113
113
|
return set()
|
|
114
114
|
|
|
115
|
+
# ----------------------------
|
|
116
|
+
# Geometry mapping helpers
|
|
117
|
+
# ----------------------------
|
|
118
|
+
|
|
119
|
+
_COORD_TOLERANCE = 1e-7 # ~1 cm at equator
|
|
120
|
+
|
|
121
|
+
def _coords_match(self, c1: tuple, c2: tuple) -> bool:
|
|
122
|
+
return abs(c1[0] - c2[0]) <= self._COORD_TOLERANCE and abs(c1[1] - c2[1]) <= self._COORD_TOLERANCE
|
|
123
|
+
|
|
124
|
+
def _build_node_coord_map(self, nodes_df: gpd.GeoDataFrame) -> Dict[Any, tuple]:
|
|
125
|
+
"""Return {node_id: (lon, lat)} from a nodes GeoDataFrame."""
|
|
126
|
+
coord_map: Dict[Any, tuple] = {}
|
|
127
|
+
for _, row in nodes_df.iterrows():
|
|
128
|
+
try:
|
|
129
|
+
nid = row['_id']
|
|
130
|
+
except KeyError:
|
|
131
|
+
continue
|
|
132
|
+
geom = row.geometry
|
|
133
|
+
if nid is not None and geom is not None and geom.geom_type == 'Point':
|
|
134
|
+
coord_map[nid] = (geom.x, geom.y)
|
|
135
|
+
return coord_map
|
|
136
|
+
|
|
137
|
+
def _validate_edge_geometry_mapping(
|
|
138
|
+
self,
|
|
139
|
+
edges_df: Optional[gpd.GeoDataFrame],
|
|
140
|
+
node_coord_map: Dict[Any, tuple],
|
|
141
|
+
max_errors: int,
|
|
142
|
+
) -> None:
|
|
143
|
+
"""Verify edge start/end coordinates match their _u_id/_v_id node geometries."""
|
|
144
|
+
if edges_df is None or not node_coord_map:
|
|
145
|
+
return
|
|
146
|
+
|
|
147
|
+
has_u_id = '_u_id' in edges_df.columns
|
|
148
|
+
has_v_id = '_v_id' in edges_df.columns
|
|
149
|
+
if not (has_u_id or has_v_id):
|
|
150
|
+
return
|
|
151
|
+
|
|
152
|
+
for feat_idx, row in edges_df.iterrows():
|
|
153
|
+
if len(self.errors) >= max_errors:
|
|
154
|
+
break
|
|
155
|
+
|
|
156
|
+
geom = row.geometry
|
|
157
|
+
if geom is None or geom.geom_type != 'LineString':
|
|
158
|
+
continue
|
|
159
|
+
|
|
160
|
+
coords = list(geom.coords)
|
|
161
|
+
if not coords:
|
|
162
|
+
continue
|
|
163
|
+
|
|
164
|
+
try:
|
|
165
|
+
edge_id = row['_id']
|
|
166
|
+
except KeyError:
|
|
167
|
+
edge_id = feat_idx
|
|
168
|
+
|
|
169
|
+
if has_u_id:
|
|
170
|
+
try:
|
|
171
|
+
u_id = row['_u_id']
|
|
172
|
+
except KeyError:
|
|
173
|
+
u_id = None
|
|
174
|
+
if u_id is not None and u_id in node_coord_map:
|
|
175
|
+
node_coord = node_coord_map[u_id]
|
|
176
|
+
edge_start = (coords[0][0], coords[0][1])
|
|
177
|
+
if not self._coords_match(edge_start, node_coord):
|
|
178
|
+
self.log_errors(
|
|
179
|
+
message=(
|
|
180
|
+
f"edges id '{edge_id}' : "
|
|
181
|
+
f"start coordinate {edge_start} does not match "
|
|
182
|
+
f"node id '{u_id}' coordinate {node_coord} (_u_id mismatch)."
|
|
183
|
+
),
|
|
184
|
+
filename='edges',
|
|
185
|
+
feature_index=feat_idx,
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
if len(self.errors) >= max_errors:
|
|
189
|
+
break
|
|
190
|
+
|
|
191
|
+
if has_v_id:
|
|
192
|
+
try:
|
|
193
|
+
v_id = row['_v_id']
|
|
194
|
+
except KeyError:
|
|
195
|
+
v_id = None
|
|
196
|
+
if v_id is not None and v_id in node_coord_map:
|
|
197
|
+
node_coord = node_coord_map[v_id]
|
|
198
|
+
edge_end = (coords[-1][0], coords[-1][1])
|
|
199
|
+
if not self._coords_match(edge_end, node_coord):
|
|
200
|
+
self.log_errors(
|
|
201
|
+
message=(
|
|
202
|
+
f"edges id '{edge_id}' : "
|
|
203
|
+
f"end coordinate {edge_end} does not match "
|
|
204
|
+
f"node id '{v_id}' coordinate {node_coord} (_v_id mismatch)."
|
|
205
|
+
),
|
|
206
|
+
filename='edges',
|
|
207
|
+
feature_index=feat_idx,
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
def _validate_zone_geometry_mapping(
|
|
211
|
+
self,
|
|
212
|
+
zones_df: Optional[gpd.GeoDataFrame],
|
|
213
|
+
node_coord_map: Dict[Any, tuple],
|
|
214
|
+
max_errors: int,
|
|
215
|
+
) -> None:
|
|
216
|
+
"""Verify each _w_id node coordinate is a vertex of the zone's polygon exterior ring."""
|
|
217
|
+
if zones_df is None or not node_coord_map:
|
|
218
|
+
return
|
|
219
|
+
|
|
220
|
+
if '_w_id' not in zones_df.columns:
|
|
221
|
+
return
|
|
222
|
+
|
|
223
|
+
for feat_idx, row in zones_df.iterrows():
|
|
224
|
+
if len(self.errors) >= max_errors:
|
|
225
|
+
break
|
|
226
|
+
|
|
227
|
+
geom = row.geometry
|
|
228
|
+
if geom is None or geom.geom_type != 'Polygon':
|
|
229
|
+
continue
|
|
230
|
+
|
|
231
|
+
try:
|
|
232
|
+
zone_id = row['_id']
|
|
233
|
+
except KeyError:
|
|
234
|
+
zone_id = feat_idx
|
|
235
|
+
|
|
236
|
+
ring_coords = {(c[0], c[1]) for c in geom.exterior.coords}
|
|
237
|
+
|
|
238
|
+
try:
|
|
239
|
+
w_ids = row['_w_id']
|
|
240
|
+
except KeyError:
|
|
241
|
+
continue
|
|
242
|
+
|
|
243
|
+
if w_ids is None:
|
|
244
|
+
continue
|
|
245
|
+
if not isinstance(w_ids, (list, tuple)):
|
|
246
|
+
w_ids = [w_ids]
|
|
247
|
+
|
|
248
|
+
for w_id in w_ids:
|
|
249
|
+
if len(self.errors) >= max_errors:
|
|
250
|
+
break
|
|
251
|
+
if w_id is None or w_id not in node_coord_map:
|
|
252
|
+
continue
|
|
253
|
+
node_coord = node_coord_map[w_id]
|
|
254
|
+
if not any(self._coords_match(node_coord, rc) for rc in ring_coords):
|
|
255
|
+
self.log_errors(
|
|
256
|
+
message=(
|
|
257
|
+
f"zones id '{zone_id}' : "
|
|
258
|
+
f"node id '{w_id}' coordinate {node_coord} is not a vertex "
|
|
259
|
+
f"of the zone polygon geometry (_w_id coordinate mismatch)."
|
|
260
|
+
),
|
|
261
|
+
filename='zones',
|
|
262
|
+
feature_index=feat_idx,
|
|
263
|
+
)
|
|
264
|
+
|
|
115
265
|
def _schema_key_from_text(self, text: Optional[str]) -> Optional[str]:
|
|
116
266
|
"""Return dataset key from exact filename suffixes only."""
|
|
117
267
|
if not text:
|
|
@@ -270,7 +420,7 @@ class OSWValidation:
|
|
|
270
420
|
osw_file = next((osw_key for osw_key in OSW_DATASET_FILES.keys()
|
|
271
421
|
if osw_key in os.path.basename(file_path)), '')
|
|
272
422
|
try:
|
|
273
|
-
gdf =
|
|
423
|
+
gdf = _read_geojson_without_ext(file_path)
|
|
274
424
|
except Exception as e:
|
|
275
425
|
self.log_errors(
|
|
276
426
|
message=f"Failed to read '{os.path.basename(file_path)}' as GeoJSON: {e}",
|
|
@@ -370,6 +520,13 @@ class OSWValidation:
|
|
|
370
520
|
feature_index=None
|
|
371
521
|
)
|
|
372
522
|
|
|
523
|
+
# Geometry mapping: coordinate consistency using already-loaded GeoDataFrames
|
|
524
|
+
if nodes_df is not None and len(self.errors) < max_errors:
|
|
525
|
+
node_coord_map = self._build_node_coord_map(nodes_df)
|
|
526
|
+
if node_coord_map:
|
|
527
|
+
self._validate_edge_geometry_mapping(edges_df, node_coord_map, max_errors)
|
|
528
|
+
self._validate_zone_geometry_mapping(zones_df, node_coord_map, max_errors)
|
|
529
|
+
|
|
373
530
|
# Geometry validation: check geometry type and SFA validity
|
|
374
531
|
for osw_file, gdf in OSW_DATASET.items():
|
|
375
532
|
if gdf is None:
|
|
@@ -401,7 +558,7 @@ class OSWValidation:
|
|
|
401
558
|
file_path = os.path.join(file)
|
|
402
559
|
file_name = os.path.basename(file)
|
|
403
560
|
try:
|
|
404
|
-
extensionFile =
|
|
561
|
+
extensionFile = _read_geojson_without_ext(file_path)
|
|
405
562
|
except Exception as e:
|
|
406
563
|
self.log_errors(
|
|
407
564
|
message=f"Failed to read extension '{file_name}' as GeoJSON: {e}",
|
|
@@ -454,7 +611,6 @@ class OSWValidation:
|
|
|
454
611
|
filename=None,
|
|
455
612
|
feature_index=None
|
|
456
613
|
)
|
|
457
|
-
traceback.print_exc()
|
|
458
614
|
return _finalize(False)
|
|
459
615
|
finally:
|
|
460
616
|
# Cleanup extracted files
|
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
"""Geometry mapping consistency validation for OSW datasets.
|
|
2
|
+
|
|
3
|
+
This module validates that cross-file references between OSW dataset
|
|
4
|
+
components correspond to real geometries:
|
|
5
|
+
|
|
6
|
+
* ``edges._u_id`` / ``edges._v_id`` must reference an existing node in
|
|
7
|
+
``nodes.geojson`` AND the node's coordinates must equal the corresponding
|
|
8
|
+
endpoint of the edge ``LineString`` (start coord for ``_u_id``, end coord
|
|
9
|
+
for ``_v_id``).
|
|
10
|
+
* ``zones._w_id`` is a list of node ids whose coordinates must match the
|
|
11
|
+
zone polygon's outer ring vertices, in order.
|
|
12
|
+
|
|
13
|
+
The validator emits structured issues with ``filename``, ``feature_index``,
|
|
14
|
+
``feature_id`` (when available) and a clear, actionable error message.
|
|
15
|
+
|
|
16
|
+
Coordinate matching is performed by exact equality on the (lon, lat) pair.
|
|
17
|
+
Altitude / extra coordinate dimensions are ignored.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple
|
|
23
|
+
import math
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
# ---------------------------------------------------------------------------
|
|
27
|
+
# Coordinate helpers
|
|
28
|
+
# ---------------------------------------------------------------------------
|
|
29
|
+
|
|
30
|
+
Coord = Tuple[float, float]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _coord_key(coord: Sequence[Any]) -> Optional[Coord]:
|
|
34
|
+
"""Return (lon, lat) tuple for a coordinate, or None when malformed."""
|
|
35
|
+
if not isinstance(coord, (list, tuple)) or len(coord) < 2:
|
|
36
|
+
return None
|
|
37
|
+
try:
|
|
38
|
+
lon = float(coord[0])
|
|
39
|
+
lat = float(coord[1])
|
|
40
|
+
except (TypeError, ValueError):
|
|
41
|
+
return None
|
|
42
|
+
if math.isnan(lon) or math.isnan(lat):
|
|
43
|
+
return None
|
|
44
|
+
return (lon, lat)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _format_coord(coord: Optional[Sequence[Any]]) -> str:
|
|
48
|
+
key = _coord_key(coord) if coord is not None else None
|
|
49
|
+
if key is None:
|
|
50
|
+
return "<missing>"
|
|
51
|
+
return f"({key[0]}, {key[1]})"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
# ---------------------------------------------------------------------------
|
|
55
|
+
# Index builders
|
|
56
|
+
# ---------------------------------------------------------------------------
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def build_node_coord_index(nodes_geojson: Optional[Dict[str, Any]]) -> Dict[str, Coord]:
|
|
60
|
+
"""Map each node ``_id`` to its (lon, lat) coordinate.
|
|
61
|
+
|
|
62
|
+
Nodes without a usable ``_id`` or geometry are skipped silently;
|
|
63
|
+
higher level validation already reports those issues.
|
|
64
|
+
"""
|
|
65
|
+
index: Dict[str, Coord] = {}
|
|
66
|
+
if not isinstance(nodes_geojson, dict):
|
|
67
|
+
return index
|
|
68
|
+
features = nodes_geojson.get("features") or []
|
|
69
|
+
if not isinstance(features, list):
|
|
70
|
+
return index
|
|
71
|
+
for feature in features:
|
|
72
|
+
if not isinstance(feature, dict):
|
|
73
|
+
continue
|
|
74
|
+
props = feature.get("properties") or {}
|
|
75
|
+
node_id = props.get("_id") if isinstance(props, dict) else None
|
|
76
|
+
if not isinstance(node_id, str) or not node_id:
|
|
77
|
+
continue
|
|
78
|
+
geom = feature.get("geometry") or {}
|
|
79
|
+
if not isinstance(geom, dict) or geom.get("type") != "Point":
|
|
80
|
+
continue
|
|
81
|
+
coord = _coord_key(geom.get("coordinates"))
|
|
82
|
+
if coord is None:
|
|
83
|
+
continue
|
|
84
|
+
# First write wins - duplicate id detection is reported elsewhere.
|
|
85
|
+
index.setdefault(node_id, coord)
|
|
86
|
+
return index
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
# ---------------------------------------------------------------------------
|
|
90
|
+
# Edge validation
|
|
91
|
+
# ---------------------------------------------------------------------------
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def validate_edge_node_mapping(
|
|
95
|
+
edges_geojson: Optional[Dict[str, Any]],
|
|
96
|
+
node_coords: Dict[str, Coord],
|
|
97
|
+
edges_filename: str = "edges",
|
|
98
|
+
nodes_present: bool = True,
|
|
99
|
+
) -> List[Dict[str, Any]]:
|
|
100
|
+
"""Validate ``_u_id`` and ``_v_id`` references on edges.
|
|
101
|
+
|
|
102
|
+
Reports issues for:
|
|
103
|
+
* Missing reference values
|
|
104
|
+
* References whose target node id does not exist in nodes
|
|
105
|
+
* References whose target node coordinate does not match the matching
|
|
106
|
+
endpoint of the edge ``LineString``
|
|
107
|
+
|
|
108
|
+
When ``nodes_present`` is False (no nodes file in dataset) coordinate
|
|
109
|
+
matching is skipped because the targets are unknown.
|
|
110
|
+
"""
|
|
111
|
+
issues: List[Dict[str, Any]] = []
|
|
112
|
+
if not isinstance(edges_geojson, dict):
|
|
113
|
+
return issues
|
|
114
|
+
features = edges_geojson.get("features") or []
|
|
115
|
+
if not isinstance(features, list):
|
|
116
|
+
return issues
|
|
117
|
+
|
|
118
|
+
for idx, feature in enumerate(features):
|
|
119
|
+
if not isinstance(feature, dict):
|
|
120
|
+
continue
|
|
121
|
+
props = feature.get("properties") or {}
|
|
122
|
+
if not isinstance(props, dict):
|
|
123
|
+
props = {}
|
|
124
|
+
feature_id = props.get("_id") if isinstance(props.get("_id"), str) else None
|
|
125
|
+
geom = feature.get("geometry") or {}
|
|
126
|
+
coords = geom.get("coordinates") if isinstance(geom, dict) else None
|
|
127
|
+
is_linestring = (
|
|
128
|
+
isinstance(geom, dict)
|
|
129
|
+
and geom.get("type") == "LineString"
|
|
130
|
+
and isinstance(coords, list)
|
|
131
|
+
and len(coords) >= 2
|
|
132
|
+
)
|
|
133
|
+
u_endpoint = _coord_key(coords[0]) if is_linestring else None
|
|
134
|
+
v_endpoint = _coord_key(coords[-1]) if is_linestring else None
|
|
135
|
+
|
|
136
|
+
for ref_field, endpoint, endpoint_label in (
|
|
137
|
+
("_u_id", u_endpoint, "start"),
|
|
138
|
+
("_v_id", v_endpoint, "end"),
|
|
139
|
+
):
|
|
140
|
+
ref_val = props.get(ref_field)
|
|
141
|
+
if ref_val is None or (isinstance(ref_val, str) and not ref_val.strip()):
|
|
142
|
+
issues.append(_make_issue(
|
|
143
|
+
edges_filename, idx, feature_id,
|
|
144
|
+
f"Edge is missing required '{ref_field}' reference.",
|
|
145
|
+
))
|
|
146
|
+
continue
|
|
147
|
+
if not isinstance(ref_val, str):
|
|
148
|
+
# Schema validation already complains about non-string ids; skip
|
|
149
|
+
# cross-file checks for these.
|
|
150
|
+
continue
|
|
151
|
+
|
|
152
|
+
if not nodes_present:
|
|
153
|
+
# Only the existence check is meaningful, and we have no node set.
|
|
154
|
+
continue
|
|
155
|
+
|
|
156
|
+
target = node_coords.get(ref_val)
|
|
157
|
+
if target is None:
|
|
158
|
+
issues.append(_make_issue(
|
|
159
|
+
edges_filename, idx, feature_id,
|
|
160
|
+
f"Edge {ref_field}='{ref_val}' does not reference any node in nodes.geojson.",
|
|
161
|
+
))
|
|
162
|
+
continue
|
|
163
|
+
|
|
164
|
+
if endpoint is None:
|
|
165
|
+
# Geometry was malformed; schema validation reports that. Skip
|
|
166
|
+
# coordinate mismatch reporting to avoid noise.
|
|
167
|
+
continue
|
|
168
|
+
|
|
169
|
+
if target != endpoint:
|
|
170
|
+
issues.append(_make_issue(
|
|
171
|
+
edges_filename, idx, feature_id,
|
|
172
|
+
(f"Edge {ref_field}='{ref_val}' coordinate mismatch: "
|
|
173
|
+
f"node is at {_format_coord(target)} but edge {endpoint_label} "
|
|
174
|
+
f"point is at {_format_coord(endpoint)}."),
|
|
175
|
+
))
|
|
176
|
+
return issues
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
# ---------------------------------------------------------------------------
|
|
180
|
+
# Zone validation
|
|
181
|
+
# ---------------------------------------------------------------------------
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _polygon_outer_ring(geom: Any) -> Optional[List[Sequence[Any]]]:
|
|
185
|
+
"""Return the outer ring coordinate list for a Polygon, else None."""
|
|
186
|
+
if not isinstance(geom, dict):
|
|
187
|
+
return None
|
|
188
|
+
if geom.get("type") != "Polygon":
|
|
189
|
+
return None
|
|
190
|
+
coords = geom.get("coordinates")
|
|
191
|
+
if not isinstance(coords, list) or not coords:
|
|
192
|
+
return None
|
|
193
|
+
ring = coords[0]
|
|
194
|
+
if not isinstance(ring, list) or len(ring) < 3:
|
|
195
|
+
return None
|
|
196
|
+
return ring
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def validate_zone_node_mapping(
|
|
200
|
+
zones_geojson: Optional[Dict[str, Any]],
|
|
201
|
+
node_coords: Dict[str, Coord],
|
|
202
|
+
zones_filename: str = "zones",
|
|
203
|
+
nodes_present: bool = True,
|
|
204
|
+
) -> List[Dict[str, Any]]:
|
|
205
|
+
"""Validate ``_w_id`` references on zones.
|
|
206
|
+
|
|
207
|
+
Each zone feature must have a ``_w_id`` array whose entries:
|
|
208
|
+
1. Reference real node ids
|
|
209
|
+
2. Map to coordinates that match the polygon's outer-ring vertices
|
|
210
|
+
in the same order. The ring may include a closing vertex
|
|
211
|
+
(last == first); when present the closing vertex is ignored
|
|
212
|
+
when comparing lengths.
|
|
213
|
+
"""
|
|
214
|
+
issues: List[Dict[str, Any]] = []
|
|
215
|
+
if not isinstance(zones_geojson, dict):
|
|
216
|
+
return issues
|
|
217
|
+
features = zones_geojson.get("features") or []
|
|
218
|
+
if not isinstance(features, list):
|
|
219
|
+
return issues
|
|
220
|
+
|
|
221
|
+
for idx, feature in enumerate(features):
|
|
222
|
+
if not isinstance(feature, dict):
|
|
223
|
+
continue
|
|
224
|
+
props = feature.get("properties") or {}
|
|
225
|
+
if not isinstance(props, dict):
|
|
226
|
+
props = {}
|
|
227
|
+
feature_id = props.get("_id") if isinstance(props.get("_id"), str) else None
|
|
228
|
+
w_ids = props.get("_w_id")
|
|
229
|
+
if w_ids is None:
|
|
230
|
+
issues.append(_make_issue(
|
|
231
|
+
zones_filename, idx, feature_id,
|
|
232
|
+
"Zone is missing required '_w_id' reference list.",
|
|
233
|
+
))
|
|
234
|
+
continue
|
|
235
|
+
if not isinstance(w_ids, (list, tuple)):
|
|
236
|
+
issues.append(_make_issue(
|
|
237
|
+
zones_filename, idx, feature_id,
|
|
238
|
+
"Zone '_w_id' must be an array of node identifiers.",
|
|
239
|
+
))
|
|
240
|
+
continue
|
|
241
|
+
if not w_ids:
|
|
242
|
+
issues.append(_make_issue(
|
|
243
|
+
zones_filename, idx, feature_id,
|
|
244
|
+
"Zone '_w_id' array is empty; expected node references for the polygon ring.",
|
|
245
|
+
))
|
|
246
|
+
continue
|
|
247
|
+
|
|
248
|
+
# Existence check
|
|
249
|
+
missing_refs = [w for w in w_ids if not (isinstance(w, str) and w in node_coords)]
|
|
250
|
+
if nodes_present and missing_refs:
|
|
251
|
+
preview = ", ".join(map(str, missing_refs[:5]))
|
|
252
|
+
more = f" (+{len(missing_refs) - 5} more)" if len(missing_refs) > 5 else ""
|
|
253
|
+
issues.append(_make_issue(
|
|
254
|
+
zones_filename, idx, feature_id,
|
|
255
|
+
f"Zone '_w_id' references unknown node id(s): {preview}{more}.",
|
|
256
|
+
))
|
|
257
|
+
# We continue to coordinate check on a best-effort basis below
|
|
258
|
+
# only if all references resolve; otherwise it's noisy.
|
|
259
|
+
continue
|
|
260
|
+
|
|
261
|
+
ring = _polygon_outer_ring(feature.get("geometry"))
|
|
262
|
+
if ring is None:
|
|
263
|
+
# Schema/geometry validation already reports malformed polygons.
|
|
264
|
+
continue
|
|
265
|
+
if not nodes_present:
|
|
266
|
+
continue
|
|
267
|
+
|
|
268
|
+
ring_coords = [_coord_key(c) for c in ring]
|
|
269
|
+
is_closed = (
|
|
270
|
+
len(ring_coords) >= 2
|
|
271
|
+
and ring_coords[0] is not None
|
|
272
|
+
and ring_coords[0] == ring_coords[-1]
|
|
273
|
+
)
|
|
274
|
+
# Two conventions are accepted for closed rings:
|
|
275
|
+
# * `_w_id` contains an entry for every ring vertex, *including* the
|
|
276
|
+
# trailing duplicate that closes the polygon.
|
|
277
|
+
# * `_w_id` contains an entry only for each unique ring vertex (no
|
|
278
|
+
# trailing duplicate).
|
|
279
|
+
# For open rings only the first convention is valid.
|
|
280
|
+
if is_closed and len(w_ids) == len(ring_coords) - 1:
|
|
281
|
+
comparable_ring = ring_coords[:-1]
|
|
282
|
+
else:
|
|
283
|
+
comparable_ring = ring_coords
|
|
284
|
+
|
|
285
|
+
if len(comparable_ring) != len(w_ids):
|
|
286
|
+
issues.append(_make_issue(
|
|
287
|
+
zones_filename, idx, feature_id,
|
|
288
|
+
(f"Zone '_w_id' has {len(w_ids)} entries but polygon ring has "
|
|
289
|
+
f"{len(comparable_ring)} vertices; they must align."),
|
|
290
|
+
))
|
|
291
|
+
continue
|
|
292
|
+
|
|
293
|
+
mismatches: List[str] = []
|
|
294
|
+
for pos, (wid, ring_pt) in enumerate(zip(w_ids, comparable_ring)):
|
|
295
|
+
if not isinstance(wid, str):
|
|
296
|
+
mismatches.append(
|
|
297
|
+
f"position {pos}: '_w_id' entry is not a string"
|
|
298
|
+
)
|
|
299
|
+
continue
|
|
300
|
+
node_pt = node_coords.get(wid)
|
|
301
|
+
if node_pt is None or ring_pt is None or node_pt != ring_pt:
|
|
302
|
+
mismatches.append(
|
|
303
|
+
f"position {pos}: '_w_id'='{wid}' at node {_format_coord(node_pt)} "
|
|
304
|
+
f"vs ring vertex {_format_coord(ring_pt)}"
|
|
305
|
+
)
|
|
306
|
+
if mismatches:
|
|
307
|
+
preview = "; ".join(mismatches[:3])
|
|
308
|
+
more = f"; and {len(mismatches) - 3} more" if len(mismatches) > 3 else ""
|
|
309
|
+
issues.append(_make_issue(
|
|
310
|
+
zones_filename, idx, feature_id,
|
|
311
|
+
f"Zone polygon ring does not match '_w_id' node coordinates: {preview}{more}.",
|
|
312
|
+
))
|
|
313
|
+
return issues
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
# ---------------------------------------------------------------------------
|
|
317
|
+
# Issue construction
|
|
318
|
+
# ---------------------------------------------------------------------------
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def _make_issue(
|
|
322
|
+
filename: str,
|
|
323
|
+
feature_index: Optional[int],
|
|
324
|
+
feature_id: Optional[str],
|
|
325
|
+
message: str,
|
|
326
|
+
) -> Dict[str, Any]:
|
|
327
|
+
return {
|
|
328
|
+
"filename": filename,
|
|
329
|
+
"feature_index": feature_index,
|
|
330
|
+
"feature_id": feature_id,
|
|
331
|
+
"error_message": [message],
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
# ---------------------------------------------------------------------------
|
|
336
|
+
# Public entry point
|
|
337
|
+
# ---------------------------------------------------------------------------
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def run_geometry_mapping_validation(
|
|
341
|
+
nodes_geojson: Optional[Dict[str, Any]],
|
|
342
|
+
edges_geojson: Optional[Dict[str, Any]],
|
|
343
|
+
zones_geojson: Optional[Dict[str, Any]],
|
|
344
|
+
filenames: Optional[Dict[str, str]] = None,
|
|
345
|
+
) -> List[Dict[str, Any]]:
|
|
346
|
+
"""Run all geometry mapping validations and return aggregated issues.
|
|
347
|
+
|
|
348
|
+
``filenames`` maps the dataset key (``edges``, ``zones``, ``nodes``)
|
|
349
|
+
to the filename used in error messages so that downstream tooling sees
|
|
350
|
+
the actual file rather than a generic dataset key.
|
|
351
|
+
"""
|
|
352
|
+
fn = filenames or {}
|
|
353
|
+
edges_name = fn.get("edges", "edges")
|
|
354
|
+
zones_name = fn.get("zones", "zones")
|
|
355
|
+
|
|
356
|
+
nodes_present = isinstance(nodes_geojson, dict) and bool(nodes_geojson.get("features"))
|
|
357
|
+
node_coords = build_node_coord_index(nodes_geojson) if nodes_present else {}
|
|
358
|
+
|
|
359
|
+
issues: List[Dict[str, Any]] = []
|
|
360
|
+
issues.extend(validate_edge_node_mapping(
|
|
361
|
+
edges_geojson, node_coords, edges_name, nodes_present
|
|
362
|
+
))
|
|
363
|
+
issues.extend(validate_zone_node_mapping(
|
|
364
|
+
zones_geojson, node_coords, zones_name, nodes_present
|
|
365
|
+
))
|
|
366
|
+
return issues
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
__all__ = [
|
|
370
|
+
"build_node_coord_index",
|
|
371
|
+
"run_geometry_mapping_validation",
|
|
372
|
+
"validate_edge_node_mapping",
|
|
373
|
+
"validate_zone_node_mapping",
|
|
374
|
+
]
|
python_osw_validation/helpers.py
CHANGED
|
@@ -1,6 +1,30 @@
|
|
|
1
1
|
from typing import Optional
|
|
2
|
+
import json
|
|
2
3
|
import re
|
|
3
4
|
|
|
5
|
+
import geopandas as gpd
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _read_geojson_without_ext(file_path: str) -> gpd.GeoDataFrame:
|
|
9
|
+
"""Load a GeoJSON file into a GeoDataFrame with ext:* properties removed.
|
|
10
|
+
|
|
11
|
+
Why: pyogrio/GDAL infers a single dtype per property column when reading
|
|
12
|
+
GeoJSON. Extension tags (ext:*) are free-form by spec and may legitimately
|
|
13
|
+
mix numbers and strings across features, which breaks that inference and
|
|
14
|
+
surfaces as a confusing JSON parse error. Schema validation has already
|
|
15
|
+
accepted these properties; the GeoDataFrame is only used for geometry and
|
|
16
|
+
_id-based integrity checks, so dropping ext:* here is safe.
|
|
17
|
+
"""
|
|
18
|
+
with open(file_path, 'r') as f:
|
|
19
|
+
data = json.load(f)
|
|
20
|
+
for feature in data.get('features', []):
|
|
21
|
+
props = feature.get('properties')
|
|
22
|
+
if isinstance(props, dict):
|
|
23
|
+
for key in [k for k in props if isinstance(k, str) and k.startswith('ext:')]:
|
|
24
|
+
del props[key]
|
|
25
|
+
crs = (data.get('crs') or {}).get('properties', {}).get('name')
|
|
26
|
+
return gpd.GeoDataFrame.from_features(data.get('features', []), crs=crs)
|
|
27
|
+
|
|
4
28
|
_ADDITIONAL_PROPERTIES_RE = re.compile(
|
|
5
29
|
r"Additional properties are not allowed \('(?P<tag>[^']+)' was unexpected\)"
|
|
6
30
|
)
|
python_osw_validation/version.py
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
__version__ = '0.
|
|
1
|
+
__version__ = '0.4.1'
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: python_osw_validation
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.1
|
|
4
4
|
Summary: Python library for OSW validation
|
|
5
5
|
Home-page: https://github.com/TaskarCenterAtUW/TDEI-python-lib-osw-validation
|
|
6
6
|
Author: Sujata Misra
|
|
@@ -31,6 +31,10 @@ Dynamic: summary
|
|
|
31
31
|
|
|
32
32
|
# TDEI python lib OSW validation package
|
|
33
33
|
|
|
34
|
+
[](https://pypi.org/project/python-osw-validation/)
|
|
35
|
+
[](https://github.com/TaskarCenterAtUW/TDEI-python-lib-osw-validation/actions/workflows/unit_tests.yml)
|
|
36
|
+
[](#)
|
|
37
|
+
|
|
34
38
|
This package validates OSW GeoJSON datasets packaged as a ZIP file.
|
|
35
39
|
|
|
36
40
|
## System requirements
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
python_osw_validation/__init__.py,sha256=
|
|
1
|
+
python_osw_validation/__init__.py,sha256=jmTokejVzcwWwuQRgwIjCEH9KDhkJqp1a-e4ubVgOOU,33301
|
|
2
2
|
python_osw_validation/extracted_data_validator.py,sha256=gEGYLaM_QkK6NrrhVYmNx-jMaNHXC4PbDGf1zKwJre4,6605
|
|
3
|
-
python_osw_validation/
|
|
4
|
-
python_osw_validation/
|
|
3
|
+
python_osw_validation/geometry_mapping_validator.py,sha256=KscmfgSwTiXbf8IPx-RXuTIXPYY4PHDwvBeb2WmhpVA,14137
|
|
4
|
+
python_osw_validation/helpers.py,sha256=iLVJZS1-AaLsbP0ngHZLW208dKSnM2k52JFal4Nuxcg,9203
|
|
5
|
+
python_osw_validation/version.py,sha256=qBs4HqYsPn6yUHWEuCN4rGUC05gABbl800d8LBd8h9w,22
|
|
5
6
|
python_osw_validation/zipfile_handler.py,sha256=jXnP-8O5AAOBapuNF3-XdFVM1MHiPaWpl_wlbX-aqhY,2631
|
|
6
7
|
python_osw_validation/schema/opensidewalks.edges.schema-0.3.json,sha256=Egp--i6ahiUDKY55g_fuv71HkVPtnQN5OW8L_okRa8o,79638
|
|
7
8
|
python_osw_validation/schema/opensidewalks.lines.schema-0.3.json,sha256=3s-VXiMPv0_wv3yU2iGw8iKjE3Ec1w6QKkUsQURp2II,9470
|
|
@@ -10,8 +11,8 @@ python_osw_validation/schema/opensidewalks.points.schema-0.3.json,sha256=WYmlC4Q
|
|
|
10
11
|
python_osw_validation/schema/opensidewalks.polygons.schema-0.3.json,sha256=VzDpHv1ZVT42cAk9n3gsFZjS7WcflQzSbjN-aNIVTYM,16286
|
|
11
12
|
python_osw_validation/schema/opensidewalks.schema-0.3.json,sha256=vyyGzPpqLxr1e5wFfNKzlA1sr6tmhHKM7ntaTk8z5k8,278489
|
|
12
13
|
python_osw_validation/schema/opensidewalks.zones.schema-0.3.json,sha256=JCqoCJj-dCuPVPHWSUQhRJMebaJ9IrzHWwTVAC6j7dY,11281
|
|
13
|
-
python_osw_validation-0.
|
|
14
|
-
python_osw_validation-0.
|
|
15
|
-
python_osw_validation-0.
|
|
16
|
-
python_osw_validation-0.
|
|
17
|
-
python_osw_validation-0.
|
|
14
|
+
python_osw_validation-0.4.1.dist-info/licenses/LICENSE,sha256=2bm9uFabQZ3Ykb_SaSU_uUbAj2-htc6WJQmS_65qD00,1073
|
|
15
|
+
python_osw_validation-0.4.1.dist-info/METADATA,sha256=NytFX-HWBMVtDbxB8PD_Ba4eHr2AoEUaIA2K19vxlR8,6502
|
|
16
|
+
python_osw_validation-0.4.1.dist-info/WHEEL,sha256=SmOxYU7pzNKBqASvQJ7DjX3XGUF92lrGhMb3R6_iiqI,91
|
|
17
|
+
python_osw_validation-0.4.1.dist-info/top_level.txt,sha256=GE81UPcDHEffJCxYu3M_iPz3Dt-O3axB73R5SLm_Veo,22
|
|
18
|
+
python_osw_validation-0.4.1.dist-info/RECORD,,
|
|
File without changes
|
{python_osw_validation-0.3.7.dist-info → python_osw_validation-0.4.1.dist-info}/licenses/LICENSE
RENAMED
|
File without changes
|
{python_osw_validation-0.3.7.dist-info → python_osw_validation-0.4.1.dist-info}/top_level.txt
RENAMED
|
File without changes
|