Repository navigation
Expand file tree
/
Copy pathsnirfvalidate.m
More file actions
1068 lines (980 loc) · 41.8 KB
/
Copy pathsnirfvalidate.m
File metadata and controls
1068 lines (980 loc) · 41.8 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
function [isvalid, issues] = snirfvalidate(fname, varargin)
%
% isvalid=snirfvalidate(fname)
% or
% [isvalid, issues]=snirfvalidate(fname, 'Param1',value1, 'Param2',value2,...)
%
% Validate an HDF5 based SNIRF file against the SNIRF specification:
% https://github.com/fNIRS/snirf
%
% author: Qianqian Fang (q.fang <at> neu.edu)
%
% The file is checked in four passes
% 1. storage: the HDF5 type, string encoding and dataspace rank of every
% dataset, which loadh5 returns along with the data
% 2. schema: the data loaded by loadh5 are validated against
% schema/snirf_schema.json; numeric datasets larger than MaxBytes are
% not read, and are validated by their type and size only
% 3. rules: checks that span several fields, such as the index ranges in
% the measurement list and the lengths of the time vectors
% 4. naming: the numbering of indexed groups (nirs, data, stim, aux and
% measurementList)
%
% input:
% fname: the SNIRF (.snirf) file to validate
% options: (optional) param/value pairs
% 'MaxBytes': [1e6|number] numeric datasets larger than this many
% bytes are not read; their value checks are reported as
% skip.notloaded. Use inf to read and check everything
% 'Level': ['warning'|'error'|'info'] the lowest severity printed
% 'Verbose': [1|0] print the report; the default is 1 when
% isvalid is not requested
% 'Schema': the schema file, schema/snirf_schema.json by default
%
% output:
% isvalid: true if no issue of severity 'error' was found
% issues: a struct array, one element per issue, with the fields
% severity: 'error', 'warning' or 'info'
% code: the issue code, such as 'missing.dataset' or 'link.index'
% path: the JSONPath of the object, such as '$.nirs.data1.time'
% h5path: the HDF5 path of the object, such as '/nirs/data1/time'
% message: a description of the issue, starting with the path
%
% issue codes:
% file.format, file.name the file can not be read as HDF5, or
% does not end with .snirf
% missing.group/dataset a required group or dataset is absent
% missing.indexed no nirs(i), data(j) or measurement list
% type.class wrong data type, such as double indices
% shape.dims, shape.rank wrong array size, or HDF5 rank
% value.range/enum/format a value is out of range, not one of the
% allowed values, or badly formatted
% value.unique duplicated source/detector labels
% link.count/length/index/labels/mlist
% inconsistent fields, such as a time
% vector not matching dataTimeSeries
% storage.fixedstring/inttype/emptygroup/numbering
% HDF5 encoding and naming problems
% extra.field, extra.unused a field SNIRF does not define, or an
% optode no channel refers to
% skip.notloaded a check not run as the data were not read
% skip.storage a storage check the HDF5 interface does
% not support, such as in oct-hdf5
%
% dependency:
% - the loadh5 function (with the MaxBytes option) is provided by the
% EasyH5 toolbox at http://github.com/NeuroJSON/easyh5
% - the jsonschema, loadjson, varargin2struct and jsonopt functions are
% provided by the JSONLab toolbox at http://github.com/NeuroJSON/jsonlab
%
% example:
% snirfvalidate('test.snirf') % print a report
% [isvalid, issues] = snirfvalidate('test.snirf', 'MaxBytes', inf);
% issues(startsWith({issues.code}, 'link.')) % the consistency issues
%
% this file is part of JSNIRF specification: https://github.com/NeuroJSON/jsnirf
%
% License: GPLv3 or Apache 2.0, see https://github.com/NeuroJSON/jsnirfy for details
%
if (nargin == 0 || ~(ischar(fname) || isa(fname, 'string')))
error('you must provide a file name');
end
fname = char(fname);
if (~exist('jsonschema', 'file'))
error('snirfvalidate requires jsonschema.m from JSONLab, http://github.com/NeuroJSON/jsonlab');
end
opt = varargin2struct(varargin{:});
maxbytes = jsonopt('MaxBytes', 1e6, opt);
level = jsonopt('Level', 'warning', opt);
verbose = jsonopt('Verbose', nargout == 0, opt);
schemafile = jsonopt('Schema', fullfile(fileparts(mfilename('fullpath')), 'schema', 'snirf_schema.json'), opt);
issues = struct('severity', {}, 'code', {}, 'path', {}, 'h5path', {}, 'message', {});
% file checks
if (~exist(fname, 'file'))
issues = addissue(issues, 'error', 'file.format', '$', sprintf('%s: file does not exist', fname));
elseif (~ishdf5(fname))
issues = addissue(issues, 'error', 'file.format', '$', sprintf('%s: not an HDF5 file', fname));
else
if (isempty(regexp(fname, '\.snirf$', 'once')))
issues = addissue(issues, 'warning', 'file.name', '$', sprintf('%s: SNIRF files should use the .snirf suffix', fname));
end
schema = loadjson(schemafile, 'usemap', 1);
% pass 1: storage; loadh5 returns the storage records while loading, and
% older versions without that output need a separate walk of the file
try
[data, ~, records] = loadh5(fname, 'MaxBytes', maxbytes);
catch
data = loadh5(fname, 'MaxBytes', maxbytes);
records = h5records(fname);
end
[issues, strings] = checkstorage(issues, records, schema);
issues = checknumbering(issues, records);
% pass 2: schema
data = normalizestrings(data, '', strings.paths, strings.counts);
[packed, packs] = packmeasurementlists(data);
[~, errs, skipped] = jsonschema(packed, schema, 'errorformat', 'struct');
errs = unpackrecords(errs, packs);
skipped = unpackrecords(skipped, packs);
issues = schemaissues(issues, [errs, processedlabels(packs)], skipped, schema, data);
% pass 3: rules
issues = checkrules(issues, data);
end
order = [find(strcmp({issues.severity}, 'error')), find(strcmp({issues.severity}, 'warning')), ...
find(strcmp({issues.severity}, 'info'))];
issues = issues(order);
isvalid = ~any(strcmp({issues.severity}, 'error'));
if (verbose)
printreport(fname, isvalid, issues, level);
end
if (nargout == 0)
clear isvalid;
end
%% -------------------------------------------------------------------------
function tf = ishdf5(fname)
% H5F.is_hdf5 is not in every HDF5 interface (such as oct-hdf5); a file that
% opens as HDF5 is one
try
tf = H5F.is_hdf5(fname) > 0;
catch
try
fid = H5F.open(fname, 'H5F_ACC_RDONLY', 'H5P_DEFAULT');
H5F.close(fid);
tf = true;
catch
tf = false;
end
end
%% -------------------------------------------------------------------------
function issues = addissue(issues, severity, code, path, message)
h5path = regexprep(path, '^\$\.?', '/');
h5path = strrep(h5path, '.', '/');
issues(end + 1) = struct('severity', severity, 'code', code, 'path', path, 'h5path', h5path, 'message', message);
%% -------------------------------------------------------------------------
function path = h52jsonpath(h5path)
path = ['$' strrep(h5path, '/', '.')];
%% -------------------------------------------------------------------------
function printreport(fname, isvalid, issues, level)
severity = {issues.severity};
status = 'valid';
if (~isvalid)
status = 'INVALID';
end
fprintf('%s: %s (%d errors, %d warnings, %d info)\n', fname, status, sum(strcmp(severity, 'error')), ...
sum(strcmp(severity, 'warning')), sum(strcmp(severity, 'info')));
shown = {'error'};
if (strcmpi(level, 'warning'))
shown = {'error', 'warning'};
elseif (strcmpi(level, 'info'))
shown = {'error', 'warning', 'info'};
end
% issues that differ only in the numbers of indexed groups, such as the same
% problem in every measurementList(k), are printed once with a count
groups = regexprep({issues.path}, '(nirs|data|stim|aux|measurementList)[0-9]+', '$1*');
groups = strcat({issues.code}, '|', groups);
[first, member] = uniquestable(groups);
for i = 1:length(first)
item = issues(first(i));
if (~ismember(item.severity, shown))
continue
end
count = sum(member == i);
message = item.message;
if (count > 1)
message = sprintf('%s (and %d more like it)', message, count - 1);
end
fprintf(' %-8s %-20s %s\n', item.severity, item.code, message);
end
%% -------------------------------------------------------------------------
% pass 1: storage
%% -------------------------------------------------------------------------
function records = h5records(fname)
% the type, string encoding, rank and dimensions of every object in the file,
% in the format of the third output of loadh5, for versions that lack it
fid = H5F.open(fname, 'H5F_ACC_RDONLY', 'H5P_DEFAULT');
cleanfid = onCleanup(@() H5F.close(fid));
store = containers.Map('KeyType', 'double', 'ValueType', 'any');
H5O.visit(fid, 'H5_INDEX_NAME', 'H5_ITER_INC', @visitobject, store);
records = values(store);
records = [records{:}];
%% -------------------------------------------------------------------------
function [status, store] = visitobject(rootid, name, store)
status = 0;
if (strcmp(name, '.'))
return
end
rec = struct('path', ['/' name], 'isgroup', false, 'nlinks', 0, 'class', '', 'bytes', 0, ...
'signed', true, 'varstring', false, 'rank', 0, 'dims', []);
oid = H5O.open(rootid, name, 'H5P_DEFAULT');
info = H5O.get_info(oid);
if (info.type == H5ML.get_constant_value('H5O_TYPE_GROUP'))
rec.isgroup = true;
ginfo = H5G.get_info(oid);
rec.nlinks = ginfo.nlinks;
elseif (info.type == H5ML.get_constant_value('H5O_TYPE_DATASET'))
tid = H5D.get_type(oid);
switch H5T.get_class(tid)
case H5ML.get_constant_value('H5T_FLOAT')
rec.class = 'float';
case H5ML.get_constant_value('H5T_INTEGER')
rec.class = 'integer';
rec.signed = H5T.get_sign(tid) ~= H5ML.get_constant_value('H5T_SGN_NONE');
case H5ML.get_constant_value('H5T_STRING')
rec.class = 'string';
rec.varstring = H5T.is_variable_str(tid);
otherwise
rec.class = 'other';
end
rec.bytes = H5T.get_size(tid);
H5T.close(tid);
sid = H5D.get_space(oid);
[rec.rank, dims] = H5S.get_simple_extent_dims(sid);
rec.dims = double(dims(:)');
H5S.close(sid);
end
H5O.close(oid);
store(store.Count + 1) = rec;
%% -------------------------------------------------------------------------
function [issues, strings] = checkstorage(issues, records, schema)
% HDF5 encoding and dataspace rank; also return the string datasets for
% normalizestrings, which are loaded differently by MATLAB and GNU Octave.
% The tests are done on all records at once, and the issues reported in the
% order of the records
paths = {records.path};
isgroup = [records.isgroup];
ranks = [records.rank];
isstring = strcmp({records.class}, 'string') & ~isgroup;
isinteger = strcmp({records.class}, 'integer') & ~isgroup;
% indexed groups share one subschema, so look up the expected rank once per
% path with the group numbers removed
keys = regexprep(paths, '(nirs|data|stim|aux|measurementList)[0-9]+', '$1#');
[first, keyid] = uniquestable(keys);
rankbad = false(1, length(records));
scalarschema = false(1, length(records));
for k = 1:length(first)
expected = findschemakey(schema, schemanode(schema, paths{first(k)}), 'h5Rank');
if (iscell(expected))
expected = [expected{:}];
end
if (isempty(expected))
continue
end
members = (keyid(:)' == k) & ~isgroup;
rankbad(members) = ~ismember(ranks(members), expected);
scalarschema(members) = isequal(expected, 0);
end
emptybad = isgroup & [records.nlinks] == 0;
% varstring is NaN where the HDF5 interface can not tell (oct-hdf5)
varstring = double([records.varstring]);
fixedbad = isstring & varstring == 0;
if (any(isstring & isnan(varstring)))
issues = addissue(issues, 'info', 'skip.storage', '$', ...
'$: string encodings not checked, the HDF5 interface can not tell fixed from variable-length strings');
end
intbad = isinteger & ([records.bytes] ~= 4 | ~[records.signed]);
% string datasets: -1 for a scalar (in the file or in the schema), otherwise
% the number of strings
idx = find(isstring);
strings.paths = paths(idx);
strings.counts = -ones(1, length(idx));
arrays = ranks(idx) > 0 & ~scalarschema(idx);
strings.counts(arrays) = arrayfun(@(i) prod(records(i).dims), idx(arrays));
for i = find(emptybad | rankbad | fixedbad | intbad)
rec = records(i);
path = h52jsonpath(rec.path);
if (emptybad(i))
issues = addissue(issues, 'warning', 'storage.emptygroup', path, sprintf('%s: empty group', path));
continue
end
if (rankbad(i))
expected = findschemakey(schema, schemanode(schema, rec.path), 'h5Rank');
if (iscell(expected))
expected = [expected{:}];
end
issues = addissue(issues, 'error', 'shape.rank', path, sprintf('%s: stored with rank %d, expected %s', ...
path, rec.rank, rankname(expected)));
end
if (fixedbad(i))
issues = addissue(issues, 'warning', 'storage.fixedstring', path, ...
sprintf('%s: fixed-length string, SNIRF requires variable-length strings', path));
end
if (intbad(i))
issues = addissue(issues, 'warning', 'storage.inttype', path, ...
sprintf('%s: stored as %sint%d, int32 recommended', path, repmat('u', 1, ~rec.signed), 8 * rec.bytes));
end
end
%% -------------------------------------------------------------------------
function name = rankname(ranks)
names = {'a scalar', '1-D', '2-D'};
name = strjoin(names(min(ranks, 2) + 1), ' or ');
%% -------------------------------------------------------------------------
function issues = checknumbering(issues, records)
% indexed groups must be numbered 1, 2, ... without gaps or leading zeros
groups = records([records.isgroup]);
parents = cellfun(@fileparts, {groups.path}, 'UniformOutput', false);
parents(cellfun(@isempty, parents)) = {'/'};
[~, names] = cellfun(@fileparts, {groups.path}, 'UniformOutput', false);
% each indexed group is checked only where SNIRF places it
for parent = unique(parents)
children = names(strcmp(parents, parent{1}));
[~, parentname] = fileparts(parent{1});
if (strcmp(parent{1}, '/'))
prefixes = {'nirs'};
elseif (~isempty(regexp(parentname, '^nirs([0-9]*)$', 'once')))
prefixes = {'data', 'stim', 'aux'};
elseif (~isempty(regexp(parentname, '^data([0-9]*)$', 'once')))
prefixes = {'measurementList'};
else
continue
end
for prefix = prefixes
tok = regexp(children, ['^' prefix{1} '([0-9]*)$'], 'tokens', 'once');
tok = [tok{:}];
if (isempty(tok))
continue
end
path = h52jsonpath(regexprep(parent{1}, '/$', ''));
if (any(strcmp(tok, '')) && length(tok) > 1)
issues = addissue(issues, 'error', 'storage.numbering', path, ...
sprintf('%s: both %s and %s1... are present', path, prefix{1}, prefix{1}));
elseif (any(strcmp(tok, '')) && ~strcmp(prefix{1}, 'nirs'))
% only /nirs may be unnumbered; older files also leave out the others
issues = addissue(issues, 'warning', 'storage.numbering', [path '.' prefix{1}], ...
sprintf('%s.%s: indexed group without a number, SNIRF names it %s1', path, prefix{1}, prefix{1}));
end
tok = tok(~strcmp(tok, ''));
if (any(cellfun(@(t) t(1) == '0', tok)))
issues = addissue(issues, 'error', 'storage.numbering', path, ...
sprintf('%s: %s indices must start from 1 without leading zeros', path, prefix{1}));
end
idx = sort(str2double(tok));
missing = setdiff(1:max([idx 0]), idx);
if (~isempty(missing))
issues = addissue(issues, 'error', 'storage.numbering', path, ...
sprintf('%s: %s%d is missing from the indexed group %s', path, prefix{1}, missing(1), prefix{1}));
end
end
end
%% -------------------------------------------------------------------------
function data = normalizestrings(data, prefix, paths, counts)
% give string datasets one form: a char for a scalar string, and a 1xN cell
% array of char for a string array. MATLAB loads a scalar string as a 1x1
% cell, GNU Octave (oct-hdf5) loads a one-element string array as a char, and
% both load fixed-length string arrays as char matrices. paths and counts are
% the string datasets under prefix; each member is passed only those under
% it, as a containers.Map of all paths is slow in GNU Octave. Each struct is
% rebuilt once, as setfield on a nested path copies every level
if (~isstruct(data) || ~isscalar(data) || isempty(paths))
return
end
names = fieldnames(data);
for i = 1:length(names)
h5path = [prefix '/' decodevarname(names{i})];
exact = strcmp(paths, h5path);
if (~any(exact))
under = strncmp(paths, [h5path '/'], length(h5path) + 1);
if (any(under))
data.(names{i}) = normalizestrings(data.(names{i}), h5path, paths(under), counts(under));
end
continue
end
count = counts(find(exact, 1));
val = data.(names{i});
if (count < 0 && iscell(val) && numel(val) == 1 && ischar(val{1}))
data.(names{i}) = val{1};
elseif (count < 0 && ischar(val) && iscolumn(val) && ~isscalar(val))
data.(names{i}) = val(:)'; % oct-hdf5 returns fixed-length strings as columns
elseif (count > 0 && ischar(val))
if (count == 1)
val = {val(:)'};
elseif (size(val, 1) == count)
val = cellstr(val)';
elseif (size(val, 2) == count)
val = cellstr(val')';
else
continue
end
data.(names{i}) = cellfun(@deblank, val, 'UniformOutput', false); % fixed-length padding
end
end
%% -------------------------------------------------------------------------
% fast path for measurementList(k)
%% -------------------------------------------------------------------------
function [data, packs] = packmeasurementlists(data)
% validating thousands of small measurementList(k) groups one by one is slow;
% where all groups of a data block have the same fields holding scalars of
% one class, they are replaced by a measurementLists group of vectors, which
% the schema checks in one pass; unpackrecords maps the errors back
packs = struct('path', {}, 'names', {}, 'lists', {});
for nirsname = matchfields(data, '^nirs([1-9][0-9]*)?$')
nirs = data.(nirsname{1});
for dataname = matchfields(nirs, '^data([1-9][0-9]*)?$')
block = nirs.(dataname{1});
mlnames = matchfields(block, '^measurementList([1-9][0-9]*)?$');
if (length(mlnames) < 2 || isfield(block, 'measurementLists'))
continue
end
[~, order] = sort(str2double(regexprep(mlnames, '^measurementList', '')));
mlnames = mlnames(order);
lists = packvectors(block, mlnames);
if (isempty(lists))
continue
end
block = rmfield(block, mlnames);
block.measurementLists = lists;
nirs.(dataname{1}) = block;
packs(end + 1) = struct('path', ['$.' nirsname{1} '.' dataname{1}], 'names', {mlnames}, 'lists', lists);
end
data.(nirsname{1}) = nirs;
end
%% -------------------------------------------------------------------------
function lists = packvectors(block, mlnames)
% one vector (or cell array of strings) per field; [] if the groups differ
lists = [];
first = block.(mlnames{1});
if (~isstruct(first) || ~isscalar(first))
return
end
fields = fieldnames(first);
for k = 2:length(mlnames)
ml = block.(mlnames{k});
if (~isstruct(ml) || ~isscalar(ml) || ~isequal(sort(fieldnames(ml)), sort(fields)))
return
end
end
packed = cell(1, length(fields));
for i = 1:length(fields)
vals = cellfun(@(name) block.(name).(fields{i}), mlnames, 'UniformOutput', false);
if (all(cellfun(@(v) ischar(v) && size(v, 1) <= 1, vals)))
packed{i} = vals;
elseif (all(cellfun(@(v) (isnumeric(v) || islogical(v)) && isscalar(v), vals)) && ...
all(strcmp(cellfun(@class, vals, 'UniformOutput', false), class(vals{1}))))
packed{i} = [vals{:}];
else
return
end
end
lists = cell2struct(packed(:), fields(:), 1);
%% -------------------------------------------------------------------------
function recs = unpackrecords(recs, packs)
% map error records on a packed measurementLists back to measurementList(k):
% element [i] belongs to group i+1, and errors on a whole vector or on the
% group itself apply to every group, which share the field and its class
out = cell(1, length(recs));
for i = 1:length(recs)
out{i} = recs(i);
for j = 1:length(packs)
prefix = [packs(j).path '.measurementLists'];
if (~strncmp(recs(i).path, prefix, length(prefix)) || ...
(length(recs(i).path) > length(prefix) && recs(i).path(length(prefix) + 1) ~= '.'))
continue
end
[field, idx, tail] = splitpath(recs(i).path(length(prefix) + 1:end));
names = packs(j).names;
if (~isnan(idx))
out{i} = repath(recs(i), sprintf('%s.%s.%s%s', packs(j).path, names{idx + 1}, field, tail));
else
suffix = '';
if (~isempty(field))
suffix = ['.' field tail];
end
out{i} = arrayfun(@(k) repath(recs(i), [packs(j).path '.' names{k} suffix]), 1:length(names));
end
break
end
end
if (~isempty(out))
recs = [out{:}];
end
%% -------------------------------------------------------------------------
function [field, idx, tail] = splitpath(rest)
% split '.field[idx]tail' into its parts; idx is NaN without an element index
field = '';
idx = NaN;
tail = '';
if (isempty(rest))
return
end
rest = rest(2:end);
stop = find(rest == '.' | rest == '[', 1);
if (isempty(stop))
field = rest;
return
end
field = rest(1:stop - 1);
tail = rest(stop:end);
if (tail(1) == '[')
close = find(tail == ']', 1);
idx = str2double(tail(2:close - 1));
tail = tail(close + 1:end);
end
%% -------------------------------------------------------------------------
function rec = repath(rec, path)
rec.message = strrep(rec.message, rec.path, path);
rec.path = path;
%% -------------------------------------------------------------------------
function recs = processedlabels(packs)
% the per-group rule that processed data (dataType 99999) need a
% dataTypeLabel, which the packed vectors do not express
recs = struct('path', {}, 'keyword', {}, 'message', {}, 'property', {});
for j = 1:length(packs)
if (~isfield(packs(j).lists, 'dataType') || isfield(packs(j).lists, 'dataTypeLabel'))
continue
end
for k = find(double(packs(j).lists.dataType) == 99999)
path = [packs(j).path '.' packs(j).names{k}];
recs(end + 1) = struct('path', path, 'keyword', 'required', ...
'message', sprintf('%s: missing "dataTypeLabel"', path), 'property', 'dataTypeLabel');
end
end
%% -------------------------------------------------------------------------
% schema lookup
%% -------------------------------------------------------------------------
function node = schemanode(schema, h5path)
% the subschema that applies to an HDF5 path, following properties,
% patternProperties, additionalProperties and $ref; [] if none
node = schema;
names = regexp(h5path, '[^/]+', 'match');
for i = 1:length(names)
node = derefschema(schema, node);
child = [];
if (isKey(node, 'properties'))
props = node('properties');
if (isKey(props, names{i}))
child = props(names{i});
end
end
if (isempty(child) && isKey(node, 'patternProperties'))
patterns = node('patternProperties');
pkeys = keys(patterns);
for j = 1:length(pkeys)
if (~isempty(regexp(names{i}, pkeys{j}, 'once')))
child = patterns(pkeys{j});
break
end
end
end
if (isempty(child) && isKey(node, 'additionalProperties') && isa(node('additionalProperties'), 'containers.Map'))
child = node('additionalProperties');
end
if (isempty(child))
node = [];
return
end
node = child;
end
%% -------------------------------------------------------------------------
function node = derefschema(schema, node)
while (isa(node, 'containers.Map') && isKey(node, '$ref'))
node = jsonschema(schema, [], 'resolveref', node('$ref'));
end
%% -------------------------------------------------------------------------
function val = findschemakey(schema, node, key)
% the value of a keyword in a subschema or in the branches of its allOf
val = [];
node = derefschema(schema, node);
if (~isa(node, 'containers.Map'))
return
end
if (isKey(node, key))
val = node(key);
return
end
if (isKey(node, 'allOf'))
branches = node('allOf');
for i = 1:length(branches)
val = findschemakey(schema, branches{i}, key);
if (~isempty(val))
return
end
end
end
%% -------------------------------------------------------------------------
% pass 2: schema errors
%% -------------------------------------------------------------------------
function issues = schemaissues(issues, errs, skipped, schema, data)
% map the failed schema keywords to issue codes; where the value is at hand,
% the message states it together with what the schema expects
for i = 1:length(errs)
e = errs(i);
path = e.path;
message = describe(e, schema, data);
switch e.keyword
case 'required'
path = [e.path '.' e.property];
node = schemanode(schema, strrep(regexprep(path, '^\$', ''), '.', '/'));
if (strcmp(findschemakey(schema, node, 'type'), 'object'))
code = 'missing.group';
else
code = 'missing.dataset';
end
issues = addissue(issues, 'error', code, path, sprintf('%s: required %s is missing', path, code(9:end)));
continue
case 'additionalProperties'
path = [e.path '.' e.property];
issues = addissue(issues, 'info', 'extra.field', path, sprintf('%s: not defined by SNIRF', path));
continue
case {'type', 'binType'}
code = 'type.class';
case {'minDims', 'maxDims', 'minItems', 'maxItems'}
code = 'shape.dims';
case {'minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum', 'multipleOf'}
code = 'value.range';
case {'enum', 'const'}
code = 'value.enum';
case {'pattern', 'format', 'minLength', 'maxLength'}
code = 'value.format';
otherwise
code = 'schema.other';
end
issues = addissue(issues, 'error', code, path, message);
end
for i = 1:length(skipped)
issues = addissue(issues, 'info', 'skip.notloaded', skipped(i).path, skipped(i).message);
end
%% -------------------------------------------------------------------------
function message = describe(e, schema, data)
% a message with the offending value; the jsonschema message otherwise
message = e.message;
names = regexp(e.path, '[^.$]+', 'match');
try
val = getfield(data, names{:});
catch
return
end
node = schemanode(schema, ['/' strjoin(names, '/')]);
switch e.keyword
case 'enum'
message = sprintf('%s: %s is not one of the allowed values', e.path, valuestr(val));
case {'pattern', 'format'}
message = sprintf('%s: %s does not have the required format', e.path, valuestr(val));
hint = findschemakey(schema, node, 'description');
if (ischar(hint))
message = sprintf('%s, expected %s', message, hint);
end
case {'minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum'}
limit = findschemakey(schema, node, e.keyword);
relation = struct('minimum', 'below the minimum', 'maximum', 'above the maximum', ...
'exclusiveMinimum', 'not above', 'exclusiveMaximum', 'not below');
if (isnumeric(limit))
message = sprintf('%s: %s is %s %g', e.path, valuestr(val), relation.(e.keyword), limit);
end
case 'binType'
bintypes = findschemakey(schema, node, 'binType');
if (iscell(bintypes) && all(~cellfun(@isempty, regexp(bintypes, '^u?int'))))
expected = 'an integer type';
elseif (iscell(bintypes) && all(ismember(bintypes, {'single', 'double'})))
expected = 'a floating-point type';
else
return
end
if (isheader(val))
stored = val.(encodevarname('_ArrayType_'));
else
stored = class(val);
end
message = sprintf('%s: stored as %s, expected %s', e.path, stored, expected);
end
%% -------------------------------------------------------------------------
function str = valuestr(val)
if (ischar(val) && (isvector(val) || isempty(val)))
str = ['"' val(:)' '"']; % oct-hdf5 returns some fixed-length strings as columns
elseif (isnumeric(val) && isscalar(val))
str = num2str(val);
else
str = sprintf('a %s %s', mat2str(size(val)), class(val));
end
%% -------------------------------------------------------------------------
% pass 3: rules spanning several fields
%% -------------------------------------------------------------------------
function issues = checkrules(issues, data)
if (~isstruct(data))
return
end
nirsnames = matchfields(data, '^nirs([1-9][0-9]*)?$');
if (isempty(nirsnames))
issues = addissue(issues, 'error', 'missing.indexed', '$', '$: no /nirs or /nirs1 group, at least one is required');
end
for i = 1:length(nirsnames)
nirs = data.(nirsnames{i});
path = ['$.' nirsnames{i}];
if (~isstruct(nirs))
continue
end
[issues, nsrc, ndet, nwl] = checkprobe(issues, nirs, path);
datanames = matchfields(nirs, '^data([1-9][0-9]*)?$');
if (isempty(datanames))
issues = addissue(issues, 'error', 'missing.indexed', path, sprintf('%s: no data1 group, at least one is required', path));
end
used = struct('src', [], 'det', [], 'complete', true);
for j = 1:length(datanames)
[issues, used] = checkdata(issues, nirs.(datanames{j}), [path '.' datanames{j}], nsrc, ndet, nwl, used);
end
if (~isempty(datanames) && used.complete && ~isnan(nsrc))
issues = reportunused(issues, [path '.probe'], 'source', setdiff(1:nsrc, used.src));
end
if (~isempty(datanames) && used.complete && ~isnan(ndet))
issues = reportunused(issues, [path '.probe'], 'detector', setdiff(1:ndet, used.det));
end
for name = matchfields(nirs, '^stim([1-9][0-9]*)?$')
issues = checkstim(issues, nirs.(name{1}), [path '.' name{1}]);
end
for name = matchfields(nirs, '^aux([1-9][0-9]*)?$')
aux = nirs.(name{1});
if (isstruct(aux) && isfield(aux, 'dataTimeSeries') && isfield(aux, 'time'))
issues = checktime(issues, aux.time, arraysize(aux.dataTimeSeries), [path '.' name{1}]);
end
end
end
%% -------------------------------------------------------------------------
function [issues, nsrc, ndet, nwl] = checkprobe(issues, nirs, path)
% count the sources, detectors and wavelengths, and check the labels
nsrc = NaN;
ndet = NaN;
nwl = NaN;
if (~isfield(nirs, 'probe') || ~isstruct(nirs.probe))
return
end
probe = nirs.probe;
path = [path '.probe'];
[issues, nsrc] = optodecount(issues, probe, path, 'source');
[issues, ndet] = optodecount(issues, probe, path, 'detector');
if (isfield(probe, 'wavelengths'))
nwl = prod(arraysize(probe.wavelengths));
end
labels = {};
if (isfield(probe, 'sourceLabels') && iscell(probe.sourceLabels))
if (~isnan(nsrc) && size(probe.sourceLabels, 1) ~= nsrc && numel(probe.sourceLabels) ~= nsrc)
issues = addissue(issues, 'error', 'link.labels', [path '.sourceLabels'], ...
sprintf('%s.sourceLabels: %d labels for %d sources', path, numel(probe.sourceLabels), nsrc));
end
labels = [labels probe.sourceLabels(:)'];
end
if (isfield(probe, 'detectorLabels') && iscell(probe.detectorLabels))
if (~isnan(ndet) && numel(probe.detectorLabels) ~= ndet)
issues = addissue(issues, 'error', 'link.labels', [path '.detectorLabels'], ...
sprintf('%s.detectorLabels: %d labels for %d detectors', path, numel(probe.detectorLabels), ndet));
end
labels = [labels probe.detectorLabels(:)'];
end
labels = labels(cellfun(@ischar, labels));
first = uniquestable(labels);
if (length(first) < length(labels))
dup = labels(setdiff(1:length(labels), first));
issues = addissue(issues, 'error', 'value.unique', path, ...
sprintf('%s: source and detector labels must be unique, "%s" is repeated', path, dup{1}));
end
for dim = {'2D', '3D'}
field = ['landmarkPos' dim{1}];
if (~isfield(probe, field) || isheader(probe.(field)) || ~isnumeric(probe.(field)))
continue
end
pos = probe.(field);
ncoord = 2 + strcmp(dim{1}, '3D');
nlabels = 0;
if (isfield(probe, 'landmarkLabels') && iscell(probe.landmarkLabels))
nlabels = numel(probe.landmarkLabels);
end
if (size(pos, 2) > ncoord)
idx = pos(:, ncoord + 1);
if (any(idx < 0 | idx > nlabels | mod(idx, 1) ~= 0))
issues = addissue(issues, 'error', 'link.index', [path '.' field], ...
sprintf('%s.%s: label index column refers past the %d landmarkLabels', path, field, nlabels));
end
elseif (nlabels > 0 && nlabels ~= size(pos, 1))
issues = addissue(issues, 'warning', 'link.labels', [path '.landmarkLabels'], ...
sprintf('%s.landmarkLabels: %d labels for %d landmarks in %s', path, nlabels, size(pos, 1), field));
end
end
%% -------------------------------------------------------------------------
function [issues, count] = optodecount(issues, probe, path, kind)
count = NaN;
fields = {[kind 'Pos2D'], [kind 'Pos3D']};
present = fields(isfield(probe, fields));
if (isempty(present))
issues = addissue(issues, 'error', 'missing.dataset', [path '.' fields{2}], ...
sprintf('%s: one of %s and %s is required', path, fields{:}));
return
end
counts = cellfun(@(f) nrows(probe.(f)), present);
count = counts(1);
if (any(counts ~= count))
issues = addissue(issues, 'error', 'link.count', [path '.' fields{1}], ...
sprintf('%s: %s has %d rows but %s has %d', path, fields{1}, counts(1), fields{2}, counts(2)));
end
%% -------------------------------------------------------------------------
function [issues, used] = checkdata(issues, block, path, nsrc, ndet, nwl, used)
if (~isstruct(block) || ~isfield(block, 'dataTimeSeries'))
return
end
dsize = arraysize(block.dataTimeSeries);
if (isfield(block, 'time'))
issues = checktime(issues, block.time, dsize, path);
end
if (isfield(block, 'dataOffset') && prod(arraysize(block.dataOffset)) ~= dsize(2))
issues = addissue(issues, 'error', 'link.count', [path '.dataOffset'], ...
sprintf('%s.dataOffset: has %d elements, expected %d (columns of dataTimeSeries)', ...
path, prod(arraysize(block.dataOffset)), dsize(2)));
end
% the measurement list as one vector per field
mlnames = matchfields(block, '^measurementList([1-9][0-9]*)?$');
haslists = isfield(block, 'measurementLists') && isstruct(block.measurementLists);
if (~isempty(mlnames) && haslists)
issues = addissue(issues, 'error', 'link.mlist', path, ...
sprintf('%s: both measurementList1... and measurementLists are present, only one is allowed', path));
end
if (haslists)
ml = block.measurementLists;
mlpath = [path '.measurementLists'];
nchan = 0;
if (isfield(ml, 'sourceIndex'))
nchan = prod(arraysize(ml.sourceIndex));
end
field = @(name) listvalues(ml, name);
where = @(name, k) sprintf('%s.%s[%d]', mlpath, name, k - 1);
elseif (~isempty(mlnames))
[~, order] = sort(str2double(regexprep(mlnames, '^measurementList', '')));
mlnames = mlnames(order);
nchan = length(mlnames);
field = @(name) groupvalues(block, mlnames, name);
where = @(name, k) sprintf('%s.%s.%s', path, mlnames{k}, name);
else
issues = addissue(issues, 'error', 'missing.indexed', path, ...
sprintf('%s: no measurementList1 group or measurementLists, one is required', path));
return
end
if (nchan ~= dsize(2))
issues = addissue(issues, 'error', 'link.count', path, ...
sprintf('%s: %d measurement list entries for %d columns of dataTimeSeries', path, nchan, dsize(2)));
end
% index ranges
limits = {'sourceIndex', nsrc, 'sources'; 'detectorIndex', ndet, 'detectors'; 'wavelengthIndex', nwl, 'wavelengths'};
datatype = field('dataType');
for i = 1:size(limits, 1)
[vals, loaded] = field(limits{i, 1});
if (~loaded)
used.complete = false;
issues = addissue(issues, 'info', 'skip.notloaded', path, ...
sprintf('%s: %s range not checked, array data not loaded', path, limits{i, 1}));
continue
end
if (isnan(limits{i, 2}))
continue
end
if (strcmp(limits{i, 1}, 'wavelengthIndex') && limits{i, 2} == 0 && all(datatype == 99999))
continue % wavelengths may be empty for processed data
end
bad = find(vals > limits{i, 2});
if (~isempty(bad))
message = sprintf('%s: %d exceeds the number of %s in the probe (%d)', ...
where(limits{i, 1}, bad(1)), vals(bad(1)), limits{i, 3}, limits{i, 2});
if (length(bad) > 1)
message = sprintf('%s, in %d channels', message, length(bad));
end
issues = addissue(issues, 'error', 'link.index', where(limits{i, 1}, bad(1)), message);
end
if (i == 1)
used.src = union(used.src, vals(~isnan(vals)));
elseif (i == 2)
used.det = union(used.det, vals(~isnan(vals)));
end
end
%% -------------------------------------------------------------------------
function [vals, loaded] = listvalues(ml, name)
% a field of measurementLists as a row vector; NaN if absent
vals = [];
loaded = true;
if (~isfield(ml, name))
return
end
if (isheader(ml.(name)))
loaded = false;
return
end
if (isnumeric(ml.(name)))
vals = double(ml.(name)(:)');
end
%% -------------------------------------------------------------------------
function [vals, loaded] = groupvalues(block, mlnames, name)
% a field of measurementList1..N as a row vector; NaN where absent
vals = nan(1, length(mlnames));
loaded = true;
for k = 1:length(mlnames)
ml = block.(mlnames{k});
if (~isstruct(ml) || ~isfield(ml, name))
continue
end
if (isheader(ml.(name)))
loaded = false;
elseif (isnumeric(ml.(name)) && ~isempty(ml.(name)))
vals(k) = double(ml.(name)(1));
end
end
%% -------------------------------------------------------------------------
function issues = checktime(issues, time, dsize, path)
% time has one entry per row of dataTimeSeries, or is [start, spacing]
ntime = prod(arraysize(time));
if (ntime ~= dsize(1) && ntime ~= 2)
issues = addissue(issues, 'error', 'link.length', [path '.time'], ...
sprintf('%s.time: has %d elements, expected %d (rows of dataTimeSeries) or 2', path, ntime, dsize(1)));
end
%% -------------------------------------------------------------------------
function issues = checkstim(issues, stim, path)
if (~isstruct(stim) || ~isfield(stim, 'data'))
return
end