python-osw-validation 0.0.5__py3-none-any.whl → 0.2.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.
@@ -2,8 +2,10 @@ import os
2
2
  import json
3
3
  import jsonschema
4
4
  from typing import Dict, Any, Optional, List
5
+ import geopandas as gpd
5
6
  from .zipfile_handler import ZipFileHandler
6
- from .extracted_data_validator import ExtractedDataValidator
7
+ from .extracted_data_validator import ExtractedDataValidator, OSW_dataset_files
8
+ from .version import __version__
7
9
 
8
10
  SCHEMA_PATH = os.path.join(os.path.dirname(__file__), 'schema')
9
11
 
@@ -34,6 +36,14 @@ class OSWValidation:
34
36
  except Exception as e:
35
37
  self.errors.append(f'Invalid or missing schema file: {e}')
36
38
  raise Exception(f'Invalid or missing schema file: {e}')
39
+
40
+ def are_ids_unique(self, gdf):
41
+ """Check for duplicate values in the _id field"""
42
+ duplicates = gdf[gdf.duplicated('_id', keep=False)]['_id'].unique()
43
+
44
+ is_valid = len(duplicates) == 0
45
+
46
+ return is_valid, list(duplicates)
37
47
 
38
48
  def validate(self) -> ValidationResult:
39
49
  try:
@@ -50,15 +60,84 @@ class OSWValidation:
50
60
  if not validator.is_valid():
51
61
  self.errors.append(validator.error)
52
62
  return ValidationResult(False, self.errors)
63
+ for file in validator.files:
64
+ file_path = os.path.join(file)
65
+ is_valid = self.validate_osw_errors(file_path)
53
66
 
67
+ if self.errors:
68
+ zip_handler.remove_extracted_files()
69
+ return ValidationResult(False, self.errors)
70
+
71
+ # Validate data integrity
72
+ OSW_dataset = {}
54
73
  for file in validator.files:
55
74
  file_path = os.path.join(file)
56
- is_valid = self.validate_osw_errors(self.load_osw_file(file_path))
75
+ osw_file = next((osw_file_any for osw_file_any in OSW_dataset_files.keys() if osw_file_any in file_path), '')
76
+ OSW_dataset[osw_file] = gpd.read_file(file_path)
77
+
78
+ # Are all id's unique in each file? No need to check uniqueness across files yet since we do not have a global OSW ID format yet
79
+ for osw_file in OSW_dataset:
80
+ is_valid, duplicates = self.are_ids_unique(OSW_dataset[osw_file])
57
81
  if not is_valid:
58
- zip_handler.remove_extracted_files()
59
- return ValidationResult(False, self.errors)
82
+ self.errors.append(f"Duplicate _id's found in {osw_file} : {duplicates}")
83
+
84
+ # Create sets of node id's and foreign keys to be used in validation
85
+ if "nodes" in OSW_dataset:
86
+ node_ids = set(OSW_dataset['nodes']['_id'])
87
+ else:
88
+ node_ids = set()
89
+
90
+ if "edges" in OSW_dataset:
91
+ node_ids_edges_u = set(OSW_dataset['edges']['_u_id'])
92
+ node_ids_edges_v = set(OSW_dataset['edges']['_v_id'])
93
+ else:
94
+ node_ids_edges_u = set()
95
+ node_ids_edges_v = set()
96
+
97
+ if "zones" in OSW_dataset:
98
+ node_ids_zones_w = set([item for sublist in OSW_dataset['zones']['_w_id'] for item in sublist])
99
+ else:
100
+ node_ids_zones_w = set()
101
+
102
+ # Do all node references in _u_id exist in nodes?
103
+ unmatched = node_ids_edges_u - node_ids
104
+ is_valid = len(unmatched) == 0
105
+ if not is_valid:
106
+ self.errors.append(f"All _u_id's in edges should be part of _id's mentioned in nodes, _u_id's not in nodes are: {unmatched}")
60
107
 
61
- return ValidationResult(True)
108
+ # Do all node references in _v_id exist in nodes?
109
+ unmatched = node_ids_edges_v - node_ids
110
+ is_valid = len(unmatched) == 0
111
+ if not is_valid:
112
+ self.errors.append(f"All _v_id's in edges should be part of _id's mentioned in nodes, _v_id's not in nodes are: {unmatched}")
113
+
114
+ # Do all node references in _w_id exist in nodes?
115
+ unmatched = node_ids_zones_w - node_ids
116
+ is_valid = len(unmatched) == 0
117
+ if not is_valid:
118
+ self.errors.append(f"All _w_id's in zones should be part of _id's mentioned in nodes, _w_id's not in nodes are: {unmatched}")
119
+
120
+ # Geometry validation: check geometry type in each file and test if coordinates make a shape that is reasonable geometric shape according to the Simple Feature Access standard
121
+ for osw_file in OSW_dataset:
122
+ invalid_geojson = OSW_dataset[osw_file][(OSW_dataset[osw_file].geometry.type != OSW_dataset_files[osw_file]['geometry']) | (OSW_dataset[osw_file].is_valid==False)]
123
+ is_valid = len(invalid_geojson) == 0
124
+ if not is_valid:
125
+ self.errors.append(f"Invalid {osw_file} geometries found, id's of invalid geometries: {set(invalid_geojson['_id'])}")
126
+
127
+ # Validate OSW external extensions
128
+ for file in validator.externalExtensions:
129
+ file_path = os.path.join(file)
130
+ extensionFile = gpd.read_file(file_path)
131
+ invalid_geojson = extensionFile[extensionFile.is_valid==False]
132
+ is_valid = len(invalid_geojson) == 0
133
+ if not is_valid:
134
+ self.errors.append(f"Invalid geometries found in extension file {file}, list of invalid geometries: {invalid_geojson.to_json()}")
135
+
136
+ if self.errors:
137
+ zip_handler.remove_extracted_files()
138
+ return ValidationResult(False, self.errors)
139
+ else:
140
+ return ValidationResult(True)
62
141
  except Exception as e:
