python-osw-validation 0.4.4__py3-none-any.whl → 0.5.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.
@@ -8,6 +8,11 @@ import geopandas as gpd
8
8
  import jsonschema_rs
9
9
 
10
10
  from .zipfile_handler import ZipFileHandler
11
+ from .config import (
12
+ DEFAULT_COORDINATE_PRECISION,
13
+ DEFAULT_MAX_GEOMETRY_VERTICES,
14
+ ValidationConfig,
15
+ )
11
16
  from .extracted_data_validator import ExtractedDataValidator, OSW_DATASET_FILES, dataset_key_for_filename
12
17
  from .version import __version__
13
18
  from .helpers import (
@@ -16,6 +21,7 @@ from .helpers import (
16
21
  _feature_index_from_error,
17
22
  _pretty_message,
18
23
  _read_geojson_without_ext,
24
+ _geojson_features_exceeding_coordinate_precision,
19
25
  )
20
26
 
21
27
  SCHEMA_PATH = os.path.join(os.path.dirname(__file__), 'schema')
@@ -28,6 +34,17 @@ DEFAULT_DATASET_SCHEMAS = {
28
34
  "zones": os.path.join(SCHEMA_PATH, 'opensidewalks.zones.schema-0.3.json'),
29
35
  }
30
36
 
37
+ COORDINATE_PRECISION_REMEDY = (
38
+ "Reduce them to at most {limit} decimal places; "
39
+ "you can use the OSW data wizard tool to clean this up."
40
+ )
41
+ NULLISH_VALUE_REMEDY = (
42
+ "Null/NaN placeholders are not allowed; provide a valid value or remove this "
43
+ "property. You can use the OSW data wizard tool to clean this up."
44
+ )
45
+ MAX_GEOMETRY_VERTICES = DEFAULT_MAX_GEOMETRY_VERTICES
46
+ VERTEX_LIMIT_DATASETS = frozenset({"edges", "lines", "polygons", "zones"})
47
+
31
48
 
32
49
  class ValidationResult:
33
50
  """Container for validation outcome.
@@ -63,12 +80,18 @@ class OSWValidation:
63
80
  point_schema_path: Optional[str] = None,
64
81
  line_schema_path: Optional[str] = None,
65
82
  polygon_schema_path: Optional[str] = None,
83
+ config: Optional[ValidationConfig] = None,
66
84
  ):
67
85
  self.zipfile_path = zipfile_path
68
86
  self.extracted_dir: Optional[str] = None
69
87
  self.errors: List[str] = []
70
88
  # per-feature schema issues (formerly `fixme`)
71
89
  self.issues: List[Dict[str, Any]] = []
90
+ # dataset key ('edges') -> the GeoJSON filename it was read from
91
+ self.dataset_filenames: Dict[str, str] = {}
92
+ if config is not None and not isinstance(config, ValidationConfig):
93
+ raise TypeError("config must be a ValidationConfig instance.")
94
+ self.config = config or ValidationConfig()
72
95
 
73
96
  # Legacy single schema (if set, used for all)
74
97
  self.schema_file_path = schema_file_path # may be None
@@ -95,13 +118,63 @@ class OSWValidation:
95
118
  'error_message': message,
96
119
  })
97
120
 
121
+ def _dataset_filename(self, dataset_name: Optional[str]) -> Optional[str]:
122
+ """Resolve a dataset key to the file it was read from.
123
+
124
+ Errors always name a real file ('opensidewalks.edges.geojson'), never the
125
+ internal dataset key ('edges'). Names that are already filenames, such as
126
+ external extensions, pass through unchanged.
127
+ """
128
+ if dataset_name is None:
129
+ return None
130
+ return self.dataset_filenames.get(dataset_name, dataset_name)
131
+
132
+ def _check_coordinate_precision(self, file_paths, max_errors: int = 20) -> bool:
133
+ """Log an error per feature whose coordinates exceed the precision limit.
134
+
135
+ Returns True when every file is within the limit.
136
+ """
137
+ is_valid = True
138
+ for file_path in file_paths:
139
+ filename = os.path.basename(str(file_path))
140
+ try:
141
+ offending = _geojson_features_exceeding_coordinate_precision(
142
+ str(file_path),
143
+ self.config.coordinate_precision,
144
+ )
145
+ except (OSError, json.JSONDecodeError, TypeError, ValueError):
146
+ # Existing parsing and schema validation own all functional errors.
147
+ continue
148
+ for feature_index in offending:
149
+ is_valid = False
150
+ location = (
151
+ f"Feature {feature_index} in '{filename}'"
152
+ if feature_index is not None
153
+ else f"'{filename}'"
154
+ )
155
+ self.log_errors(
156
+ message=(
157
+ f"{location} contains coordinates with more than "
158
+ f"{self.config.coordinate_precision} decimal places. "
159
+ + COORDINATE_PRECISION_REMEDY.format(
160
+ limit=self.config.coordinate_precision
161
+ )
162
+ ),
163
+ filename=filename,
164
+ feature_index=feature_index,
165
+ )
166
+ if len(self.errors) >= max_errors:
167
+ return False
168
+ return is_valid
169
+
98
170
  # add this small helper inside OSWValidation (near other helpers)
99
171
  def _get_colset(self, gdf: Optional[gpd.GeoDataFrame], col: str, filekey: str) -> set:
100
172
  """Return set of a column if present; else log and return empty set."""
101
173
  if gdf is None:
102
174
  return set()
175
+ filename = self._dataset_filename(filekey)
103
176
  if col not in gdf.columns:
104
- self.log_errors(f"Missing required column '{col}' in {filekey}.", filekey, None)
177
+ self.log_errors(f"Missing required column '{col}' in {filename}.", filename, None)
105
178
  return set()
106
179
  try:
107
180
  return set(gdf[col].dropna())
@@ -110,17 +183,15 @@ class OSWValidation:
110
183
  try:
111
184
  return set(map(str, gdf[col].dropna()))
112
185
  except Exception:
113
- self.log_errors(f"Could not create set for column '{col}' in {filekey}.", filekey, None)
186
+ self.log_errors(f"Could not create set for column '{col}' in {filename}.", filename, None)
114
187
  return set()
115
188
 
116
189
  # ----------------------------
117
190
  # Geometry mapping helpers
118
191
  # ----------------------------
119
192
 
120
- _COORD_TOLERANCE = 1e-7 # ~1 cm at equator
121
-
122
193
  def _coords_match(self, c1: tuple, c2: tuple) -> bool:
123
- return abs(c1[0] - c2[0]) <= self._COORD_TOLERANCE and abs(c1[1] - c2[1]) <= self._COORD_TOLERANCE
194
+ return c1 == c2
124
195
 
125
196
  def _build_node_coord_map(self, nodes_df: gpd.GeoDataFrame) -> Dict[Any, tuple]:
126
197
  """Return {node_id: (lon, lat)} from a nodes GeoDataFrame."""
@@ -182,7 +253,7 @@ class OSWValidation:
182
253
  f"start coordinate {edge_start} does not match "
183
254
  f"node id '{u_id}' coordinate {node_coord} (_u_id mismatch)."
184
255
  ),
185
- filename='edges',
256
+ filename=self._dataset_filename('edges'),
186
257
  feature_index=feat_idx,
187
258
  )
188
259
 
@@ -204,7 +275,7 @@ class OSWValidation:
204
275
  f"end coordinate {edge_end} does not match "
205
276
  f"node id '{v_id}' coordinate {node_coord} (_v_id mismatch)."
206
277
  ),
207
- filename='edges',
278
+ filename=self._dataset_filename('edges'),
208
279
  feature_index=feat_idx,
209
280
  )
210
281
 
@@ -259,10 +330,131 @@ class OSWValidation:
259
330
  f"node id '{w_id}' coordinate {node_coord} is not a vertex "
260
331
  f"of the zone polygon geometry (_w_id coordinate mismatch)."
261
332
  ),
262
- filename='zones',
333
+ filename=self._dataset_filename('zones'),
263
334
  feature_index=feat_idx,
264
335
  )
265
336
 
337
+ @staticmethod
338
+ def _ring_vertex_count(ring) -> int:
339
+ coords = list(ring.coords)
340
+ if len(coords) > 1 and coords[0] == coords[-1]:
341
+ return len(coords) - 1
342
+ return len(coords)
343
+
344
+ def _geometry_vertex_count(self, geom) -> int:
345
+ """Count line and polygon vertices, excluding polygon ring closure coordinates."""
346
+ if geom is None:
347
+ return 0
348
+ if geom.geom_type == 'LineString':
349
+ return len(geom.coords)
350
+ if geom.geom_type == 'Polygon':
351
+ return self._ring_vertex_count(geom.exterior) + sum(
352
+ self._ring_vertex_count(ring) for ring in geom.interiors
353
+ )
354
+ if geom.geom_type in {'MultiLineString', 'MultiPolygon', 'GeometryCollection'}:
355
+ return sum(self._geometry_vertex_count(part) for part in geom.geoms)
356
+ return 0
357
+
358
+ def _validate_geometry_vertex_limit(
359
+ self,
360
+ gdf: Optional[gpd.GeoDataFrame],
361
+ dataset_name: str,
362
+ max_errors: int,
363
+ ) -> None:
364
+ """Report line or polygon features exceeding the configured vertex limit."""
365
+ if gdf is None:
366
+ return
367
+
368
+ for feature_index, row in gdf.iterrows():
369
+ if len(self.errors) >= max_errors:
370
+ break
371
+
372
+ vertex_count = self._geometry_vertex_count(row.geometry)
373
+ if vertex_count <= self.config.max_geometry_vertices:
374
+ continue
375
+
376
+ feature_id = row.get('_id', feature_index)
377
+ if self._is_nullish_value(feature_id):
378
+ feature_id = feature_index
379
+ filename = self._dataset_filename(dataset_name)
380
+ self.log_errors(
381
+ message=(
382
+ f"Feature '{feature_id}' in '{filename}' contains {vertex_count} geometry vertices. "
383
+ f"Maximum allowed is {self.config.max_geometry_vertices}."
384
+ ),
385
+ filename=filename,
386
+ feature_index=feature_index,
387
+ )
388
+
389
+ def _geometry_coordinate_pairs(self, geometry) -> List[tuple]:
390
+ """Return two-dimensional coordinate pairs from line and polygon geometries."""
391
+ if geometry is None or geometry.is_empty:
392
+ return []
393
+ if geometry.geom_type in {'LineString', 'LinearRing'}:
394
+ return [(coordinate[0], coordinate[1]) for coordinate in geometry.coords]
395
+ if geometry.geom_type == 'Polygon':
396
+ coordinates = self._geometry_coordinate_pairs(geometry.exterior)
397
+ for ring in geometry.interiors:
398
+ coordinates.extend(self._geometry_coordinate_pairs(ring))
399
+ return coordinates
400
+ if geometry.geom_type in {'MultiLineString', 'MultiPolygon', 'GeometryCollection'}:
401
+ return [
402
+ coordinate
403
+ for part in geometry.geoms
404
+ for coordinate in self._geometry_coordinate_pairs(part)
405
+ ]
406
+ return []
407
+
408
+ def _validate_collapsed_geometries(
409
+ self,
410
+ gdf: Optional[gpd.GeoDataFrame],
411
+ dataset_name: str,
412
+ max_errors: int,
413
+ ) -> set:
414
+ """Report line or polygon features whose coordinates all share one location."""
415
+ collapsed_indexes = set()
416
+ if gdf is None:
417
+ return collapsed_indexes
418
+
419
+ for feature_index, row in gdf.iterrows():
420
+ geometry = row.geometry
421
+ coordinates = self._geometry_coordinate_pairs(geometry)
422
+ if len(coordinates) < 2 or len(set(coordinates)) != 1:
423
+ continue
424
+
425
+ if geometry.geom_type in {'LineString', 'MultiLineString'}:
426
+ geometry_problem = 'zero-length'
427
+ elif geometry.geom_type in {'Polygon', 'MultiPolygon'}:
428
+ geometry_problem = 'zero-area'
429
+ else:
430
+ continue
431
+
432
+ collapsed_indexes.add(feature_index)
433
+ allow_zero_length_line = (
434
+ self.config.allow_zero_length_lines
435
+ and geometry.geom_type == 'LineString'
436
+ and dataset_name not in {"nodes", "points", "polygons", "zones"}
437
+ )
438
+ if allow_zero_length_line:
439
+ continue
440
+ if len(self.errors) >= max_errors:
441
+ continue
442
+
443
+ feature_id = row.get('_id', feature_index)
444
+ if self._is_nullish_value(feature_id):
445
+ feature_id = feature_index
446
+ filename = self._dataset_filename(dataset_name)
447
+ self.log_errors(
448
+ message=(
449
+ f"Feature '{feature_id}' in '{filename}' has {geometry_problem} geometry "
450
+ "because all coordinates are identical."
451
+ ),
452
+ filename=filename,
453
+ feature_index=feature_index,
454
+ )
455
+
456
+ return collapsed_indexes
457
+
266
458
  def _schema_key_from_text(self, text: Optional[str]) -> Optional[str]:
267
459
  """Return dataset key from exact filename suffixes only."""
268
460
  if not text:
@@ -423,6 +615,22 @@ class OSWValidation:
423
615
  )
424
616
  return _finalize(False)
425
617
 
618
+ # Remember which file each dataset key came from, so every error can
619
+ # name a real file instead of the internal key.
620
+ self.dataset_filenames = {}
621
+ for file in getattr(validator, 'files', []) or []:
622
+ basename = os.path.basename(str(file))
623
+ dataset_key = dataset_key_for_filename(basename)
624
+ if dataset_key:
625
+ self.dataset_filenames[dataset_key] = basename
626
+
627
+ if not self._check_coordinate_precision(
628
+ list(getattr(validator, 'files', []) or [])
629
+ + list(getattr(validator, 'externalExtensions', []) or []),
630
+ max_errors=max_errors,
631
+ ):
632
+ return _finalize(False)
633
+
426
634
  # Per-file schema validation → populate self.issues (fixme-like)
427
635
  for file in validator.files:
428
636
  file_path = os.path.join(file)
@@ -457,14 +665,15 @@ class OSWValidation:
457
665
  if not is_valid:
458
666
  total_duplicates = len(duplicates)
459
667
  displayed = ', '.join(map(str, duplicates[:max_errors]))
668
+ filename = self._dataset_filename(osw_file)
460
669
  if total_duplicates > max_errors:
461
- message = (f"Duplicate _id's found in {osw_file}: showing first {max_errors} "
670
+ message = (f"Duplicate _id's found in {filename}: showing first {max_errors} "
462
671
  f"of {total_duplicates} duplicates: {displayed}")
463
672
  else:
464
- message = f"Duplicate _id's found in {osw_file}: {displayed}"
673
+ message = f"Duplicate _id's found in {filename}: {displayed}"
465
674
  self.log_errors(
466
675
  message=message,
467
- filename=osw_file,
676
+ filename=filename,
468
677
  feature_index=None
469
678
  )
470
679
 
@@ -487,7 +696,12 @@ class OSWValidation:
487
696
  for item in (sub if isinstance(sub, (list, tuple)) else [sub])
488
697
  )
489
698
  else:
490
- self.log_errors("Missing required column '_w_id' in zones.", 'zones', None)
699
+ zones_filename = self._dataset_filename('zones')
700
+ self.log_errors(
701
+ f"Missing required column '_w_id' in {zones_filename}.",
702
+ zones_filename,
703
+ None,
704
+ )
491
705
  node_ids_zones_w = set()
492
706
  else:
493
707
  node_ids_zones_w = set()
@@ -504,7 +718,7 @@ class OSWValidation:
504
718
  message=(f"All _u_id's in edges should be part of _id's mentioned in nodes. "
505
719
  f"Showing {max_errors if num_unmatched > max_errors else 'all'} out of {num_unmatched} "
506
720
  f"unmatched _u_id's: {displayed_unmatched}"),
507
- filename='All',
721
+ filename=self._dataset_filename('edges'),
508
722
  feature_index=None
509
723
  )
510
724
 
@@ -519,7 +733,7 @@ class OSWValidation:
519
733
  message=(f"All _v_id's in edges should be part of _id's mentioned in nodes. "
520
734
  f"Showing {max_errors if num_unmatched > max_errors else 'all'} out of {num_unmatched} "
521
735
  f"unmatched _v_id's: {displayed_unmatched}"),
522
- filename='All',
736
+ filename=self._dataset_filename('edges'),
523
737
  feature_index=None
524
738
  )
525
739
 
@@ -534,7 +748,7 @@ class OSWValidation:
534
748
  message=(f"All _w_id's in zones should be part of _id's mentioned in nodes. "
535
749
  f"Showing {max_errors if num_unmatched > max_errors else 'all'} out of {num_unmatched} "
536
750
  f"unmatched _w_id's: {displayed_unmatched}"),
537
- filename='All',
751
+ filename=self._dataset_filename('zones'),
538
752
  feature_index=None
539
753
  )
540
754
 
@@ -549,6 +763,9 @@ class OSWValidation:
549
763
  for osw_file, gdf in OSW_DATASET.items():
550
764
  if gdf is None:
551
765
  continue
766
+ collapsed_indexes = self._validate_collapsed_geometries(gdf, osw_file, max_errors)
767
+ if osw_file in VERTEX_LIMIT_DATASETS and len(self.errors) < max_errors:
768
+ self._validate_geometry_vertex_limit(gdf, osw_file, max_errors)
552
769
  expected_geom = OSW_DATASET_FILES.get(osw_file, {}).get('geometry')
553
770
  if expected_geom:
554
771
  invalid_geojson = gdf[
@@ -557,6 +774,9 @@ class OSWValidation:
557
774
  else:
558
775
  invalid_geojson = gdf[gdf.is_valid == False]
559
776
 
777
+ if collapsed_indexes:
778
+ invalid_geojson = invalid_geojson.drop(index=collapsed_indexes, errors='ignore')
779
+
560
780
  if len(invalid_geojson) > 0:
561
781
  # Extract IDs if present, else fallback to index
562
782
  ids_series = invalid_geojson['_id'] if '_id' in invalid_geojson.columns else invalid_geojson.index
@@ -566,8 +786,9 @@ class OSWValidation:
566
786
  displayed_invalid = ', '.join(map(str, invalid_ids[:limit]))
567
787
  self.log_errors(
568
788
  message=(f"Showing {max_errors if num_invalid > max_errors else 'all'} out of {num_invalid} "
569
- f"invalid {osw_file} geometries, id's of invalid geometries: {displayed_invalid}"),
570
- filename='All',
789
+ f"invalid geometries in {self._dataset_filename(osw_file)}, "
790
+ f"id's of invalid geometries: {displayed_invalid}"),
791
+ filename=self._dataset_filename(osw_file),
571
792
  feature_index=None
572
793
  )
573
794
 
@@ -585,7 +806,18 @@ class OSWValidation:
585
806
  )
586
807
  continue
587
808
 
809
+ if len(self.errors) < max_errors:
810
+ self._validate_geometry_vertex_limit(extensionFile, file_name, max_errors)
811
+
812
+ collapsed_indexes = self._validate_collapsed_geometries(
813
+ extensionFile,
814
+ file_name,
815
+ max_errors,
816
+ )
817
+
588
818
  invalid_geojson = extensionFile[extensionFile.is_valid == False]
819
+ if collapsed_indexes:
820
+ invalid_geojson = invalid_geojson.drop(index=collapsed_indexes, errors='ignore')
589
821
  if len(invalid_geojson) > 0:
590
822
  try:
591
823
  invalid_ids = list(set(invalid_geojson.get('_id', invalid_geojson.index)))
@@ -710,10 +942,7 @@ class OSWValidation:
710
942
  return False
711
943
  found_nullish = True
712
944
  rendered = f'"{bad_value}"' if isinstance(bad_value, str) else str(bad_value)
713
- msg = (
714
- f"Invalid value at '{path}': {rendered}. "
715
- f"Null/NaN placeholders are not allowed; provide a valid value or remove this property."
716
- )
945
+ msg = f"Invalid value at '{path}': {rendered}. {NULLISH_VALUE_REMEDY}"
717
946
  self.errors.append(f"Validation error: {msg}")
718
947
  self.issues.append({
719
948
  "filename": filename,
@@ -0,0 +1,31 @@
1
+ from dataclasses import dataclass
2
+
3
+
4
+ DEFAULT_MAX_GEOMETRY_VERTICES = 2000
5
+ DEFAULT_COORDINATE_PRECISION = 7
6
+ DEFAULT_ALLOW_ZERO_LENGTH_LINES = True
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class ValidationConfig:
11
+ """User-configurable validation behavior."""
12
+
13
+ max_geometry_vertices: int = DEFAULT_MAX_GEOMETRY_VERTICES
14
+ coordinate_precision: int = DEFAULT_COORDINATE_PRECISION
15
+ allow_zero_length_lines: bool = DEFAULT_ALLOW_ZERO_LENGTH_LINES
16
+
17
+ def __post_init__(self) -> None:
18
+ if isinstance(self.max_geometry_vertices, bool) or not isinstance(
19
+ self.max_geometry_vertices, int
20
+ ):
21
+ raise TypeError("max_geometry_vertices must be an integer.")
22
+ if self.max_geometry_vertices <= 0:
23
+ raise ValueError("max_geometry_vertices must be greater than zero.")
24
+ if isinstance(self.coordinate_precision, bool) or not isinstance(
25
+ self.coordinate_precision, int
26
+ ):
27
+ raise TypeError("coordinate_precision must be an integer.")
28
+ if self.coordinate_precision < 0:
29
+ raise ValueError("coordinate_precision must be zero or greater.")
30
+ if not isinstance(self.allow_zero_length_lines, bool):
31
+ raise TypeError("allow_zero_length_lines must be a boolean.")
@@ -1,10 +1,68 @@
1
- from typing import Optional
2
1
  import json
3
2
  import re
3
+ from decimal import Decimal
4
+ from typing import Any, List, Optional
4
5
 
5
6
  import geopandas as gpd
6
7
 
7
8
 
9
+ def _coordinate_values_exceed_decimal_places(values: Any, max_decimal_places: int) -> bool:
10
+ if isinstance(values, Decimal):
11
+ return values.is_finite() and max(0, -values.as_tuple().exponent) > max_decimal_places
12
+ if isinstance(values, list):
13
+ return any(_coordinate_values_exceed_decimal_places(value, max_decimal_places) for value in values)
14
+ return False
15
+
16
+
17
+ def _geometry_exceeds_coordinate_precision(geometry: Any, max_decimal_places: int) -> bool:
18
+ if not isinstance(geometry, dict):
19
+ return False
20
+ if _coordinate_values_exceed_decimal_places(geometry.get("coordinates"), max_decimal_places):
21
+ return True
22
+ geometries = geometry.get("geometries", [])
23
+ if not isinstance(geometries, list):
24
+ return False
25
+ return any(
26
+ _geometry_exceeds_coordinate_precision(child, max_decimal_places)
27
+ for child in geometries
28
+ )
29
+
30
+
31
+ def _geojson_features_exceeding_coordinate_precision(
32
+ file_path: str, max_decimal_places: int = 7
33
+ ) -> List[Optional[int]]:
34
+ """Return feature indices whose coordinates exceed the decimal-place limit.
35
+
36
+ A single-`Feature` or bare-geometry document has no feature index, so it is
37
+ reported as `None` when it violates the limit.
38
+ """
39
+ with open(file_path, 'r', encoding='utf-8') as file:
40
+ data = json.load(file, parse_float=Decimal)
41
+
42
+ if not isinstance(data, dict):
43
+ return []
44
+ if data.get("type") == "FeatureCollection":
45
+ features = data.get("features", [])
46
+ if not isinstance(features, list):
47
+ return []
48
+ return [
49
+ index
50
+ for index, feature in enumerate(features)
51
+ if isinstance(feature, dict)
52
+ and _geometry_exceeds_coordinate_precision(feature.get("geometry"), max_decimal_places)
53
+ ]
54
+ if data.get("type") == "Feature":
55
+ geometry = data.get("geometry")
56
+ else:
57
+ geometry = data
58
+ return [None] if _geometry_exceeds_coordinate_precision(geometry, max_decimal_places) else []
59
+
60
+
61
+ def _geojson_file_has_excess_coordinate_precision(file_path: str, max_decimal_places: int = 7) -> bool:
62
+ """Return whether serialized GeoJSON coordinates exceed the decimal-place limit."""
63
+ return bool(_geojson_features_exceeding_coordinate_precision(file_path, max_decimal_places))
64
+
65
+
8
66
  def _read_geojson_without_ext(file_path: str) -> gpd.GeoDataFrame:
9
67
  """Load a GeoJSON file into a GeoDataFrame with ext:* properties removed.
10
68
 
@@ -415,7 +415,6 @@
415
415
  "enum": [
416
416
  "broadleaved",
417
417
  "leafless",
418
- "mixed",
419
418
  "needleleaved"
420
419
  ],
421
420
  "type": "string"
@@ -255,25 +255,6 @@
255
255
  "yes"
256
256
  ],
