-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathpysnirf2.py
More file actions
7216 lines (6328 loc) · 310 KB
/
Copy pathpysnirf2.py
File metadata and controls
7216 lines (6328 loc) · 310 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
# -*- coding: utf-8 -*-
"""Module for reading, writing and validating SNIRF files.
SNIRF files are HDF5 files designed to facilitate the sharing of near-infrared
spectrocopy data. Their specification is defined at https://github.com/fNIRS/snirf.
This library wraps each HDF5 Group and offers a Pythonic interface on lists
of like-Groups which the SNIRF specification calls "indexed Groups".
Example:
Load a file:
>>> from snirf import Snirf
>>> with Snirf(<filename>) as s:
...
Maintained by the Boston University Neurophotonics Center
"""
from abc import ABC, abstractmethod
import h5py
import os
import sys
import numpy as np
from warnings import warn
from collections.abc import MutableSequence
import uuid
import logging
from typing import Tuple
import time
import io
import json
import copy
try:
from snirf.__version__ import __version__ as __version__
except Exception:
warn('Failed to load pysnirf2 library version')
__version__ = '0.0.0'
if sys.version_info[0] < 3:
raise ImportError('pysnirf2 requires Python > 3')
class SnirfFormatError(Warning):
"""Raised when SNIRF-specific error prevents file from loading or saving properly."""
pass
# Colored prints for validation output to console
try:
import termcolor
import colorama
if os.name == 'nt':
colorama.init()
_printr = lambda x: termcolor.cprint(x, 'red')
_printg = lambda x: termcolor.cprint(x, 'green')
_printb = lambda x: termcolor.cprint(x, 'blue')
_printm = lambda x: termcolor.cprint(x, 'magenta')
_colored = termcolor.colored
except ImportError:
_printr = lambda x: print(x)
_printg = lambda x: print(x)
_printb = lambda x: print(x)
_printm = lambda x: print(x)
_colored = lambda x, c: x
def _isfilelike(o: object) -> bool:
"""Returns True if object is an instance of a file-like object like `io.IOBase` or `io.BufferedIOBase`."""
return any([
isinstance(o, io.TextIOBase),
isinstance(o, io.BufferedIOBase),
isinstance(o, io.RawIOBase),
isinstance(o, io.IOBase)
])
_loggers = {}
def _create_logger(name, log_file, level=logging.INFO):
if name in _loggers.keys():
return _loggers[name]
if log_file == '' or log_file is None:
handler = logging.NullHandler()
else:
handler = logging.FileHandler(log_file)
handler.setFormatter(
logging.Formatter('%(asctime)s | %(name)s v%(version)s | %(message)s'))
logger = logging.getLogger(name)
logger.setLevel(level)
logger.addHandler(handler)
logger = logging.LoggerAdapter(logger, {'version': __version__})
_loggers[name] = logger
return logger
def _close_logger(logger: logging.LoggerAdapter):
if type(logger) is logging.LoggerAdapter:
handlers = logger.logger.handlers[:]
elif type(logger) is logging.Logger:
handlers = logger.handlers[:]
else:
raise TypeError(
'logger must be logging.LoggerAdapter or logging.Logger')
for handler in handlers:
handler.close()
# Package-wide logger
_logfile = os.path.join(os.path.dirname(os.path.abspath(__file__)),
'pysnirf2.log')
if os.path.exists(_logfile):
try:
if (time.time() - os.path.getctime(_logfile)
) / 86400 > 10: # Keep logs for only 10 days
os.remove(_logfile)
_logger = _create_logger('pysnirf2', _logfile)
except (FileNotFoundError, PermissionError):
_logger = _create_logger('pysnirf2', None) # Null logger
else:
_logger = _create_logger('pysnirf2',
os.path.join(os.getcwd(), 'pysnirf2.log'))
_logger.info('Library loaded by process {}'.format(os.getpid()))
# -- methods to cast data prior to writing to and after reading from h5py interfaces------
_varlen_str_type = h5py.string_dtype(
encoding='ascii',
length=None) # Length=None creates HDF5 variable length string
_DTYPE_FLOAT32 = 'f4'
_DTYPE_FLOAT64 = 'f8'
_DTYPE_INT32 = 'i4'
_DTYPE_INT64 = 'i8'
_DTYPE_UINT32 = 'u4'
_DTYPE_UINT64 = 'u8'
_DTYPE_FIXED_LEN_STR = 'S' # Not sure how robust this is, but fixed length strings will always at least contain S
_DTYPE_VAR_LEN_STR = 'O' # Variable length string
_INT_DTYPES = [int, np.int32, np.int64]
_FLOAT_DTYPES = [float, np.float64]
_STR_DTYPES = [str, np.bytes_]
# -- Dataset creators ---------------------------------------
def _get_padded_shape(name: str, data: np.ndarray,
desired_ndim: int) -> np.ndarray:
"""Utility function which pads data shape to ndim."""
if desired_ndim is None:
return data.shape
if data.ndim == desired_ndim:
return np.shape(data)
elif desired_ndim > data.ndim:
return np.concatenate(
[data.shape,
np.ones(int(desired_ndim) - int(data.ndim))])
elif desired_ndim < data.ndim:
flattened = [x for x in data.shape if x > 1]
if len(flattened) == desired_ndim:
warn(
"Dataset '{}' must have ndim {} but had erroneous shape {}. Singular dimensions were removed."
.format(name, desired_ndim, data.shape))
return flattened
else:
raise SnirfFormatError(
"Cannot coerce Dataset '{}' with shape {} to the required {} dimension(s)"
.format(name, data.shape, desired_ndim))
def _create_dataset(file: h5py.File, name: str, data):
"""Saves a variable to an h5py.File on disk as a new Dataset.
Discerns the type of a given variable and adds it to an h5py File as a
new dataset with SNIRF compliant formatting.
Args:
file: An open `h5py.File` or `h5py.Group` instance to which the Dataset will be added
name (str): The name of the new dataset. Can be a relative HDF5 name.
data: The variable to save to the Dataset.
Returns:
A dict mapping keys to the corresponding table row data
fetched. Each row is represented as a tuple of strings. For
example:
Raises:
TypeError: The data could not be mapped to a SNIRF compliant h5py format.
"""
if data is None: # Don't create dataset from None
return
data = np.array(data) # Cast to numpy type to identify
if data.size > 1:
dtype = data[0].dtype
print(dtype)
if any([dtype == t for t in _INT_DTYPES]): # int
return _create_dataset_int_array(file, name, data)
elif any([dtype == t for t in _FLOAT_DTYPES]): # float
return _create_dataset_float_array(file, name, data)
elif any([dtype == t for t in _STR_DTYPES]) or any(
[t in dtype.str for t in ['U', 'S']]): # string
return _create_dataset_string_array(file, name, data)
dtype = data.dtype
if any([dtype == t for t in _INT_DTYPES]): # int
return _create_dataset_int(file, name, data)
elif any([dtype == t for t in _FLOAT_DTYPES]): # float
return _create_dataset_float(file, name, data)
elif any([dtype == t for t in _STR_DTYPES]) or any(
[t in dtype.str for t in ['U', 'S']]): # string
return _create_dataset_string(file, name, data)
raise TypeError(
"Unrecognized data type '" + str(dtype) +
"'. Please provide an int, float, or str, or an iterable of these.")
def _create_dataset_string(file: h5py.File, name: str, data: str):
"""Saves a variable to an h5py.File on disk as a new SNIRF compliant variable length string Dataset.
Args:
file: An open `h5py.File` or `h5py.Group` instance to which the Dataset will be added
name (str): The name of the new dataset. Can be a relative HDF5 name.
data: The string to save to the Dataset.
Returns:
An h5py.Dataset instance created
"""
if data is None:
return None
return file.create_dataset(name, dtype=_varlen_str_type, data=str(data))
def _create_dataset_int(file: h5py.File, name: str, data: int):
"""Saves a variable to an h5py.File on disk as a new SNIRF compliant integer Dataset.
Args:
file: An open `h5py.File` or `h5py.Group` instance to which the Dataset will be added
name (str): The name of the new dataset. Can be a relative HDF5 name.
data: The integer to save to the Dataset.
Returns:
An h5py.Dataset instance created
"""
if data is None:
return None
return file.create_dataset(name, dtype=_DTYPE_INT32, data=int(data))
def _create_dataset_float(file: h5py.File, name: str, data: float):
"""Saves a variable to an h5py.File on disk as a new SNIRF compliant float Dataset.
Args:
file: An open `h5py.File` or `h5py.Group` instance to which the Dataset will be added
name (str): The name of the new dataset. Can be a relative HDF5 name.
data: The float to save to the Dataset.
Returns:
An h5py.Dataset instance created
"""
if data is None:
return None
return file.create_dataset(name, dtype=_DTYPE_FLOAT64, data=float(data))
def _create_dataset_string_array(file: h5py.File,
name: str,
data: np.ndarray,
ndim=None):
"""Saves a NumPy array to an h5py.File on disk as a new SNIRF compliant array of variable length strings.
Args:
file: An open `h5py.File` or `h5py.Group` instance to which the Dataset will be added
name (str): The name of the new dataset. Can be a relative HDF5 name.
data: The array to save to the Dataset.
Returns:
An h5py.Dataset instance created
"""
try:
array = np.array(data).astype('O')
except TypeError as e:
warn('Could not cast {} array to numpy "O": {}'.format(name, e))
return
shape = _get_padded_shape(name, array, ndim)
return file.create_dataset(name, dtype=_varlen_str_type, data=array)
def _create_dataset_int_array(file: h5py.File,
name: str,
data: np.ndarray,
ndim=None):
"""Saves a NumPy array to an h5py.File on disk as a new SNIRF compliant array of 32-bit integers.
Args:
file: An open `h5py.File` or `h5py.Group` instance to which the Dataset will be added
name (str): The name of the new dataset. Can be a relative HDF5 name.
data: The array to save to the Dataset.
Returns:
An h5py.Dataset instance created
"""
try:
array = np.array(data).astype(int)
except TypeError as e:
warn('Could not cast {} array to int: {}'.format(name, e))
return
shape = _get_padded_shape(name, array, ndim)
return file.create_dataset(name, dtype=_DTYPE_INT32, data=array)
def _create_dataset_float_array(file: h5py.File,
name: str,
data: np.ndarray,
ndim=None):
"""Saves a NumPy array to an h5py.File on disk as a new SNIRF compliant array of 64-bit floats.
Args:
file: An open `h5py.File` or `h5py.Group` instance to which the Dataset will be added
name (str): The name of the new dataset. Can be a relative HDF5 name.
data: The array to save to the Dataset.
Returns:
An h5py.Dataset instance created
"""
try:
array = np.array(data).astype(float)
except TypeError as e:
warn('Could not cast {} array to float: {}'.format(name, e))
return
shape = _get_padded_shape(name, array, ndim)
return file.create_dataset(name,
dtype=_DTYPE_FLOAT64,
shape=shape,
data=array)
# -- Dataset readers ---------------------------------------
def _read_dataset(dataset: h5py.Dataset):
"""Converts the contents of an h5py Dataset into a NumPy object.
Converts the contents of an `h5py.Dataset` into a NumPy object after
attempting to determine the appropriate SNIRF compliant type.
Args:
dataset (h5py.Dataset): An open` h5py.Dataset` instance.
Returns:
A dict mapping keys to the corresponding table row data
fetched. Each row is represented as a tuple of strings. For
example:
Raises:
TypeError: The Dataset could not be mapped to a SNIRF compliant type.
"""
if type(dataset) is not h5py.Dataset:
raise TypeError("'dataset' must be type h5py.Dataset")
if dataset.size > 1:
if _DTYPE_FIXED_LEN_STR in dataset.dtype.str or _DTYPE_VAR_LEN_STR in dataset.dtype.str:
return _read_string_array(dataset)
elif _DTYPE_INT32 in dataset.dtype.str or _DTYPE_INT64 in dataset.dtype.str:
return _read_int_array(dataset)
elif _DTYPE_FLOAT32 in dataset.dtype.str or _DTYPE_FLOAT64 in dataset.dtype.str:
return _read_float_array(dataset)
else:
if _DTYPE_FIXED_LEN_STR in dataset.dtype.str or _DTYPE_VAR_LEN_STR in dataset.dtype.str:
return _read_string(dataset)
elif _DTYPE_INT32 in dataset.dtype.str or _DTYPE_INT64 in dataset.dtype.str:
return _read_int(dataset)
elif _DTYPE_FLOAT32 in dataset.dtype.str or _DTYPE_FLOAT64 in dataset.dtype.str:
return _read_float(dataset)
raise TypeError(
"Dataset dtype='" + str(dataset.dtype) +
"' not recognized. Expecting dtype to contain one of these: " + str([
_DTYPE_FIXED_LEN_STR, _DTYPE_VAR_LEN_STR, _DTYPE_INT32,
_DTYPE_INT64, _DTYPE_FLOAT32, _DTYPE_FLOAT64
]))
def _read_string(dataset: h5py.Dataset) -> str:
"""Reads the contents of an `h5py.Dataset` to a `str`.
Args:
dataset (h5py.Dataset): An open` h5py.Dataset` instance
Returns:
A `str`
"""
if type(dataset) is not h5py.Dataset:
raise TypeError("'dataset' must be type h5py.Dataset")
# Because many SNIRF files are saved with string values in length 1 arrays
try:
if dataset.ndim > 0:
return str(dataset[0].decode('ascii'))
else:
return str(dataset[()].decode('ascii'))
except AttributeError: # If we expected a string and got something else, `decode` isn't there
warn(
'Expected dataset {} to be stringlike, is {} conversion may be incorrect'
.format(dataset.name, dataset.dtype), SnirfFormatError)
return str(dataset[0])
def _read_int(dataset: h5py.Dataset) -> int:
"""Reads the contents of an `h5py.Dataset` to an `int`.
Args:
dataset (h5py.Dataset): An open` h5py.Dataset` instance
Returns:
An `int`
"""
if type(dataset) is not h5py.Dataset:
raise TypeError("'dataset' must be type h5py.Dataset")
if dataset.ndim > 0:
return int(dataset[0])
else:
return int(dataset[()])
def _read_float(dataset: h5py.Dataset) -> float:
"""Reads the contents of an `h5py.Dataset` to a `float`.
Args:
dataset (h5py.Dataset): An open` h5py.Dataset` instance
Returns:
A `float`
"""
if type(dataset) is not h5py.Dataset:
raise TypeError("'dataset' must be type h5py.Dataset")
if dataset.ndim > 0:
return float(dataset[0])
else:
return float(dataset[()])
def _read_string_array(dataset: h5py.Dataset) -> np.ndarray:
"""Reads the contents of an `h5py.Dataset` to an array of `dtype=str`.
Args:
dataset (h5py.Dataset): An open` h5py.Dataset` instance
Returns:
A numpy array `astype(str)`
"""
if type(dataset) is not h5py.Dataset:
raise TypeError("'dataset' must be type h5py.Dataset")
return np.array(dataset).astype(str)
def _read_int_array(dataset: h5py.Dataset) -> np.ndarray:
"""Reads the contents of an `h5py.Dataset` to an array of `dtype=int`.
Args:
dataset (h5py.Dataset): An open` h5py.Dataset` instance
Returns:
A numpy array `astype(int)`
"""
if type(dataset) is not h5py.Dataset:
raise TypeError("'dataset' must be type h5py.Dataset")
return np.array(dataset).astype(int)
def _read_float_array(dataset: h5py.Dataset) -> np.ndarray:
"""Reads the contents of an `h5py.Dataset` to an array of `dtype=float`.
Args:
dataset (h5py.Dataset): An open` h5py.Dataset` instance
Returns:
A numpy array astype(float)
"""
if type(dataset) is not h5py.Dataset:
raise TypeError("'dataset' must be type h5py.Dataset")
return np.array(dataset).astype(float)
# -- Validation types ---------------------------------------
_SEVERITY_LEVELS = {
0: 'OK ',
1: 'INFO ',
2: 'WARNING',
3: 'FATAL ',
}
_SEVERITY_COLORS = {
0: 'green',
1: 'blue',
2: 'magenta',
3: 'red',
}
_CODES = {
# Errors (Severity 1)
'INVALID_FILE_NAME': (1, 3, 'Valid SNIRF files must end with .snirf'),
'INVALID_FILE': (2, 3,
'The file could not be opened, or the validator crashed'),
'REQUIRED_DATASET_MISSING':
(3, 3, 'A required dataset is missing from the file'),
'REQUIRED_GROUP_MISSING': (4, 3,
'A required Group is missing from the file'),
'REQUIRED_INDEXED_GROUP_EMPTY':
(5, 3,
'At least one member of the indexed group must be present in the file'),
'INVALID_DATASET_TYPE':
(6, 3, 'An HDF5 Dataset is not stored in the specified format'),
'INVALID_DATASET_SHAPE':
(7, 3,
'An HDF5 Dataset is not stored in the specified shape. Strings and scalars should never be stored as arrays of length 1.'
),
'INVALID_MEASUREMENTLIST':
(8, 3,
'The number of measurementList elements does not match the second dimension of dataTimeSeries'
),
'INVALID_MEASUREMENTLISTS':
(9, 3,
'The length of at least one measurementLists element does not match the second dimension of dataTimeSeries'
),
'INVALID_TIME':
(10, 3,
'The length of the data/time vector does not match the first dimension of data/dataTimeSeries'
),
'INVALID_STIM_DATALABELS':
(11, 3,
'The length of stim/dataLabels exceeds the second dimension of stim/data'
),
'INVALID_SOURCE_INDEX':
(12, 3,
'measurementList(s)/sourceIndex exceeds length of probe/sourceLabels or the first axis of source position data'
),
'INVALID_DETECTOR_INDEX':
(13, 3,
'measurementList(s)/detectorIndex exceeds length of probe/detectorLabels or the first axis of source position data'
),
'INVALID_WAVELENGTH_INDEX':
(14, 3,
'measurementList(s)/waveLengthIndex exceeds length of probe/wavelengths'),
'NEGATIVE_INDEX': (15, 3, 'An index is negative'),
# Warnings (Severity 2)
'INDEX_OF_ZERO': (16, 2, 'An index of zero is usually undefined'),
'UNRECOGNIZED_GROUP': (17, 2,
'An unspecified Group is a part of the file'),
'UNRECOGNIZED_DATASET':
(18, 2,
'An unspecified Dataset is a part of the file in an unexpected place'),
'UNRECOGNIZED_DATA_TYPE_LABEL':
(19, 3,
'measurementList(s)/dataTypeLabel is not one of the recognized values listed in the Appendix'
),
'UNRECOGNIZED_DATA_TYPE':
(20, 3,
'measurementList(s)/dataType is not one of the recognized values listed in the Appendix'
),
'INT_64':
(21, 2,
'The SNIRF specification limits users to the use of 32 bit native integer types'
),
'UNRECOGNIZED_COORDINATE_SYSTEM':
(22, 2,
'The identifying string of the coordinate system was not recognized.'),
'NO_COORDINATE_SYSTEM_DESCRIPTION':
(23, 2,
"The coordinate system was unrecognized or 'Other' but lacks a probe/coordinateSystemDescription"
),
'FIXED_LENGTH_STRING':
(24, 2,
'The use of fixed-length strings is discouraged and may be banned by a future spec version. Rewrite this file with pysnirf2 to use variable length strings'
),
# Info (Severity 1)
'OPTIONAL_GROUP_MISSING': (25, 1,
'Missing an optional Group in this location'),
'OPTIONAL_DATASET_MISSING': (26, 1,
'Missing optional Dataset in this location'),
'OPTIONAL_INDEXED_GROUP_EMPTY':
(27, 1, 'The optional indexed group has no elements'),
# OK (Severity 0)
'OK': (28, 0, 'No issues detected'),
}
class ValidationIssue:
"""Information about the validity of a given SNIRF file location.
Properties:
location: A relative HDF5 name corresponding to the location of the issue
name: A string describing the issue. Must be predefined in `_CODES`
id: An integer corresponding to the predefined error type
severity: An integer ranking the serverity level of the issue.
0 OK, Nothing remarkable
1 Potentially useful `INFO`
2 `WARNING`, the file is valid but exhibits undefined behavior or features marked deprecation
3 `FATAL`, The file is invalid.
message: A string containing a more verbose description of the issue
"""
def __init__(self, name: str, location: str):
self.location = location # A location in the Snirf file matching an HDF5 name
self.name = name # The name of the issue, a key in _CODES above
self.id = _CODES[name][0] # The ID of the issue
self.severity = _CODES[name][1] # The severity level of the issue
self.message = _CODES[name][2] # A string describing the issue
def __repr__(self):
s = super().__repr__()
s += '\nlocation: ' + self.location + '\nseverity: '
s += str(self.severity).ljust(4) + _SEVERITY_LEVELS[self.severity]
s += '\nname: ' + str(
self.id).ljust(4) + self.name + '\nmessage: ' + self.message
return s
def dictize(self):
"""Return dictionary representation of Issue."""
return {
'location': self.location,
'name': self.name,
'id': self.id,
'severity': self.severity,
'message': self.message
}
class ValidationResult:
"""The result of Snirf file validation routines.
Validation results in a list of issues. Each issue records information about
the validity of each location (each named Dataset and Group) in a SNIRF file.
ValidationResult organizes the issues catalogued during validation and affords interfaces
to retrieve and display them.
```
<ValidationResult> = <Snirf instance>.validate()
<ValidationResult> = validateSnirf(<path>)
```
"""
def __init__(self):
"""`ValidationResult` should only be created by a `Snirf` instance's `validate` method."""
self._issues = []
self._locations = []
def __bool__(self):
return self.is_valid()
def is_valid(self) -> bool:
"""Returns True if no `FATAL` issues were catalogued during validation."""
for issue in self._issues:
if issue.severity > 2:
return False
return True
@property
def issues(self):
"""A comprehensive list of all `ValidationIssue` instances for the result."""
return self._issues
@property
def locations(self):
"""A list of the HDF5 location associated with each issue."""
return self._locations
@property
def codes(self):
"""A list of each unique code name associated with all catalogued issues."""
return list(set([issue.name for issue in self._issues]))
@property
def errors(self):
"""A list of the `FATAL` issues catalogued during validation."""
errors = []
for issue in self._issues:
if issue.severity == 3:
errors.append(issue)
return errors
@property
def warnings(self):
"""A list of the `WARNING` issues catalogued during validation."""
warnings = []
for issue in self._issues:
if issue.severity == 2:
warnings.append(issue)
return warnings
@property
def info(self):
"""A list of the `INFO` issues catalogued during validation."""
info = []
for issue in self._issues:
if issue.severity == 1:
info.append(issue)
return info
def serialize(self, indent=4):
"""Render serialized JSON ValidationResult."""
d = {}
for issue in self._issues:
d[issue.location] = issue.dictize()
return json.dumps(d, indent=indent)
def display(self, severity=2):
"""Reads the contents of an `h5py.Dataset` to an array of `dtype=str`.
Args:
severity: An `int` which sets the minimum severity message to
display. Default is 2.
severity=0 All messages will be shown, including `OK`
severity=1 Prints `INFO`, `WARNING`, and `FATAL` messages
severity=2 Prints `WARNING` and `FATAL` messages
severity=3 Prints only `FATAL` error messages
"""
try:
longest_key = max([len(key) for key in self.locations])
longest_code = max([len(code) for code in self.codes])
except ValueError:
print('Empty ValidationResult: nothing to display')
s = repr(self) + '\n'
printed = [0, 0, 0, 0]
for issue in self._issues:
sev = issue.severity
printed[sev] += 1
if sev >= severity:
s += issue.location.ljust(
longest_key) + ' ' + _SEVERITY_LEVELS[
sev] + ' ' + issue.name.ljust(longest_code) + '\n'
print(s)
for i in range(0, severity):
[_printg, _printb, _printm,
_printr][i]('Found ' + str(printed[i]) + ' ' +
_colored(_SEVERITY_LEVELS[i], _SEVERITY_COLORS[i]) +
' (hidden)')
for i in range(severity, 4):
[_printg, _printb, _printm,
_printr][i]('Found ' + str(printed[i]) + ' ' +
_colored(_SEVERITY_LEVELS[i], _SEVERITY_COLORS[i]))
i = int(self.is_valid())
[_printr, _printg][i]('\nFile is ' + ['INVALID', 'VALID'][i])
def _add(self, location, key):
if key not in _CODES.keys():
raise KeyError("Invalid code '" + key + "'")
if location not in self: # only one issue per HDF5 name
issue = ValidationIssue(key, location)
self._locations.append(location)
self._issues.append(issue)
def __contains__(self, key):
for issue in self._issues:
if issue.location == key:
return True
return False
def __getitem__(self, key):
for issue in self._issues:
if issue.location == key:
return issue
raise KeyError("'" + key + "' not in issues list")
def __repr__(self):
return object.__repr__(self) + ' is_valid ' + str(self.is_valid())
# -- Validation functions ---------------------------------------
def _validate_string(dataset: h5py.Dataset) -> str:
"""Determines an issue code (as predefined in `_CODES`) based on the contents an `h5py.Dataset` instance..
Args:
dataset (h5py.Dataset): An open` h5py.Dataset` instance
Returns:
An issue code describing the validity of the dataset based on its format and shape
"""
if dataset is None:
return 'REQUIRED_DATASET_MISSING'
if type(dataset) is not h5py.Dataset:
raise TypeError("'dataset' must be type h5py.Dataset")
if dataset.size > 1 or dataset.ndim > 0:
return 'INVALID_DATASET_SHAPE'
if _DTYPE_VAR_LEN_STR in dataset.dtype.str:
return 'OK'
elif _DTYPE_FIXED_LEN_STR in dataset.dtype.str:
return 'FIXED_LENGTH_STRING'
else:
return 'INVALID_DATASET_TYPE'
def _validate_int(dataset: h5py.Dataset) -> str:
"""Determines an issue code (as predefined in `_CODES`) based on the contents an `h5py.Dataset` instance.
Args:
dataset (h5py.Dataset): An open` h5py.Dataset` instance
Returns:
An issue code describing the validity of the dataset based on its format and shape
"""
if dataset is None:
return 'REQUIRED_DATASET_MISSING'
if type(dataset) is not h5py.Dataset:
raise TypeError("'dataset' must be type h5py.Dataset")
if dataset.size > 1 or dataset.ndim > 0:
return 'INVALID_DATASET_SHAPE'
if _DTYPE_INT32 in dataset.dtype.str:
return 'OK'
if _DTYPE_UINT32 in dataset.dtype.str:
return 'OK'
if _DTYPE_INT64 in dataset.dtype.str:
return 'OK'
if _DTYPE_UINT64 in dataset.dtype.str:
return 'OK'
else:
return 'INVALID_DATASET_TYPE'
def _validate_float(dataset: h5py.Dataset) -> str:
"""Determines an issue code (as predefined in `_CODES`) based on the contents an `h5py.Dataset` instance.
Args:
dataset (h5py.Dataset): An open` h5py.Dataset` instance
Returns:
An issue code describing the validity of the dataset based on its format and shape
"""
if dataset is None:
return 'REQUIRED_DATASET_MISSING'
if type(dataset) is not h5py.Dataset:
raise TypeError("'dataset' must be type h5py.Dataset")
if dataset.size > 1 or dataset.ndim > 0:
return 'INVALID_DATASET_SHAPE'
if _DTYPE_FLOAT32 in dataset.dtype.str or _DTYPE_FLOAT64 in dataset.dtype.str:
return 'OK'
else:
return 'INVALID_DATASET_TYPE'
def _validate_string_array(dataset: h5py.Dataset, ndims=[1]) -> str:
"""Determines an issue code (as predefined in `_CODES`) based on the contents an `h5py.Dataset` instance.
Args:
dataset (h5py.Dataset): An open` h5py.Dataset` instance
Returns:
An issue code describing the validity of the dataset based on its format and shape
"""
if dataset is None:
return 'REQUIRED_DATASET_MISSING'
if type(dataset) is not h5py.Dataset:
raise TypeError("'dataset' must be type h5py.Dataset")
if dataset.ndim not in ndims:
return 'INVALID_DATASET_SHAPE'
if _DTYPE_VAR_LEN_STR in dataset.dtype.str:
return 'OK'
elif _DTYPE_FIXED_LEN_STR in dataset.dtype.str:
return 'FIXED_LENGTH_STRING'
else:
return 'INVALID_DATASET_TYPE'
def _validate_int_array(dataset: h5py.Dataset, ndims=[1]) -> str:
"""Determines an issue code (as predefined in `_CODES`) based on the contents an `h5py.Dataset` instance.
Args:
dataset (h5py.Dataset): An open` h5py.Dataset` instance
Returns:
An issue code describing the validity of the dataset based on its format and shape
"""
if dataset is None:
return 'REQUIRED_DATASET_MISSING'
if type(dataset) is not h5py.Dataset:
raise TypeError("'dataset' must be type h5py.Dataset")
if dataset.ndim not in ndims:
return 'INVALID_DATASET_SHAPE'
if _DTYPE_INT32 in dataset.dtype.str:
return 'OK'
if _DTYPE_INT64 in dataset.dtype.str:
return 'INT_64'
else:
return 'INVALID_DATASET_TYPE'
def _validate_float_array(dataset: h5py.Dataset, ndims=[1]) -> str:
"""Determines an issue code (as predefined in `_CODES`) based on the contents an `h5py.Dataset` instance.
Args:
dataset (h5py.Dataset): An open` h5py.Dataset` instance
Returns:
An issue code describing the validity of the dataset based on its format and shape
"""
if dataset is None:
return 'REQUIRED_DATASET_MISSING'
if type(dataset) is not h5py.Dataset:
raise TypeError("'dataset' must be type h5py.Dataset")
if dataset.ndim != ndims[0]:
return 'INVALID_DATASET_SHAPE'
if _DTYPE_FLOAT32 in dataset.dtype.str or _DTYPE_FLOAT64 in dataset.dtype.str:
return 'OK'
else:
return 'INVALID_DATASET_TYPE'
# -----------------------------------------
class SnirfConfig:
"""Structure containing Snirf-wide data and settings.
Properties:
logger (logging.Logger): The logger that the Snirf instance writes to
dynamic_loading (bool): If True, data is loaded from the HDF5 file only on access via property
"""
def __init__(self):
self.logger: logging.Logger = _logger # The logger that the interface will write to
self.dynamic_loading: bool = False # If False, data is loaded in the constructor, if True, data is loaded on access
self.fmode: str = 'w' # 'w' or 'r', mode to open HDF5 file with
# Placeholder for a Dataset that is not on disk or in memory
class _AbsentDatasetType():
pass
# Placeholder for a Group that is not on disk or in memory
class _AbsentGroupType():
pass
# Placeholder for a Dataset that is available only on disk in a dynamic_loading=True wrapper
class _PresentDatasetType():
pass
# Instantiate faux singletons
_AbsentDataset = _AbsentDatasetType()
_AbsentGroup = _AbsentGroupType()
_PresentDataset = _PresentDatasetType()
class Group(ABC):
def __init__(self, varg, cfg: SnirfConfig):
"""Wrapper for an HDF5 Group element defined by SNIRF.
Base class for an HDF5 Group element defined by SNIRF. Must be created with a
Group ID or string specifying a complete path relative to file root--in
the latter case, the wrapper will not correspond to a real HDF5 group on
disk until `_save()` (with no arguments) is executed for the first time
Args:
varg (h5py.h5g.GroupID or str): Either a string which maps to a future Group location or an ID corresponding to a current one on disk
cfg (SnirfConfig): Injected configuration of parent `Snirf` instance
"""
self._cfg = cfg
if type(
varg
) is str: # If a Group wrapper is created prior to a save to HDF Group object
self._h = {}
self._location = varg
elif isinstance(varg, h5py.h5g.GroupID
): # If Group is created based on an HDF Group object
self._h = h5py.Group(varg)
self._location = self._h.name
else:
raise TypeError('must initialize ' + self.__class__.__name__ +
' with a Group ID or string, not ' +
str(type(varg)))
def save(self, *args):
"""Group level save to a SNIRF file on disk.
Args:
args (str or h5py.File): A path to a closed SNIRF file on disk or an open `h5py.File` instance
Examples:
save can be called on a Group already on disk to overwrite the current contents:
>>> mysnirf.nirs[0].probe.save()
or using a new filename to write the Group there:
>>> mysnirf.nirs[0].probe.save(<new destination>)
"""
if len(args) > 0:
if type(args[0]) is h5py.File:
self._cfg.logger.info('Group-level save of %s in %s',
self.location, self.filename)
self._save(args[0])
elif type(args[0]) is str:
path = args[0]
if not path.endswith('.snirf'):
path += '.snirf'
if os.path.exists(path):
file = h5py.File(path, 'w')
else:
raise FileNotFoundError(
"No such SNIRF file '" + path +
"'. Create a SNIRF file before attempting to save a Group to it."
)
self._cfg.logger.info(