63
142
  self.errors.append(f'Unable to validate: {e}')
64
143
  return ValidationResult(False, self.errors)
@@ -68,8 +147,9 @@ class OSWValidation:
68
147
  with open(graph_geojson_path, 'r') as file:
69
148
  return json.load(file)
70
149
 
71
- def validate_osw_errors(self, geojson_data: Dict[str, Any]) -> bool:
150
+ def validate_osw_errors(self, file_path: str) -> bool:
72
151
  '''Validate OSW Data against the schema and process all errors'''
152
+ geojson_data = self.load_osw_file(file_path)
73
153
  validator = jsonschema.Draft7Validator(self.load_osw_schema(self.schema_file_path))
74
154
  errors = list(validator.iter_errors(geojson_data))
75
155
 
@@ -2,10 +2,38 @@ import os
2
2
  import glob
3
3
 
4
4
 
5
+ OSW_dataset_files = {"edges": {
6
+ "required": False,
7
+ "geometry": "LineString"
8
+ },
9
+ "nodes": {
10
+ "required": False,
11
+ "geometry": "Point"
12
+ },
13
+ "points": {
14
+ "required": False,
15
+ "geometry": "Point"
16
+ },
17
+ "lines": {
18
+ "required": False,
19
+ "geometry": "LineString"
20
+ },
21
+ "zones": {
22
+ "required": False,
23
+ "geometry": "Polygon"
24
+ },
25
+ "polygons": {
26
+ "required": False,
27
+ "geometry": "Polygon"
28
+ }
29
+ }
30
+
31
+
5
32
  class ExtractedDataValidator:
6
33
  def __init__(self, extracted_dir: str):
7
34
  self.extracted_dir = extracted_dir
8
35
  self.files = []
36
+ self.externalExtensions = []
9
37
  self.error = None
10
38
 
11
39
  def is_valid(self) -> bool:
@@ -25,23 +53,48 @@ class ExtractedDataValidator:
25
53
  self.error = 'No .geojson files found in the specified directory or its subdirectories.'
26
54
  return False
27
55
 
28
- required_files = {'nodes', 'edges'}
29
- optional_files = {'points'}
30
- for filename in geojson_files:
31
- base_name = os.path.basename(filename)
32
- for required_file in required_files:
56
+ required_files = [key for key, value in OSW_dataset_files.items() if value['required']]
57
+ optional_files = [key for key, value in OSW_dataset_files.items() if not value['required']]
58
+ missing_files = []
59
+ duplicate_files = []
60
+ for required_file in required_files:
61
+ file_count = 0
62
+ for filename in geojson_files:
63
+ base_name = os.path.basename(filename)
33
64
  if required_file in base_name and base_name.endswith('.geojson'):
34
- self.files.append(filename)
35
- required_files.remove(required_file)
36
- break
37
- for optional_file in optional_files:
65
+ file_count += 1
66
+ save_filename = filename
67
+ if file_count == 0:
68
+ # Missing required file
69
+ missing_files.append(required_file)
70
+ elif file_count == 1:
71
+ self.files.append(save_filename)
72
+ else:
73
+ # Duplicate file
74
+ duplicate_files.append(required_file)
75
+
76
+ for optional_file in optional_files:
77
+ file_count = 0
78
+ for filename in geojson_files:
79
+ base_name = os.path.basename(filename)
38
80
  if optional_file in base_name and base_name.endswith('.geojson'):
39
- self.files.append(filename)
40
- optional_files.remove(optional_file)
41
- break
81
+ file_count += 1
82
+ save_filename = filename
83
+ if file_count == 1:
84
+ self.files.append(save_filename)
85
+ elif file_count > 1:
86
+ # Duplicate file
87
+ duplicate_files.append(optional_file)
42
88
 
43
- if required_files:
44
- self.error = f'Missing required .geojson files: {", ".join(required_files)}.'
89
+ if missing_files:
90
+ self.error = f'Missing required .geojson files: {", ".join(missing_files)}.'
91
+ return False
92
+
93
+ if duplicate_files:
94
+ self.error = f'Multiple .geojson files of the same type found: {", ".join(duplicate_files)}.'
45
95
  return False
96
+
97
+ # Add OSW external extensions, GeoJSON files we know nothing about
98
+ self.externalExtensions.extend([item for item in geojson_files if item not in self.files])
46
99
 
47
100
  return True