forked from OSGeo/gdal
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathvalidate_s102.py
More file actions
executable file
·2250 lines (2013 loc) · 93 KB
/
validate_s102.py
File metadata and controls
executable file
·2250 lines (2013 loc) · 93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
###############################################################################
#
# Project: GDAL/OGR
# Purpose: Test compliance of IHO S102 v3.0 dataset
# Author: Even Rouault <even.rouault at spatialys.com>
#
###############################################################################
# Copyright (c) 2025, Even Rouault <even.rouault at spatialys.com>
#
# SPDX-License-Identifier: MIT
###############################################################################
# Validates against
# https://iho-ohi.github.io/S-102-Product-Specification/documents/3.0.0/document.html and
# https://iho.int/uploads/user/pubs/standards/s-100/S-100_5.2.0_Final_Clean.pdf
# "102_DevXXXX" are for traceability with respect to requirements of the spreadsheet:
# https://raw.githubusercontent.com/iho-ohi/S-100-Validation-Checks/refs/heads/main/Documents/S-158-102/0.2.0/S-158_102_0_2_0_20241118.xlsx
# Note that there are a few checks in that spreadsheet that are specific only of 2.3.0, and not 3.0.0...
import os
import re
import struct
import sys
# Standard Python modules
from collections import namedtuple
# Extension modules
import h5py
import numpy as np
try:
from osgeo import osr
osr.UseExceptions()
gdal_available = True
except ImportError:
gdal_available = False
ERROR = "Error"
CRITICAL_ERROR = "Critical error"
AttributeDefinition = namedtuple(
"AttributeDefinition", ["name", "required", "type", "fixed_value"]
)
def _get_int_value_or_none(v):
try:
return int(v)
except ValueError:
return None
def _get_int_attr_or_none(group, attr_name):
if attr_name not in group.attrs:
return None
return _get_int_value_or_none(group.attrs[attr_name])
def _get_float_value_or_none(v):
try:
return float(v)
except ValueError:
return None
def _get_float_attr_or_none(group, attr_name):
if attr_name not in group.attrs:
return None
return _get_float_value_or_none(group.attrs[attr_name])
def _cast_to_float32(v):
return struct.unpack("f", struct.pack("f", v))[0]
class S102ValidationException(Exception):
pass
class S102Checker:
def __init__(self, filename, abort_at_first_error=False):
self.filename = filename
self.abort_at_first_error = abort_at_first_error
self.errors = []
self.warnings = []
self.checks_done = set([])
def _log_check(self, name):
self.checks_done.add(name)
def _warning(self, msg):
self.warnings += [msg]
def _error(self, msg):
self.errors += [(ERROR, msg)]
if self.abort_at_first_error:
raise S102ValidationException(f"{ERROR}: {msg}")
def _critical_error(self, msg):
self.errors += [(CRITICAL_ERROR, msg)]
if self.abort_at_first_error:
raise S102ValidationException(f"{CRITICAL_ERROR}: {msg}")
def _is_uint8(self, h5_type):
return (
isinstance(h5_type, h5py.h5t.TypeIntegerID)
and h5_type.get_sign() == h5py.h5t.SGN_NONE
and h5_type.get_size() == 1
)
def _is_uint16(self, h5_type):
return (
isinstance(h5_type, h5py.h5t.TypeIntegerID)
and h5_type.get_sign() == h5py.h5t.SGN_NONE
and h5_type.get_size() == 2
)
def _is_uint32(self, h5_type):
return (
isinstance(h5_type, h5py.h5t.TypeIntegerID)
and h5_type.get_sign() == h5py.h5t.SGN_NONE
and h5_type.get_size() == 4
)
def _is_int16(self, h5_type):
return (
isinstance(h5_type, h5py.h5t.TypeIntegerID)
and h5_type.get_sign() == h5py.h5t.SGN_2
and h5_type.get_size() == 2
)
def _is_int32(self, h5_type):
return (
isinstance(h5_type, h5py.h5t.TypeIntegerID)
and h5_type.get_sign() == h5py.h5t.SGN_2
and h5_type.get_size() == 4
)
def _is_float32(self, h5_type):
return isinstance(h5_type, h5py.h5t.TypeFloatID) and h5_type.get_size() == 4
def _is_float64(self, h5_type):
return isinstance(h5_type, h5py.h5t.TypeFloatID) and h5_type.get_size() == 8
def _is_string(self, h5_type):
return isinstance(h5_type, h5py.h5t.TypeStringID)
def _is_enumeration(self, h5_type):
return isinstance(h5_type, h5py.h5t.TypeEnumID)
def _check_attributes(self, ctxt_name, group, attr_list):
for attr_def in attr_list:
if attr_def.required and attr_def.name not in group.attrs:
# 102_Dev1002: check presence of required attributes
self._critical_error(
f"Required {ctxt_name} attribute '{attr_def.name}' is missing"
)
elif attr_def.name in group.attrs:
attr = group.attrs[attr_def.name]
if isinstance(attr, np.ndarray):
self._critical_error(
f"{ctxt_name} attribute '{attr_def.name}' is not a scalar"
)
if len(attr) == 1:
attr = attr[0]
if isinstance(attr, bytes):
attr = attr.decode("utf-8")
h5_type = group.attrs.get_id(attr_def.name).get_type()
# 102_Dev1004: check type
if attr_def.type == "string":
if not self._is_string(h5_type):
self._critical_error(
f"{ctxt_name} attribute '{attr_def.name}' is not a string "
)
elif attr_def.type == "time":
if not self._is_string(h5_type):
self._critical_error(
f"{ctxt_name} attribute '{attr_def.name}' is not a string"
)
# 102_Dev1005: validate date or time
self._log_check("102_Dev1005")
pattern = re.compile(
r"^(?:[01]\d|2[0-3])[0-5]\d[0-5]\d(?:Z|[+-](?:[01]\d|2[0-3])[0-5]\d)$"
)
if not pattern.match(attr):
self._error(
f"{ctxt_name} attribute '{attr_def.name}' is not a valid time: {attr}"
)
elif attr_def.type == "date":
if not isinstance(h5_type, h5py.h5t.TypeStringID):
self._critical_error(
f"{ctxt_name} attribute '{attr_def.name}' is not a string"
)
elif h5_type.get_size() != 8:
self._warning(
f"{ctxt_name} attribute '{attr_def.name}' is not a 8-character string"
)
# 102_Dev1005: validate date or time
self._log_check("102_Dev1005")
pattern = re.compile(
r"^(?:[0-9]{4})(?:(?:0[1-9]|1[0-2])(?:0[1-9]|[12][0-9]|3[01]))$"
)
if not pattern.match(attr):
self._error(
f"{ctxt_name} attribute '{attr_def.name}' is not a valid date: {attr}"
)
elif attr_def.type == "uint8":
if not self._is_uint8(h5_type):
self._critical_error(
f"{ctxt_name} attribute '{attr_def.name}' is not a uint8"
)
elif attr_def.type == "uint16":
if not self._is_uint16(h5_type):
self._critical_error(
f"{ctxt_name} attribute '{attr_def.name}' is not a uint16"
)
elif attr_def.type == "uint32":
if not self._is_uint32(h5_type):
self._critical_error(
f"{ctxt_name} attribute '{attr_def.name}' is not a uint32"
)
elif attr_def.type == "int32":
if not self._is_int32(h5_type):
self._critical_error(
f"{ctxt_name} attribute '{attr_def.name}' is not a int32"
)
elif attr_def.type == "float32":
if not self._is_float32(h5_type):
self._critical_error(
f"{ctxt_name} attribute '{attr_def.name}' is not a float32"
)
elif attr_def.type == "float64":
if not self._is_float64(h5_type):
self._critical_error(
f"{ctxt_name} attribute '{attr_def.name}' is not a float64"
)
elif attr_def.type == "enumeration":
if not self._is_enumeration(h5_type):
self._critical_error(
f"{ctxt_name} attribute '{attr_def.name}' is not an enumeration"
)
else:
raise Exception(
f"Programming error: unexpected type {attr_def.type}"
)
if attr_def.fixed_value:
self._log_check("102_Dev1006")
if attr != attr_def.fixed_value:
self._critical_error(
f"{ctxt_name} attribute '{attr_def.name}' has value '{attr}', whereas '{attr_def.fixed_value}' is expected"
)
self._log_check("102_Dev1028")
attr_dict = {a.name: a for a in attr_list}
for attr in group.attrs:
if attr not in attr_dict:
self._warning(f"Extra element in {ctxt_name} group: '{attr}'")
def check(self):
try:
f = h5py.File(self.filename, "r")
except Exception as e:
self._critical_error(str(e))
return
self._log_check("102_Dev9005")
file_size = os.stat(self.filename).st_size
if file_size > 10 * 1024 * 1024:
self._warning(
f"File size of {self.filename} = {file_size}, which exceeds 10 MB"
)
basename = os.path.basename(self.filename)
if not basename.startswith("102"):
self._warning("File name should start with '102'")
if not basename.upper().endswith(".H5"):
self._warning("File name should end with '.H5'")
pattern = r"^102[a-zA-Z0-9]{4}[a-zA-Z0-9_]{1,12}\.(?:h5|H5)$"
if not re.match(pattern, basename):
self._warning(
f"File name '{basename}' does not match expected pattern '{pattern}'"
)
self._log_check("102_Dev1028")
for key in f.keys():
if key not in (
"Group_F",
"BathymetryCoverage",
"QualityOfBathymetryCoverage",
):
self._warning(f"Unexpected element {key} in top level group")
self._log_check("102_Dev1001")
if "Group_F" in f.keys():
self._validate_group_f(f, f["Group_F"])
else:
self._critical_error("No feature information group ('Group_F')")
# Cf Table 10-2 - Root group attributes
topLevelAttributesList = [
AttributeDefinition(
name="productSpecification",
required=True,
type="string",
fixed_value="INT.IHO.S-102.3.0.0",
),
AttributeDefinition(
name="issueTime", required=False, type="time", fixed_value=None
),
AttributeDefinition(
name="issueDate", required=True, type="date", fixed_value=None
),
AttributeDefinition(
name="horizontalCRS", required=True, type="int32", fixed_value=None
),
AttributeDefinition(
name="epoch", required=False, type="string", fixed_value=None
),
AttributeDefinition(
name="westBoundLongitude",
required=True,
type="float32",
fixed_value=None,
),
AttributeDefinition(
name="eastBoundLongitude",
required=True,
type="float32",
fixed_value=None,
),
AttributeDefinition(
name="southBoundLatitude",
required=True,
type="float32",
fixed_value=None,
),
AttributeDefinition(
name="northBoundLatitude",
required=True,
type="float32",
fixed_value=None,
),
AttributeDefinition(
name="metadata", required=False, type="string", fixed_value=None
),
# 102_Dev1020
AttributeDefinition(
name="verticalCS", required=True, type="int32", fixed_value=6498
),
AttributeDefinition(
name="verticalCoordinateBase",
required=True,
type="enumeration",
fixed_value=2,
),
AttributeDefinition(
name="verticalDatumReference",
required=True,
type="enumeration",
fixed_value=1,
),
AttributeDefinition(
name="verticalDatum", required=True, type="uint16", fixed_value=None
),
]
self._log_check("102_Dev1002")
self._log_check("102_Dev1003")
self._log_check("102_Dev1004")
self._check_attributes("top level", f, topLevelAttributesList)
if _get_int_attr_or_none(f, "verticalCS"):
self._log_check("102_Dev1020")
self._validate_verticalCoordinateBase(f)
self._validate_verticalDatumReference(f)
self._validate_verticalDatum("top level", f)
self._validate_epoch(f)
self._validate_metadata(f, self.filename)
self._validate_horizontalCRS(f)
self._validate_bounds("top level", f)
if "BathymetryCoverage" in f.keys():
self._validate_BathymetryCoverage(f)
else:
self._log_check("102_Dev1026")
self._critical_error("Missing /BathymetryCoverage group")
if "QualityOfBathymetryCoverage" in f.keys():
self._validate_QualityOfBathymetryCoverage(f)
self.checks_done = sorted(self.checks_done)
def _validate_enumeration(self, group, attr_name, expected_values):
h5_type = group.attrs.get_id(attr_name).get_type()
if isinstance(h5_type, h5py.h5t.TypeEnumID):
if h5_type.get_nmembers() != len(expected_values):
self._warning(
f"Expected {len(expected_values)} members for enumeration {attr_name}"
)
else:
for code in expected_values:
try:
value = h5_type.enum_nameof(code).decode("utf-8")
except Exception:
value = None
self._warning(
f"Enumeration {attr_name}: did not find value for code {code}"
)
if value:
expected = expected_values[code]
if value != expected:
self._error(
f"Enumeration {attr_name}: for code {code}, found value {value}, whereas {expected} was expected"
)
def _validate_verticalCoordinateBase(self, f):
if "verticalCoordinateBase" in f.attrs:
expected_values = {
1: "seaSurface",
2: "verticalDatum",
3: "seaBottom",
}
self._validate_enumeration(f, "verticalCoordinateBase", expected_values)
def _validate_verticalDatumReference(self, f):
if "verticalDatumReference" in f.attrs:
expected_values = {
1: "s100VerticalDatum",
2: "EPSG",
}
self._validate_enumeration(f, "verticalDatumReference", expected_values)
def _validate_verticalDatum(self, ctxt_name, f):
verticalDatum = _get_int_attr_or_none(f, "verticalDatum")
if verticalDatum is not None and not (
(verticalDatum >= 1 and verticalDatum <= 30) or verticalDatum == 44
):
# 102_Dev1006
self._critical_error(
f"{ctxt_name} attribute verticalDatum has value '{verticalDatum}', whereas it should be in [1, 30] range or 44"
)
def _validate_epoch(self, f):
self._log_check("102_Dev1007")
epoch = _get_float_attr_or_none(f, "epoch")
if epoch and not (epoch >= 1980 and epoch <= 2100):
self._warning(f"Top level attribute epoch has invalid value: {epoch}")
def _validate_metadata(self, f, filename):
if "metadata" in f.attrs:
metadata = f.attrs["metadata"]
if isinstance(metadata, str) and metadata:
basename = os.path.basename(filename)
if basename.endswith(".h5") or basename.endswith(".H5"):
basename = basename[0:-3]
if metadata not in (f"MD_{basename}.xml", f"MD_{basename}.XML"):
self._critical_error(
f"Top level attribute metadata has value '{metadata}', whereas it should be empty, 'MD_{basename}.xml' or 'MD_{basename}.XML'"
)
def _validate_horizontalCRS(self, f):
self._log_check("102_Dev1009")
horizontalCRS = _get_int_attr_or_none(f, "horizontalCRS")
if horizontalCRS and not (
horizontalCRS in (4326, 5041, 5042)
or (horizontalCRS >= 32601 and horizontalCRS <= 32660)
or (horizontalCRS >= 32701 and horizontalCRS <= 32760)
):
self._critical_error(
f"Top level attribute 'horizontalCRS'={horizontalCRS} must be 4326, 5041, 5042 or in [32601,32660] or [32701,32760] ranges"
)
def _validate_bounds(self, ctxt_name, f):
west = _get_float_attr_or_none(f, "westBoundLongitude")
east = _get_float_attr_or_none(f, "eastBoundLongitude")
north = _get_float_attr_or_none(f, "northBoundLatitude")
south = _get_float_attr_or_none(f, "southBoundLatitude")
if (
west is not None
and east is not None
and north is not None
and south is not None
):
if not (west >= -180 and west <= 180):
self._warning(
f"{ctxt_name}: westBoundLongitude is not in [-180, 180] range"
)
if not (east >= -180 and east <= 180):
self._warning(
f"{ctxt_name}: eastBoundLongitude is not in [-180, 180] range"
)
if west >= east:
self._warning(
f"{ctxt_name}: westBoundLongitude is greater or equal to eastBoundLongitude"
)
if not (north >= -90 and north <= 90):
self._warning(
f"{ctxt_name}: northBoundLatitude is not in [-90, 90] range"
)
if not (south >= -90 and south <= 90):
self._warning(
f"{ctxt_name}: southBoundLatitude is not in [-90, 90] range"
)
if south >= north:
self._warning(
f"{ctxt_name}: southBoundLatitude is greater or equal to northBoundLatitude"
)
def _validate_group_f(self, rootGroup, group_f):
for key in group_f.keys():
if key not in (
"featureCode",
"BathymetryCoverage",
"QualityOfBathymetryCoverage",
):
self._warning(f"Unexpected element {key} in Group_F")
self._log_check("102_Dev1021")
if "featureCode" in group_f.keys():
self._validate_group_f_featureCode(
rootGroup, group_f, group_f["featureCode"]
)
else:
self._critical_error(
"No featureCode array in feature information group ('/Group_F/featureCode')"
)
def _validate_group_f_featureCode(self, rootGroup, group_f, featureCode):
self._log_check("102_Dev1021")
if not isinstance(featureCode, h5py.Dataset):
self._critical_error("'/Group_F/featureCode' is not a dataset")
return
if len(featureCode.shape) != 1:
self._critical_error(
"'/Group_F/featureCode' is not a one-dimensional dataset"
)
return
self._log_check("102_Dev1022")
values = set([v.decode("utf-8") for v in featureCode[:]])
if "BathymetryCoverage" not in values:
self._critical_error(
"Bathymetry data feature missing from featureCode array"
)
self._log_check("102_Dev1023")
if (
"QualityOfBathymetryCoverage" not in values
or "QualityOfBathymetryCoverage" not in rootGroup
):
self._warning("Quality feature not used")
self._log_check("102_Dev1024")
for value in values:
if value not in ("BathymetryCoverage", "QualityOfBathymetryCoverage"):
#
self._critical_error(
f"Group_F feature information must correspond to feature catalog. Did not expect {value}"
)
self._log_check("102_Dev1025")
if value not in group_f.keys():
self._critical_error(
f"Feature information dataset for feature type {value} missing"
)
self._log_check("102_Dev1026")
if value not in rootGroup.keys():
self._critical_error(f"No feature instances for feature type {value}")
if "BathymetryCoverage" in group_f.keys():
self._validate_group_f_BathymetryCoverage(group_f)
if "QualityOfBathymetryCoverage" in group_f.keys():
self._validate_group_f_QualityOfBathymetryCoverage(group_f)
def _validate_group_f_BathymetryCoverage(self, group_f):
self._log_check("102_Dev1027")
BathymetryCoverage = group_f["BathymetryCoverage"]
if not isinstance(BathymetryCoverage, h5py.Dataset):
self._critical_error("'/Group_F/BathymetryCoverage' is not a dataset")
elif BathymetryCoverage.shape not in ((1,), (2,)):
self._critical_error(
"'/Group_F/BathymetryCoverage' is not a one-dimensional dataset of shape 1 or 2"
)
elif BathymetryCoverage.dtype != [
("code", "O"),
("name", "O"),
("uom.name", "O"),
("fillValue", "O"),
("datatype", "O"),
("lower", "O"),
("upper", "O"),
("closure", "O"),
]:
self._critical_error(
"'/Group_F/BathymetryCoverage' has not expected data type"
)
else:
type = BathymetryCoverage.id.get_type()
assert isinstance(type, h5py.h5t.TypeCompoundID)
for member_idx in range(type.get_nmembers()):
subtype = type.get_member_type(member_idx)
if not isinstance(subtype, h5py.h5t.TypeStringID):
self._critical_error(
f"Member of index {member_idx} in /Group_F/BathymetryCoverage is not a string"
)
return
if not subtype.is_variable_str():
self._critical_error(
f"Member of index {member_idx} in /Group_F/BathymetryCoverage is not a variable length string"
)
values = BathymetryCoverage[:]
expected_values = [
(0, 0, "depth"),
(0, 1, "depth"),
(0, 2, "metres"),
(0, 3, "1000000"),
(0, 4, "H5T_FLOAT"),
(0, 5, "-14"),
(0, 6, "11050"),
(0, 7, "closedInterval"),
(1, 0, "uncertainty"),
(1, 1, "uncertainty"),
(1, 2, "metres"),
(1, 3, "1000000"),
(1, 4, "H5T_FLOAT"),
(1, 5, "0"),
(1, 6, ""),
(1, 7, "geSemiInterval"),
]
for row, col, expected_value in expected_values:
if row < BathymetryCoverage.shape[0]:
value = values[row][col].decode("utf-8")
if value != expected_value:
self._critical_error(
f"/Group_F/BathymetryCoverage: row {row}, {col}, got value '{value}', whereas '{expected_value}' is expected"
)
def _validate_group_f_QualityOfBathymetryCoverage(self, group_f):
self._log_check("102_Dev1027")
QualityOfBathymetryCoverage = group_f["QualityOfBathymetryCoverage"]
if not isinstance(QualityOfBathymetryCoverage, h5py.Dataset):
self._critical_error(
"'/Group_F/QualityOfBathymetryCoverage' is not a dataset"
)
elif QualityOfBathymetryCoverage.shape != (1,):
self._critical_error(
"'/Group_F/QualityOfBathymetryCoverage' is not a one-dimensional dataset of shape 1"
)
elif QualityOfBathymetryCoverage.dtype != [
("code", "O"),
("name", "O"),
("uom.name", "O"),
("fillValue", "O"),
("datatype", "O"),
("lower", "O"),
("upper", "O"),
("closure", "O"),
]:
self._critical_error(
"'/Group_F/QualityOfBathymetryCoverage' has not expected data type"
)
else:
type = QualityOfBathymetryCoverage.id.get_type()
assert isinstance(type, h5py.h5t.TypeCompoundID)
for member_idx in range(type.get_nmembers()):
subtype = type.get_member_type(member_idx)
if not isinstance(subtype, h5py.h5t.TypeStringID):
self._critical_error(
f"Member of index {member_idx} in /Group_F/QualityOfBathymetryCoverage is not a string"
)
return
if not subtype.is_variable_str():
self._critical_error(
f"Member of index {member_idx} in /Group_F/QualityOfBathymetryCoverage is not a variable length string"
)
values = QualityOfBathymetryCoverage[:]
expected_values = [
(0, 0, "iD"),
(0, 1, "ID"),
(0, 2, ""),
(0, 3, "0"),
(0, 4, "H5T_INTEGER"),
(0, 5, "1"),
(0, 6, ""),
(0, 7, "geSemiInterval"),
]
for row, col, expected_value in expected_values:
value = values[row][col].decode("utf-8")
if value != expected_value:
self._critical_error(
f"/Group_F/QualityOfBathymetryCoverage: row {row}, {col}, got value '{value}', whereas '{expected_value}' is expected"
)
def _validate_BathymetryCoverage(self, f):
BathymetryCoverage = f["BathymetryCoverage"]
if not isinstance(BathymetryCoverage, h5py.Group):
self._critical_error("/BathymetryCoverage is not a group")
return
# Cf Table 10-4 - Attributes of BathymetryCoverage feature container group
attr_list = [
AttributeDefinition(
name="dataCodingFormat",
required=True,
type="enumeration",
fixed_value=2,
),
AttributeDefinition(
name="dimension",
required=True,
type="uint8",
fixed_value=2,
),
AttributeDefinition(
name="commonPointRule",
required=True,
type="enumeration",
fixed_value=2,
),
AttributeDefinition(
name="horizontalPositionUncertainty",
required=True,
type="float32",
fixed_value=None,
),
AttributeDefinition(
name="verticalUncertainty",
required=True,
type="float32",
fixed_value=None,
),
AttributeDefinition(
name="numInstances",
required=True,
type="uint8",
fixed_value=None,
),
AttributeDefinition(
name="sequencingRule.type",
required=True,
type="enumeration",
fixed_value=1,
),
AttributeDefinition(
name="sequencingRule.scanDirection",
required=True,
type="string",
fixed_value=None,
),
AttributeDefinition(
name="interpolationType",
required=True,
type="enumeration",
fixed_value=1,
),
AttributeDefinition(
name="dataOffsetCode",
required=True,
type="enumeration",
fixed_value=5,
),
]
self._log_check("102_Dev2001")
self._check_attributes(
"BathymetryCoverage group", BathymetryCoverage, attr_list
)
numInstances = _get_int_attr_or_none(BathymetryCoverage, "numInstances")
if numInstances is not None:
if numInstances <= 0:
self._critical_error(
'/BathymetryCoverage["numInstances"] attribute value must be >= 1'
)
numInstances = None
if "commonPointRule" in BathymetryCoverage.attrs:
expected_values = {
1: "average",
2: "low",
3: "high",
4: "all",
}
self._validate_enumeration(
BathymetryCoverage, "commonPointRule", expected_values
)
if "dataCodingFormat" in BathymetryCoverage.attrs:
expected_values = {
1: "Fixed Stations",
2: "Regular Grid",
3: "Ungeorectified Grid",
4: "Moving Platform",
5: "Irregular Grid",
6: "Variable cell size",
7: "TIN",
8: "Fixed Stations (Stationwise)",
9: "Feature oriented Regular Grid",
}
self._validate_enumeration(
BathymetryCoverage, "dataCodingFormat", expected_values
)
if "interpolationType" in BathymetryCoverage.attrs:
expected_values = {
1: "nearestneighbor",
5: "bilinear",
6: "biquadratic",
7: "bicubic",
9: "barycentric",
10: "discrete",
}
self._validate_enumeration(
BathymetryCoverage, "interpolationType", expected_values
)
if "dataOffsetCode" in BathymetryCoverage.attrs:
expected_values = {
1: 'XMin, YMin ("Lower left") corner ("Cell origin")',
2: 'XMax, YMax ("Upper right") corner',
3: 'XMax, YMin ("Lower right") corner',
4: 'XMin, YMax ("Upper left") corner',
5: "Barycenter (centroid) of cell",
}
self._validate_enumeration(
BathymetryCoverage, "dataOffsetCode", expected_values
)
horizontalPositionUncertainty = _get_float_attr_or_none(
BathymetryCoverage, "horizontalPositionUncertainty"
)
if horizontalPositionUncertainty and not (
horizontalPositionUncertainty == -1.0 or horizontalPositionUncertainty >= 0
):
self._warning(
'/BathymetryCoverage["horizontalPositionUncertainty"] attribute value must be -1 or positive'
)
verticalUncertainty = _get_float_attr_or_none(
BathymetryCoverage, "verticalUncertainty"
)
if verticalUncertainty and not (
verticalUncertainty == -1.0 or verticalUncertainty >= 0
):
self._warning(
'/BathymetryCoverage["verticalUncertainty"] attribute value must be -1 or positive'
)
scanDirection_values = None
if "sequencingRule.scanDirection" in BathymetryCoverage.attrs:
scanDirection = BathymetryCoverage.attrs["sequencingRule.scanDirection"]
if isinstance(scanDirection, str):
# strip leading space. IMHO there should not be any, but
# the examples in the specification sometimes show one...
scanDirection_values = [x.lstrip() for x in scanDirection.split(",")]
self._log_check("102_Dev2011")
if len(scanDirection_values) != 2:
self._warning(
'/BathymetryCoverage["sequencingRule.scanDirection"] attribute should have 2 values'
)
elif "axisNames" in BathymetryCoverage.keys():
scanDirection_values_without_orientation = []
for v in scanDirection_values:
if v.startswith("-"):
scanDirection_values_without_orientation.append(v[1:])
else:
scanDirection_values_without_orientation.append(v)
scanDirection_values_without_orientation = set(
scanDirection_values_without_orientation
)
axisNames = BathymetryCoverage["axisNames"]
if (
isinstance(axisNames, h5py.Dataset)
and axisNames.shape == (2,)
and isinstance(axisNames.id.get_type(), h5py.h5t.TypeStringID)
):
axisNames_values = set(
[v.decode("utf-8") for v in axisNames[:]]
)
if scanDirection_values_without_orientation != axisNames_values:
self._warning(
f"Sequencing rule scanDirection contents ({scanDirection_values_without_orientation}) does not match axis names ({axisNames_values}"
)
# Check that QualityOfBathymetryCoverage has (almost) the same attributes as BathymetryCoverage
if "QualityOfBathymetryCoverage" in f.keys():
QualityOfBathymetryCoverage = f["QualityOfBathymetryCoverage"]
if not isinstance(QualityOfBathymetryCoverage, h5py.Group):
self._critical_error("/QualityOfBathymetryCoverage is not a group")
else:
attr_list[0] = AttributeDefinition(
name="dataCodingFormat",
required=True,
type="enumeration",
fixed_value=9,
)
self._log_check("102_Dev2002")
self._check_attributes(
"QualityOfBathymetryCoverage group",
QualityOfBathymetryCoverage,
attr_list,
)
self._validate_axisNames(f, BathymetryCoverage)
subgroups = set(
[
name
for name, item in BathymetryCoverage.items()
if isinstance(item, h5py.Group)
]
)
self._log_check("102_Dev2007")
if len(subgroups) == 0:
self._critical_error("/BathymetryCoverage has no groups")
else:
for i in range(1, len(subgroups) + 1):
expected_name = "BathymetryCoverage.%02d" % i
if expected_name not in subgroups:
self._critical_error(
"/BathymetryCoverage/{expected_name} group does not exist"
)
for name in subgroups:
if not name.startswith("BathymetryCoverage."):
self._warning(
"/BathymetryCoverage/{expected_name} is an unexpected group"
)
self._log_check("102_Dev2008")
if numInstances and len(subgroups) != numInstances:
self._critical_error(
f"/BathymetryCoverage has {len(subgroups)} groups whereas numInstances={numInstances}"
)
# Attributes and groups already checked above
self._log_check("102_Dev2012")
for name, item in BathymetryCoverage.items():
if isinstance(item, h5py.Dataset) and name != "axisNames":
self._warning(f"/BathymetryCoverage has unexpected dataset {name}")
if isinstance(item, h5py.Group) and name.startswith("BathymetryCoverage."):
self._validate_BathymetryCoverage_instance(f, BathymetryCoverage, item)
def _validate_BathymetryCoverage_instance(self, f, BathymetryCoverage, instance):
# Cf Table 10-6 - Attributes of BathymetryCoverage feature instance group
attr_list = [
AttributeDefinition(
name="westBoundLongitude",
required=False,
type="float32",
fixed_value=None,
),
AttributeDefinition(
name="eastBoundLongitude",
required=False,
type="float32",
fixed_value=None,