257
257
  "type": "string"
258
- },
259
- "name": {
260
- "description": "A field for a designated name for an entity. Example: an official name for a trail.",
261
- "type": "string"
262
- },
263
- "surface": {
264
- "description": "A field for the surface material of the path.",
265
- "enum": [
266
- "asphalt",
267
- "concrete",
268
- "dirt",
269
- "grass",
270
- "grass_paver",
271
- "gravel",
272
- "paved",
273
- "paving_stones",
274
- "unpaved"
275
- ],
276
- "type": "string"
277
258
  }
278
259
  },
279
260
  "required": [
@@ -1 +1 @@
1
- __version__ = '0.4.4'
1
+ __version__ = '0.5.0'
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python_osw_validation
3
- Version: 0.4.4
3
+ Version: 0.5.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
@@ -77,12 +77,46 @@ print(result.errors) # returns up to the first 10 high-level errors
77
77
  print(result.issues) # capped by the same max_errors limit
78
78
  ```
79
79
 
80
+ ### Validation configuration
81
+
82
+ Use `ValidationConfig` to override validation behavior for one validator instance.
83
+ When no configuration is supplied, the documented defaults are used.
84
+
85
+ ```python
86
+ from python_osw_validation import OSWValidation, ValidationConfig
87
+
88
+ config = ValidationConfig(
89
+ max_geometry_vertices=3000,
90
+ coordinate_precision=8,
91
+ allow_zero_length_lines=False,
92
+ )
93
+
94
+ validator = OSWValidation(
95
+ zipfile_path="dataset.zip",
96
+ config=config,
97
+ )
98
+ result = validator.validate()
99
+ ```
100
+
101
+ | Setting | Default | Meaning |
102
+ |---------|---------|---------|
103
+ | `max_geometry_vertices` | `2000` | Maximum allowed vertices for edges, lines, polygons, and zones. Must be an integer greater than zero. |
104
+ | `coordinate_precision` | `7` | Maximum coordinate decimal places allowed. Features exceeding it fail validation. Must be a non-negative integer. |
105
+ | `allow_zero_length_lines` | `True` | Allows collapsed `LineString` geometries in edges, lines, and external line data. Set to `False` to reject them. |
106
+
107
+ Allowing zero-length lines does not bypass `_u_id`/`_v_id` existence or exact
108
+ node-coordinate checks. Zero-area polygons and zones, collapsed `MultiLineString`
109
+ geometries, and line geometries in point datasets remain invalid.
110
+
80
111
  ## Error behavior
81
112
 
82
113
  - `errors`: high-level validation messages, capped by `max_errors` (default `20`).
83
114
  - `issues`: detailed per-feature validation issues, also capped by `max_errors`.
115
+ - Coordinates carrying more than `coordinate_precision` decimal places fail validation before schema checks, one error per offending feature, and the message names the fix:
116
+ - `Feature 12 in 'osw.edges.geojson' contains coordinates with more than 7 decimal places. Reduce them to at most 7 decimal places; you can use the OSW data wizard tool to clean this up.`
117
+ - `issues[].filename` is always the GeoJSON file the problem was found in, never an internal dataset key.
84
118
  - If actual null or numeric NaN values are found in `ext:*` extension properties, validation fails early before schema checks with actionable messages such as:
85
- - `Invalid value at 'ext:metadata.score': nan. Null/NaN placeholders are not allowed; provide a valid value or remove this property.`
119
+ - `Invalid value at 'ext:metadata.score': nan. Null/NaN placeholders are not allowed; provide a valid value or remove this property. You can use the OSW data wizard tool to clean this up.`
86
120
  - For enum validation, long allowed-value lists are summarized as:
87
121
  - first 5 values joined by `|`
88
122
  - followed by `| and N more` when applicable.
@@ -1,18 +1,19 @@
1
- python_osw_validation/__init__.py,sha256=TnXG51m-hm4gcHE5E5QovPu6Nnm7GeM7dgEVjmNCT3k,34074
1
+ python_osw_validation/__init__.py,sha256=oa0KQNuAP5GRZYS63DvV5D_csltBrCq6kNu4WRh_kGM,43928
2
+ python_osw_validation/config.py,sha256=NFxqenwuSeQgAW-QIXCTRZV2Bf5OavBtUOr3ZHtSTcw,1260
2
3
  python_osw_validation/extracted_data_validator.py,sha256=ry5M6XO-fwijVc1XCIAMmfeR3n45V-NkSWPuJNF6vJ4,6949
3
4
  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=xKUiX0ZYXbYTA8dYVoy7bcY2aZprczNMGX4XQ_Q1slw,22
5
+ python_osw_validation/helpers.py,sha256=oiKqlGEVJVT5Zcws7h09zdLQOSJx1Vc-DqSu7bCedsA,11546
6
+ python_osw_validation/version.py,sha256=0PaI2eSOCp5kkNcpKpUSbLHf66rL9xQzFpYyLGpEtyM,22
6
7
  python_osw_validation/zipfile_handler.py,sha256=jXnP-8O5AAOBapuNF3-XdFVM1MHiPaWpl_wlbX-aqhY,2631
7
8
  python_osw_validation/schema/opensidewalks.edges.schema-0.3.json,sha256=yE4K97WEdQBMHlVo5k9uheJ8TzHE6Tfupekxq_uv5Bk,78976
8
9
  python_osw_validation/schema/opensidewalks.lines.schema-0.3.json,sha256=AlZuNu4dxEvnnqamHoogg9Y0yZMEyUtB0r854SF0xYo,9326
9
10
  python_osw_validation/schema/opensidewalks.nodes.schema-0.3.json,sha256=yEv4pIY69YvPHhSiQmvU21HeI426V-Z4j2K7ONQAwLM,14445
10
- python_osw_validation/schema/opensidewalks.points.schema-0.3.json,sha256=WYmlC4QFD-JUCnM0w3GBVI1E-LmCTRmTrGla1Z7o9Kw,13035
11
+ python_osw_validation/schema/opensidewalks.points.schema-0.3.json,sha256=hx5L1FvlvYTtBwpzaMAwCEl4T4MX7fdnABcNR7aFqAk,13004
11
12
  python_osw_validation/schema/opensidewalks.polygons.schema-0.3.json,sha256=VzDpHv1ZVT42cAk9n3gsFZjS7WcflQzSbjN-aNIVTYM,16286
12
13
  python_osw_validation/schema/opensidewalks.schema-0.3.json,sha256=vyyGzPpqLxr1e5wFfNKzlA1sr6tmhHKM7ntaTk8z5k8,278489
13
- python_osw_validation/schema/opensidewalks.zones.schema-0.3.json,sha256=JCqoCJj-dCuPVPHWSUQhRJMebaJ9IrzHWwTVAC6j7dY,11281
14
- python_osw_validation-0.4.4.dist-info/licenses/LICENSE,sha256=2bm9uFabQZ3Ykb_SaSU_uUbAj2-htc6WJQmS_65qD00,1073
15
- python_osw_validation-0.4.4.dist-info/METADATA,sha256=rtDNQFVz6QIpEBSqStehNTY3h1MCNSD2KsE6PS8Xx7Y,6782
16
- python_osw_validation-0.4.4.dist-info/WHEEL,sha256=SmOxYU7pzNKBqASvQJ7DjX3XGUF92lrGhMb3R6_iiqI,91
17
- python_osw_validation-0.4.4.dist-info/top_level.txt,sha256=GE81UPcDHEffJCxYu3M_iPz3Dt-O3axB73R5SLm_Veo,22
18
- python_osw_validation-0.4.4.dist-info/RECORD,,
14
+ python_osw_validation/schema/opensidewalks.zones.schema-0.3.json,sha256=j4vjO5JR5LrRieEhoqOl1ftqwEiU7xggAz__s6LQI38,10548
15
+ python_osw_validation-0.5.0.dist-info/licenses/LICENSE,sha256=2bm9uFabQZ3Ykb_SaSU_uUbAj2-htc6WJQmS_65qD00,1073
16
+ python_osw_validation-0.5.0.dist-info/METADATA,sha256=lZmfZqN9l09dPus89VwLASjuVPWH94gCYqjWkEXPH5Y,8542
17
+ python_osw_validation-0.5.0.dist-info/WHEEL,sha256=SmOxYU7pzNKBqASvQJ7DjX3XGUF92lrGhMb3R6_iiqI,91
18
+ python_osw_validation-0.5.0.dist-info/top_level.txt,sha256=GE81UPcDHEffJCxYu3M_iPz3Dt-O3axB73R5SLm_Veo,22
19
+ python_osw_validation-0.5.0.dist-info/RECORD,,