python-osw-validation 0.3.6__py3-none-any.whl → 0.4.0__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 +244 -32
- python_osw_validation/geometry_mapping_validator.py +374 -0
- python_osw_validation/helpers.py +133 -6
- python_osw_validation/version.py +1 -1
- {python_osw_validation-0.3.6.dist-info → python_osw_validation-0.4.0.dist-info}/METADATA +14 -2
- {python_osw_validation-0.3.6.dist-info → python_osw_validation-0.4.0.dist-info}/RECORD +9 -8
- {python_osw_validation-0.3.6.dist-info → python_osw_validation-0.4.0.dist-info}/WHEEL +0 -0
- {python_osw_validation-0.3.6.dist-info → python_osw_validation-0.4.0.dist-info}/licenses/LICENSE +0 -0
- {python_osw_validation-0.3.6.dist-info → python_osw_validation-0.4.0.dist-info}/top_level.txt +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import os
|
|
2
2
|
import gc
|
|
3
3
|
import json
|
|
4
|
-
import
|
|
4
|
+
import math
|
|
5
5
|
from typing import Dict, Any, Optional, List, Tuple
|
|
6
6
|
import geopandas as gpd
|
|
7
7
|
import jsonschema_rs
|
|
@@ -11,9 +11,9 @@ from .extracted_data_validator import ExtractedDataValidator, OSW_DATASET_FILES
|
|
|
11
11
|
from .version import __version__
|
|
12
12
|
from .helpers import (
|
|
13
13
|
_add_additional_properties_hint,
|
|
14
|
+
_err_kind,
|
|
14
15
|
_feature_index_from_error,
|
|
15
16
|
_pretty_message,
|
|
16
|
-
_rank_for,
|
|
17
17
|
)
|
|
18
18
|
|
|
19
19
|
SCHEMA_PATH = os.path.join(os.path.dirname(__file__), 'schema')
|
|
@@ -111,6 +111,156 @@ class OSWValidation:
|
|
|
111
111
|
self.log_errors(f"Could not create set for column '{col}' in {filekey}.", filekey, None)
|
|
112
112
|
return set()
|
|
113
113
|
|
|
114
|
+
# ----------------------------
|
|
115
|
+
# Geometry mapping helpers
|
|
116
|
+
# ----------------------------
|
|
117
|
+
|
|
118
|
+
_COORD_TOLERANCE = 1e-7 # ~1 cm at equator
|
|
119
|
+
|
|
120
|
+
def _coords_match(self, c1: tuple, c2: tuple) -> bool:
|
|
121
|
+
return abs(c1[0] - c2[0]) <= self._COORD_TOLERANCE and abs(c1[1] - c2[1]) <= self._COORD_TOLERANCE
|
|
122
|
+
|
|
123
|
+
def _build_node_coord_map(self, nodes_df: gpd.GeoDataFrame) -> Dict[Any, tuple]:
|
|
124
|
+
"""Return {node_id: (lon, lat)} from a nodes GeoDataFrame."""
|
|
125
|
+
coord_map: Dict[Any, tuple] = {}
|
|
126
|
+
for _, row in nodes_df.iterrows():
|
|
127
|
+
try:
|
|
128
|
+
nid = row['_id']
|
|
129
|
+
except KeyError:
|
|
130
|
+
continue
|
|
131
|
+
geom = row.geometry
|
|
132
|
+
if nid is not None and geom is not None and geom.geom_type == 'Point':
|
|
133
|
+
coord_map[nid] = (geom.x, geom.y)
|
|
134
|
+
return coord_map
|
|
135
|
+
|
|
136
|
+
def _validate_edge_geometry_mapping(
|
|
137
|
+
self,
|
|
138
|
+
edges_df: Optional[gpd.GeoDataFrame],
|
|
139
|
+
node_coord_map: Dict[Any, tuple],
|
|
140
|
+
max_errors: int,
|
|
141
|
+
) -> None:
|
|
142
|
+
"""Verify edge start/end coordinates match their _u_id/_v_id node geometries."""
|
|
143
|
+
if edges_df is None or not node_coord_map:
|
|
144
|
+
return
|
|
145
|
+
|
|
146
|
+
has_u_id = '_u_id' in edges_df.columns
|
|
147
|
+
has_v_id = '_v_id' in edges_df.columns
|
|
148
|
+
if not (has_u_id or has_v_id):
|
|
149
|
+
return
|
|
150
|
+
|
|
151
|
+
for feat_idx, row in edges_df.iterrows():
|
|
152
|
+
if len(self.errors) >= max_errors:
|
|
153
|
+
break
|
|
154
|
+
|
|
155
|
+
geom = row.geometry
|
|
156
|
+
if geom is None or geom.geom_type != 'LineString':
|
|
157
|
+
continue
|
|
158
|
+
|
|
159
|
+
coords = list(geom.coords)
|
|
160
|
+
if not coords:
|
|
161
|
+
continue
|
|
162
|
+
|
|
163
|
+
try:
|
|
164
|
+
edge_id = row['_id']
|
|
165
|
+
except KeyError:
|
|
166
|
+
edge_id = feat_idx
|
|
167
|
+
|
|
168
|
+
if has_u_id:
|
|
169
|
+
try:
|
|
170
|
+
u_id = row['_u_id']
|
|
171
|
+
except KeyError:
|
|
172
|
+
u_id = None
|
|
173
|
+
if u_id is not None and u_id in node_coord_map:
|
|
174
|
+
node_coord = node_coord_map[u_id]
|
|
175
|
+
edge_start = (coords[0][0], coords[0][1])
|
|
176
|
+
if not self._coords_match(edge_start, node_coord):
|
|
177
|
+
self.log_errors(
|
|
178
|
+
message=(
|
|
179
|
+
f"edges id '{edge_id}' : "
|
|
180
|
+
f"start coordinate {edge_start} does not match "
|
|
181
|
+
f"node id '{u_id}' coordinate {node_coord} (_u_id mismatch)."
|
|
182
|
+
),
|
|
183
|
+
filename='edges',
|
|
184
|
+
feature_index=feat_idx,
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
if len(self.errors) >= max_errors:
|
|
188
|
+
break
|
|
189
|
+
|
|
190
|
+
if has_v_id:
|
|
191
|
+
try:
|
|
192
|
+
v_id = row['_v_id']
|
|
193
|
+
except KeyError:
|
|
194
|
+
v_id = None
|
|
195
|
+
if v_id is not None and v_id in node_coord_map:
|
|
196
|
+
node_coord = node_coord_map[v_id]
|
|
197
|
+
edge_end = (coords[-1][0], coords[-1][1])
|
|
198
|
+
if not self._coords_match(edge_end, node_coord):
|
|
199
|
+
self.log_errors(
|
|
200
|
+
message=(
|
|
201
|
+
f"edges id '{edge_id}' : "
|
|
202
|
+
f"end coordinate {edge_end} does not match "
|
|
203
|
+
f"node id '{v_id}' coordinate {node_coord} (_v_id mismatch)."
|
|
204
|
+
),
|
|
205
|
+
filename='edges',
|
|
206
|
+
feature_index=feat_idx,
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
def _validate_zone_geometry_mapping(
|
|
210
|
+
self,
|
|
211
|
+
zones_df: Optional[gpd.GeoDataFrame],
|
|
212
|
+
node_coord_map: Dict[Any, tuple],
|
|
213
|
+
max_errors: int,
|
|
214
|
+
) -> None:
|
|
215
|
+
"""Verify each _w_id node coordinate is a vertex of the zone's polygon exterior ring."""
|
|
216
|
+
if zones_df is None or not node_coord_map:
|
|
217
|
+
return
|
|
218
|
+
|
|
219
|
+
if '_w_id' not in zones_df.columns:
|
|
220
|
+
return
|
|
221
|
+
|
|
222
|
+
for feat_idx, row in zones_df.iterrows():
|
|
223
|
+
if len(self.errors) >= max_errors:
|
|
224
|
+
break
|
|
225
|
+
|
|
226
|
+
geom = row.geometry
|
|
227
|
+
if geom is None or geom.geom_type != 'Polygon':
|
|
228
|
+
continue
|
|
229
|
+
|
|
230
|
+
try:
|
|
231
|
+
zone_id = row['_id']
|
|
232
|
+
except KeyError:
|
|
233
|
+
zone_id = feat_idx
|
|
234
|
+
|
|
235
|
+
ring_coords = {(c[0], c[1]) for c in geom.exterior.coords}
|
|
236
|
+
|
|
237
|
+
try:
|
|
238
|
+
w_ids = row['_w_id']
|
|
239
|
+
except KeyError:
|
|
240
|
+
continue
|
|
241
|
+
|
|
242
|
+
if w_ids is None:
|
|
243
|
+
continue
|
|
244
|
+
if not isinstance(w_ids, (list, tuple)):
|
|
245
|
+
w_ids = [w_ids]
|
|
246
|
+
|
|
247
|
+
for w_id in w_ids:
|
|
248
|
+
if len(self.errors) >= max_errors:
|
|
249
|
+
break
|
|
250
|
+
if w_id is None or w_id not in node_coord_map:
|
|
251
|
+
continue
|
|
252
|
+
node_coord = node_coord_map[w_id]
|
|
253
|
+
if not any(self._coords_match(node_coord, rc) for rc in ring_coords):
|
|
254
|
+
self.log_errors(
|
|
255
|
+
message=(
|
|
256
|
+
f"zones id '{zone_id}' : "
|
|
257
|
+
f"node id '{w_id}' coordinate {node_coord} is not a vertex "
|
|
258
|
+
f"of the zone polygon geometry (_w_id coordinate mismatch)."
|
|
259
|
+
),
|
|
260
|
+
filename='zones',
|
|
261
|
+
feature_index=feat_idx,
|
|
262
|
+
)
|
|
263
|
+
|
|
114
264
|
def _schema_key_from_text(self, text: Optional[str]) -> Optional[str]:
|
|
115
265
|
"""Return dataset key from exact filename suffixes only."""
|
|
116
266
|
if not text:
|
|
@@ -129,6 +279,29 @@ class OSWValidation:
|
|
|
129
279
|
|
|
130
280
|
return None
|
|
131
281
|
|
|
282
|
+
def _is_nullish_value(self, value: Any) -> bool:
|
|
283
|
+
if value is None:
|
|
284
|
+
return True
|
|
285
|
+
if isinstance(value, str) and value.strip().lower() in {"null", "nan"}:
|
|
286
|
+
return True
|
|
287
|
+
return isinstance(value, float) and math.isnan(value)
|
|
288
|
+
|
|
289
|
+
def _collect_nullish_property_paths(self, obj: Any, prefix: str = "") -> List[Tuple[str, Any]]:
|
|
290
|
+
paths: List[Tuple[str, Any]] = []
|
|
291
|
+
if isinstance(obj, dict):
|
|
292
|
+
for key, value in obj.items():
|
|
293
|
+
next_prefix = f"{prefix}.{key}" if prefix else str(key)
|
|
294
|
+
paths.extend(self._collect_nullish_property_paths(value, next_prefix))
|
|
295
|
+
return paths
|
|
296
|
+
if isinstance(obj, list):
|
|
297
|
+
for idx, value in enumerate(obj):
|
|
298
|
+
next_prefix = f"{prefix}[{idx}]" if prefix else f"[{idx}]"
|
|
299
|
+
paths.extend(self._collect_nullish_property_paths(value, next_prefix))
|
|
300
|
+
return paths
|
|
301
|
+
if self._is_nullish_value(obj):
|
|
302
|
+
paths.append((prefix or "value", obj))
|
|
303
|
+
return paths
|
|
304
|
+
|
|
132
305
|
def _contains_disallowed_features_for_02(self, geojson_data: Dict[str, Any]) -> set:
|
|
133
306
|
"""Detect Tree coverage or Custom content in legacy 0.2 datasets.
|
|
134
307
|
|
|
@@ -197,6 +370,12 @@ class OSWValidation:
|
|
|
197
370
|
# Core validation entrypoint
|
|
198
371
|
# ----------------------------
|
|
199
372
|
def validate(self, max_errors=20) -> ValidationResult:
|
|
373
|
+
def _finalize(is_valid: bool, errors: Optional[List[str]] = None) -> ValidationResult:
|
|
374
|
+
final_errors = self.errors if errors is None else errors
|
|
375
|
+
final_errors = (final_errors or [])[:max_errors]
|
|
376
|
+
final_issues = (self.issues or [])[:max_errors]
|
|
377
|
+
return ValidationResult(is_valid, final_errors, final_issues)
|
|
378
|
+
|
|
200
379
|
zip_handler = None
|
|
201
380
|
OSW_DATASET: Dict[str, Optional[gpd.GeoDataFrame]] = {}
|
|
202
381
|
validator = None
|
|
@@ -211,7 +390,7 @@ class OSWValidation:
|
|
|
211
390
|
filename=self.zipfile_path,
|
|
212
391
|
feature_index=None
|
|
213
392
|
)
|
|
214
|
-
return
|
|
393
|
+
return _finalize(False)
|
|
215
394
|
|
|
216
395
|
# Validate the folder structure
|
|
217
396
|
validator = ExtractedDataValidator(self.extracted_dir)
|
|
@@ -222,7 +401,7 @@ class OSWValidation:
|
|
|
222
401
|
filename=upload_name,
|
|
223
402
|
feature_index=None
|
|
224
403
|
)
|
|
225
|
-
return
|
|
404
|
+
return _finalize(False)
|
|
226
405
|
|
|
227
406
|
# Per-file schema validation → populate self.issues (fixme-like)
|
|
228
407
|
for file in validator.files:
|
|
@@ -232,7 +411,7 @@ class OSWValidation:
|
|
|
232
411
|
break
|
|
233
412
|
|
|
234
413
|
if self.errors:
|
|
235
|
-
return
|
|
414
|
+
return _finalize(False)
|
|
236
415
|
|
|
237
416
|
# Load GeoDataFrames for integrity checks
|
|
238
417
|
for file in validator.files:
|
|
@@ -340,6 +519,13 @@ class OSWValidation:
|
|
|
340
519
|
feature_index=None
|
|
341
520
|
)
|
|
342
521
|
|
|
522
|
+
# Geometry mapping: coordinate consistency using already-loaded GeoDataFrames
|
|
523
|
+
if nodes_df is not None and len(self.errors) < max_errors:
|
|
524
|
+
node_coord_map = self._build_node_coord_map(nodes_df)
|
|
525
|
+
if node_coord_map:
|
|
526
|
+
self._validate_edge_geometry_mapping(edges_df, node_coord_map, max_errors)
|
|
527
|
+
self._validate_zone_geometry_mapping(zones_df, node_coord_map, max_errors)
|
|
528
|
+
|
|
343
529
|
# Geometry validation: check geometry type and SFA validity
|
|
344
530
|
for osw_file, gdf in OSW_DATASET.items():
|
|
345
531
|
if gdf is None:
|
|
@@ -414,9 +600,9 @@ class OSWValidation:
|
|
|
414
600
|
break
|
|
415
601
|
|
|
416
602
|
if self.errors:
|
|
417
|
-
return
|
|
603
|
+
return _finalize(False)
|
|
418
604
|
else:
|
|
419
|
-
return
|
|
605
|
+
return _finalize(True, [])
|
|
420
606
|
|
|
421
607
|
except Exception as e:
|
|
422
608
|
self.log_errors(
|
|
@@ -424,8 +610,7 @@ class OSWValidation:
|
|
|
424
610
|
filename=None,
|
|
425
611
|
feature_index=None
|
|
426
612
|
)
|
|
427
|
-
|
|
428
|
-
return ValidationResult(False, self.errors, self.issues)
|
|
613
|
+
return _finalize(False)
|
|
429
614
|
finally:
|
|
430
615
|
# Cleanup extracted files
|
|
431
616
|
try:
|
|
@@ -488,6 +673,37 @@ class OSWValidation:
|
|
|
488
673
|
except OSError:
|
|
489
674
|
return False
|
|
490
675
|
|
|
676
|
+
filename = os.path.basename(file_path)
|
|
677
|
+
|
|
678
|
+
# Upfront guard: reject null/NaN values in feature properties.
|
|
679
|
+
# This runs before schema validation to surface data quality issues first.
|
|
680
|
+
features = geojson_data.get("features", []) if isinstance(geojson_data, dict) else []
|
|
681
|
+
found_nullish = False
|
|
682
|
+
for idx, feature in enumerate(features):
|
|
683
|
+
if not isinstance(feature, dict):
|
|
684
|
+
continue
|
|
685
|
+
props = feature.get("properties")
|
|
686
|
+
if not isinstance(props, dict):
|
|
687
|
+
continue
|
|
688
|
+
bad_paths = self._collect_nullish_property_paths(props)
|
|
689
|
+
for path, bad_value in bad_paths:
|
|
690
|
+
if len(self.errors) >= max_errors:
|
|
691
|
+
return False
|
|
692
|
+
found_nullish = True
|
|
693
|
+
rendered = f'"{bad_value}"' if isinstance(bad_value, str) else str(bad_value)
|
|
694
|
+
msg = (
|
|
695
|
+
f"Invalid value at '{path}': {rendered}. "
|
|
696
|
+
f"Null/NaN placeholders are not allowed; provide a valid value or remove this property."
|
|
697
|
+
)
|
|
698
|
+
self.errors.append(f"Validation error: {msg}")
|
|
699
|
+
self.issues.append({
|
|
700
|
+
"filename": filename,
|
|
701
|
+
"feature_index": idx,
|
|
702
|
+
"error_message": [msg],
|
|
703
|
+
})
|
|
704
|
+
if found_nullish:
|
|
705
|
+
return False
|
|
706
|
+
|
|
491
707
|
schema_url = geojson_data.get('$schema')
|
|
492
708
|
if isinstance(schema_url, str) and '0.2/schema.json' in schema_url:
|
|
493
709
|
reasons = self._contains_disallowed_features_for_02(geojson_data)
|
|
@@ -518,15 +734,9 @@ class OSWValidation:
|
|
|
518
734
|
schema = self.load_osw_schema(schema_path)
|
|
519
735
|
validator = jsonschema_rs.Draft7Validator(schema)
|
|
520
736
|
|
|
521
|
-
filename = os.path.basename(file_path)
|
|
522
|
-
|
|
523
|
-
# Per-feature best error accumulator (streaming)
|
|
524
|
-
# feature_idx -> (rank_tuple, error_obj)
|
|
525
|
-
best_by_feature: Dict[Optional[int], Tuple[tuple, Any]] = {}
|
|
526
|
-
feature_order: List[Optional[int]] = [] # preserve first-seen order
|
|
527
|
-
|
|
528
737
|
# Legacy cap
|
|
529
738
|
legacy_count = 0
|
|
739
|
+
collected_issues: List[Dict[str, Any]] = []
|
|
530
740
|
|
|
531
741
|
# --- STREAM over errors; STOP as soon as legacy hits the cap ---
|
|
532
742
|
for err in validator.iter_errors(geojson_data):
|
|
@@ -539,26 +749,28 @@ class OSWValidation:
|
|
|
539
749
|
# We've reached the legacy cap; stop work to match original performance
|
|
540
750
|
break
|
|
541
751
|
|
|
542
|
-
#
|
|
752
|
+
# Keep every issue (no per-feature collapsing)
|
|
543
753
|
fidx = _feature_index_from_error(err)
|
|
544
|
-
|
|
545
|
-
prev = best_by_feature.get(fidx)
|
|
546
|
-
if prev is None:
|
|
547
|
-
best_by_feature[fidx] = (r, err)
|
|
548
|
-
feature_order.append(fidx)
|
|
549
|
-
else:
|
|
550
|
-
if r < prev[0]:
|
|
551
|
-
best_by_feature[fidx] = (r, err)
|
|
552
|
-
|
|
553
|
-
# Build per-feature issues (one concise message per feature) in first-seen order
|
|
554
|
-
for fidx in feature_order:
|
|
555
|
-
_, best_err = best_by_feature[fidx]
|
|
556
|
-
pretty = _pretty_message(best_err, schema)
|
|
557
|
-
self.issues.append({
|
|
754
|
+
collected_issues.append({
|
|
558
755
|
"filename": filename,
|
|
559
756
|
"feature_index": fidx if fidx is not None else -1,
|
|
560
|
-
"error_message": [
|
|
757
|
+
"error_message": [_pretty_message(err, schema)],
|
|
758
|
+
"_kind": _err_kind(err),
|
|
561
759
|
})
|
|
562
760
|
|
|
761
|
+
# Drop noisy AnyOf summaries when specific field-level errors exist
|
|
762
|
+
# for the same feature.
|
|
763
|
+
has_specific_by_feature: Dict[int, bool] = {}
|
|
764
|
+
for issue in collected_issues:
|
|
765
|
+
fidx = issue["feature_index"]
|
|
766
|
+
if issue.get("_kind") != "AnyOf":
|
|
767
|
+
has_specific_by_feature[fidx] = True
|
|
768
|
+
|
|
769
|
+
for issue in collected_issues:
|
|
770
|
+
if issue.get("_kind") == "AnyOf" and has_specific_by_feature.get(issue["feature_index"], False):
|
|
771
|
+
continue
|
|
772
|
+
issue.pop("_kind", None)
|
|
773
|
+
self.issues.append(issue)
|
|
774
|
+
|
|
563
775
|
# Mirror original boolean behavior: False when we exactly hit the cap
|
|
564
776
|
return len(self.errors) < max_errors
|
|
@@ -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
|
@@ -4,6 +4,8 @@ import re
|
|
|
4
4
|
_ADDITIONAL_PROPERTIES_RE = re.compile(
|
|
5
5
|
r"Additional properties are not allowed \('(?P<tag>[^']+)' was unexpected\)"
|
|
6
6
|
)
|
|
7
|
+
_ENUM_RE = re.compile(r'^(?P<got>.+?) is not one of (?P<allowed>.+)$')
|
|
8
|
+
_TYPE_RE = re.compile(r'^(?P<got>.+?) is not of type (?P<type>.+)$')
|
|
7
9
|
|
|
8
10
|
|
|
9
11
|
def _add_additional_properties_hint(msg: str) -> str:
|
|
@@ -45,6 +47,118 @@ def _clean_enum_message(err) -> str:
|
|
|
45
47
|
msg = re.sub(r"\s*or\s+\d+\s+other candidates", "", msg)
|
|
46
48
|
return msg.split("\n")[0]
|
|
47
49
|
|
|
50
|
+
def _friendly_enum_message(err, schema=None) -> str:
|
|
51
|
+
raw = _clean_enum_message(err)
|
|
52
|
+
match = _ENUM_RE.match(raw)
|
|
53
|
+
if not match:
|
|
54
|
+
return raw
|
|
55
|
+
|
|
56
|
+
path = list(getattr(err, "instance_path", []) or [])
|
|
57
|
+
field = path[-1] if path and isinstance(path[-1], str) else "value"
|
|
58
|
+
got = match.group("got").strip('"')
|
|
59
|
+
allowed = match.group("allowed")
|
|
60
|
+
values = []
|
|
61
|
+
if schema is not None:
|
|
62
|
+
try:
|
|
63
|
+
node = schema
|
|
64
|
+
for seg in list(getattr(err, "schema_path", []) or []):
|
|
65
|
+
node = node[seg]
|
|
66
|
+
if isinstance(node, list):
|
|
67
|
+
values = [str(v) for v in node]
|
|
68
|
+
elif isinstance(node, dict) and isinstance(node.get("enum"), list):
|
|
69
|
+
values = [str(v) for v in node["enum"]]
|
|
70
|
+
except Exception:
|
|
71
|
+
values = []
|
|
72
|
+
if not values:
|
|
73
|
+
values = re.findall(r'"([^"]+)"', allowed)
|
|
74
|
+
if values:
|
|
75
|
+
shown = values[:5]
|
|
76
|
+
allowed_text = "|".join(shown)
|
|
77
|
+
if len(values) > 5:
|
|
78
|
+
allowed_text = f"{allowed_text}| and {len(values) - 5} more"
|
|
79
|
+
else:
|
|
80
|
+
allowed_text = allowed
|
|
81
|
+
return (
|
|
82
|
+
f"Invalid value at '{field}': '{got}'. "
|
|
83
|
+
f"Acceptable values can be one of {allowed_text}, provide a valid value and retry again."
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
def _friendly_type_message(err, schema) -> Optional[str]:
|
|
87
|
+
raw = (getattr(err, "message", "") or "").split("\n")[0]
|
|
88
|
+
if not _TYPE_RE.match(raw):
|
|
89
|
+
return None
|
|
90
|
+
|
|
91
|
+
path = list(getattr(err, "instance_path", []) or [])
|
|
92
|
+
field = path[-1] if path and isinstance(path[-1], str) else "value"
|
|
93
|
+
type_match = _TYPE_RE.match(raw)
|
|
94
|
+
got = type_match.group("got")
|
|
95
|
+
expected_type = type_match.group("type").strip('"')
|
|
96
|
+
|
|
97
|
+
try:
|
|
98
|
+
node = schema
|
|
99
|
+
for seg in list(getattr(err, "schema_path", []) or []):
|
|
100
|
+
node = node[seg]
|
|
101
|
+
|
|
102
|
+
parent = None
|
|
103
|
+
schema_path = list(getattr(err, "schema_path", []) or [])
|
|
104
|
+
if schema_path:
|
|
105
|
+
parent = schema
|
|
106
|
+
for seg in schema_path[:-1]:
|
|
107
|
+
parent = parent[seg]
|
|
108
|
+
|
|
109
|
+
if isinstance(parent, dict) and isinstance(parent.get("enum"), list):
|
|
110
|
+
enum_values = list(parent["enum"])
|
|
111
|
+
shown = enum_values[:5]
|
|
112
|
+
allowed = "|".join(str(v) for v in shown)
|
|
113
|
+
if len(enum_values) > 5:
|
|
114
|
+
allowed = f"{allowed}| and {len(enum_values) - 5} more"
|
|
115
|
+
cleaned_got = got.strip('"')
|
|
116
|
+
return (
|
|
117
|
+
f"Invalid value at '{field}': '{cleaned_got}'. "
|
|
118
|
+
f"Acceptable values can be one of {allowed}, provide a valid value and retry again."
|
|
119
|
+
)
|
|
120
|
+
except Exception:
|
|
121
|
+
pass
|
|
122
|
+
|
|
123
|
+
cleaned_got = got.strip('"')
|
|
124
|
+
return (
|
|
125
|
+
f"Invalid value at '{field}': '{cleaned_got}' . "
|
|
126
|
+
f"Acceptable datatype is {expected_type} ; provide a valid value and retry"
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
def _has_enum_context(err, schema) -> bool:
|
|
130
|
+
"""True when this error is an enum mismatch or type mismatch on an enum-constrained field."""
|
|
131
|
+
if _err_kind(err) == "Enum":
|
|
132
|
+
return True
|
|
133
|
+
if _err_kind(err) != "Type":
|
|
134
|
+
return False
|
|
135
|
+
return _friendly_type_message(err, schema) is not None
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _instance_path_str(err) -> str:
|
|
139
|
+
"""Render jsonschema instance path as a readable JSON path."""
|
|
140
|
+
path = list(getattr(err, "instance_path", []) or [])
|
|
141
|
+
if not path:
|
|
142
|
+
return ""
|
|
143
|
+
|
|
144
|
+
parts = []
|
|
145
|
+
for seg in path:
|
|
146
|
+
if isinstance(seg, int):
|
|
147
|
+
if parts:
|
|
148
|
+
parts[-1] = f"{parts[-1]}[{seg}]"
|
|
149
|
+
else:
|
|
150
|
+
parts.append(f"[{seg}]")
|
|
151
|
+
else:
|
|
152
|
+
parts.append(str(seg))
|
|
153
|
+
return ".".join(parts)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _with_path(err, msg: str) -> str:
|
|
157
|
+
path = _instance_path_str(err)
|
|
158
|
+
if not path:
|
|
159
|
+
return msg
|
|
160
|
+
return f"{msg} (at: {path})"
|
|
161
|
+
|
|
48
162
|
|
|
49
163
|
def _pretty_message(err, schema) -> str:
|
|
50
164
|
"""
|
|
@@ -58,7 +172,12 @@ def _pretty_message(err, schema) -> str:
|
|
|
58
172
|
kind = _err_kind(err)
|
|
59
173
|
|
|
60
174
|
if kind == "Enum":
|
|
61
|
-
return _add_additional_properties_hint(
|
|
175
|
+
return _add_additional_properties_hint(_friendly_enum_message(err, schema))
|
|
176
|
+
|
|
177
|
+
if kind == "Type":
|
|
178
|
+
friendly_type = _friendly_type_message(err, schema)
|
|
179
|
+
if friendly_type:
|
|
180
|
+
return _add_additional_properties_hint(friendly_type)
|
|
62
181
|
|
|
63
182
|
if kind == "AnyOf":
|
|
64
183
|
# Follow schema_path to the anyOf node; union of 'required' keys in branches.
|
|
@@ -85,24 +204,32 @@ def _pretty_message(err, schema) -> str:
|
|
|
85
204
|
|
|
86
205
|
if required:
|
|
87
206
|
props = ", ".join(sorted(required))
|
|
88
|
-
return _add_additional_properties_hint(f"must include one of: {props}")
|
|
207
|
+
return _with_path(err, _add_additional_properties_hint(f"must include one of: {props}"))
|
|
89
208
|
except Exception:
|
|
90
209
|
pass
|
|
91
210
|
|
|
92
211
|
# Default: first line from library message
|
|
212
|
+
friendly_enum = _friendly_enum_message(err, schema)
|
|
213
|
+
if friendly_enum != _clean_enum_message(err):
|
|
214
|
+
return _add_additional_properties_hint(friendly_enum)
|
|
215
|
+
|
|
216
|
+
friendly_type = _friendly_type_message(err, schema)
|
|
217
|
+
if friendly_type:
|
|
218
|
+
return _add_additional_properties_hint(friendly_type)
|
|
219
|
+
|
|
93
220
|
default_msg = (getattr(err, "message", "") or "").split("\n")[0]
|
|
94
|
-
return _add_additional_properties_hint(default_msg)
|
|
221
|
+
return _with_path(err, _add_additional_properties_hint(default_msg))
|
|
95
222
|
|
|
96
223
|
|
|
97
224
|
def _rank_for(err) -> tuple:
|
|
98
225
|
"""
|
|
99
226
|
Ranking for 'best' error per feature.
|
|
100
|
-
Prefer
|
|
227
|
+
Prefer Type/Required/Const > Enum > (Pattern/Minimum/Maximum) > others.
|
|
101
228
|
"""
|
|
102
229
|
kind = _err_kind(err)
|
|
103
230
|
order = (
|
|
104
|
-
0 if kind
|
|
105
|
-
1 if kind
|
|
231
|
+
0 if kind in {"Type", "Required", "Const"} else
|
|
232
|
+
1 if kind == "Enum" else
|
|
106
233
|
2 if kind in {"Pattern", "Minimum", "Maximum"} else
|
|
107
234
|
3
|
|
108
235
|
)
|
python_osw_validation/version.py
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
__version__ = '0.
|
|
1
|
+
__version__ = '0.4.0'
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: python_osw_validation
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.0
|
|
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
|
|
@@ -44,6 +44,7 @@ This package validates OSW GeoJSON datasets packaged as a ZIP file.
|
|
|
44
44
|
- Extracts the provided ZIP file
|
|
45
45
|
- Finds supported OSW dataset files inside the extracted directory
|
|
46
46
|
- Validates each file (`edges`, `lines`, `nodes`, `points`, `polygons`, and `zones`) against the matching schema
|
|
47
|
+
- Performs an upfront data-quality check for null-like placeholders in feature properties (for example `null`, `NaN`, `"null"`, `"nan"`)
|
|
47
48
|
- Runs cross-file integrity checks such as duplicate `_id` detection and edge or zone references back to nodes
|
|
48
49
|
- Returns a `ValidationResult` object with `is_valid`, `errors`, and `issues`
|
|
49
50
|
|
|
@@ -64,13 +65,24 @@ validator = OSWValidation(zipfile_path='<Zip file path>')
|
|
|
64
65
|
result = validator.validate()
|
|
65
66
|
print(result.is_valid)
|
|
66
67
|
print(result.errors) # returns up to the first 20 high-level errors by default
|
|
67
|
-
print(result.issues) #
|
|
68
|
+
print(result.issues) # detailed per-feature issues, capped to first 20 by default
|
|
68
69
|
|
|
69
70
|
result = validator.validate(max_errors=10)
|
|
70
71
|
print(result.is_valid)
|
|
71
72
|
print(result.errors) # returns up to the first 10 high-level errors
|
|
73
|
+
print(result.issues) # capped by the same max_errors limit
|
|
72
74
|
```
|
|
73
75
|
|
|
76
|
+
## Error behavior
|
|
77
|
+
|
|
78
|
+
- `errors`: high-level validation messages, capped by `max_errors` (default `20`).
|
|
79
|
+
- `issues`: detailed per-feature validation issues, also capped by `max_errors`.
|
|
80
|
+
- If null-like placeholders are found in feature `properties`, validation fails early before schema checks with actionable messages such as:
|
|
81
|
+
- `Invalid value at 'climb': 'null'. Null/NaN placeholders are not allowed; provide a valid value or remove this property.`
|
|
82
|
+
- For enum validation, long allowed-value lists are summarized as:
|
|
83
|
+
- first 5 values joined by `|`
|
|
84
|
+
- followed by `| and N more` when applicable.
|
|
85
|
+
|
|
74
86
|
You can also override schemas:
|
|
75
87
|
|
|
76
88
|
```python
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
python_osw_validation/__init__.py,sha256=
|
|
1
|
+
python_osw_validation/__init__.py,sha256=GQX6EdJxaYkMVZv0dGjhT1rJgX7FYyR6ksAi-UYayEs,33246
|
|
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=_LgtNoFTjJLqg64zxJLO1Q4dPpui_lWNPNDMnqN8Qck,8106
|
|
5
|
+
python_osw_validation/version.py,sha256=2eiWQI55fd-roDdkt4Hvl9WzrTJ4xQo33VzFud6D03U,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.0.dist-info/licenses/LICENSE,sha256=2bm9uFabQZ3Ykb_SaSU_uUbAj2-htc6WJQmS_65qD00,1073
|
|
15
|
+
python_osw_validation-0.4.0.dist-info/METADATA,sha256=fIdNFivsf7gvoWIVNtL11MtQ0yzoScgYS1XzHeLRp_o,6080
|
|
16
|
+
python_osw_validation-0.4.0.dist-info/WHEEL,sha256=SmOxYU7pzNKBqASvQJ7DjX3XGUF92lrGhMb3R6_iiqI,91
|
|
17
|
+
python_osw_validation-0.4.0.dist-info/top_level.txt,sha256=GE81UPcDHEffJCxYu3M_iPz3Dt-O3axB73R5SLm_Veo,22
|
|
18
|
+
python_osw_validation-0.4.0.dist-info/RECORD,,
|
|
File without changes
|
{python_osw_validation-0.3.6.dist-info → python_osw_validation-0.4.0.dist-info}/licenses/LICENSE
RENAMED
|
File without changes
|
{python_osw_validation-0.3.6.dist-info → python_osw_validation-0.4.0.dist-info}/top_level.txt
RENAMED
|
File without changes
|