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 | # -*- coding: utf-8 -*-
"""sidecars classes"""
import itertools
import logging
import os
import re
from collections import defaultdict, OrderedDict
from fnmatch import fnmatch
from dcm2bids.acquisition import Acquisition
from dcm2bids.utils.io import load_json
from dcm2bids.utils.utils import DEFAULT, convert_dir, splitext_
compare_float_keys = ["lt", "gt", "le", "ge", "btw", "btwe"]
class Sidecar(object):
""" A sidecar object
Args:
filename (str): Path of a JSON sidecar
keyComp (list): A list of keys from the JSON sidecar to compare sidecars
default=["SeriesNumber","AcquisitionTime","SideCarFilename"]
"""
def __init__(self, filename, compKeys=DEFAULT.compKeys):
self._origData = {}
self._data = {}
self.filename = filename
self.root, _ = splitext_(filename)
self.data = filename
self.compKeys = compKeys
def __lt__(self, other):
lts = []
for key in self.compKeys:
try:
if all(key in d for d in (self.data, other.data)):
if self.data.get(key) == other.data.get(key):
lts.append(None)
else:
lts.append(self.data.get(key) < other.data.get(key))
else:
lts.append(None)
except Exception:
lts.append(None)
for lt in lts:
if lt is not None:
return lt
def __eq__(self, other):
return self.data == other.data
def __hash__(self):
return hash(self.filename)
@property
def origData(self):
return self._origData
@property
def data(self):
return self._data
@data.setter
def data(self, filename):
"""
Args:
filename (path): path of a JSON file
Return:
A dictionary of the JSON content plus the SidecarFilename
"""
try:
data = load_json(filename)
except Exception:
data = {}
self._origData = data.copy()
data["SidecarFilename"] = os.path.basename(filename)
self._data = data
class SidecarPairing(object):
"""
Args:
sidecars (list): List of Sidecar objects
descriptions (list): List of dictionaries describing acquisitions
"""
def __init__(self,
sidecars,
descriptions,
extractors=DEFAULT.extractors,
auto_extractor=DEFAULT.auto_extract_entities,
search_method=DEFAULT.search_method,
case_sensitive=DEFAULT.case_sensitive,
dup_method=DEFAULT.dup_method,
post_op=DEFAULT.post_op):
self.logger = logging.getLogger(__name__)
self._search_method = ""
self._dup_method = ""
self._post_op = ""
self.graph = OrderedDict()
self.acquisitions = []
self.extractors = extractors
self.auto_extract_entities = auto_extractor
self.sidecars = sidecars
self.descriptions = descriptions
self.search_method = search_method
self.case_sensitive = case_sensitive
self.dup_method = dup_method
self.post_op = post_op
@property
def search_method(self):
return self._search_method
@search_method.setter
def search_method(self, value):
"""
Checks if the search method is implemented
Warns the user if not and fall back to default
"""
if value in DEFAULT.search_methodChoices:
self._search_method = value
else:
self._search_method = DEFAULT.search_method
self.logger.warning(f"'{value}' is not a search method implemented")
self.logger.warning(f"Falling back to default: {DEFAULT.search_method}")
self.logger.warning(
f"Search methods implemented: {DEFAULT.search_methodChoices}"
)
@property
def dup_method(self):
return self._dup_method
@dup_method.setter
def dup_method(self, value):
"""
Checks if the duplicate method is implemented
Warns the user if not and fall back to default
"""
if value in DEFAULT.dup_method_choices:
self._dup_method = value
else:
self._dup_method = DEFAULT.dup_method
self.logger.warning(
"Duplicate methods implemented: %s", DEFAULT.dup_method_choices)
self.logger.warning(f"{value} is not a duplicate method implemented.")
self.logger.warning(f"Falling back to default: {DEFAULT.dup_method}.")
@property
def post_op(self):
return self._post_op
@post_op.setter
def post_op(self, value):
"""
Checks if post_op commands don't overlap
"""
post_op = []
if isinstance(value, dict):
value = [value]
elif not isinstance(value, list):
raise ValueError("post_op should be a list of dict."
"Please check the documentation.")
try:
pairs = []
for curr_post_op in value:
post_op.append(curr_post_op)
datatype = curr_post_op['datatype']
suffix = curr_post_op['suffix']
if isinstance(curr_post_op['cmd'], str):
cmd_split = curr_post_op['cmd'].split()
else:
raise ValueError("post_op cmd should be a string."
"Please check the documentation.")
if 'srcFile' not in cmd_split or 'dstFile' not in cmd_split:
raise ValueError("post_op cmd is not defined correctly."
"srcFile and/or dstFile is missing."
"Please check the documentation.")
if isinstance(datatype, str):
post_op[-1]['datatype'] = [datatype]
datatype = [datatype]
if isinstance(suffix, str):
# It will be compare with acq.suffix which has a `_` character
post_op[-1]['suffix'] = ['_' + suffix]
suffix = [suffix]
elif isinstance(suffix, list):
post_op[-1]['suffix'] = ['_' + curr_suffix for curr_suffix in suffix]
pairs = pairs + list(itertools.product(datatype, suffix))
res = list(set([ele for ele in pairs if pairs.count(ele) > 1]))
if res:
raise ValueError("Some post operations apply on "
"the same combination of datatype/suffix."
"Please fix post_op key in your config file."
f"{pairs}")
self._post_op = post_op
except Exception:
raise ValueError("post_op is not defined correctly."
"Please check the documentation.")
@property
def case_sensitive(self):
return self._case_sensitive
@case_sensitive.setter
def case_sensitive(self, value):
if isinstance(value, bool):
self._case_sensitive = value
else:
self._case_sensitive = DEFAULT.case_sensitive
self.logger.warning(f"'{value}' is not a boolean")
self.logger.warning(f"Falling back to default: {DEFAULT.case_sensitive}")
self.logger.warning(f"Search methods implemented: {DEFAULT.case_sensitive}")
def build_graph(self):
"""
Test all the possible links between the list of sidecars and the
description dictionaries and build a graph from it
The graph is in a OrderedDict object. The keys are the Sidecars and
the values are a list of possible descriptions
Returns:
A graph (OrderedDict)
"""
graph = OrderedDict((_, []) for _ in self.sidecars)
possibleLinks = itertools.product(self.sidecars, self.descriptions)
for sidecar, description in possibleLinks:
criteria = description.get("criteria", None)
if criteria and self.isLink(sidecar.data, criteria):
graph[sidecar].append(description)
self.graph = graph
return graph
def isLink(self, data, criteria):
"""
Args:
data (dict): Dictionary data of a sidecar
criteria (dict): Dictionary criteria
Returns:
boolean
"""
def compare(name, pattern):
name = str(name)
if self.search_method == "re":
return bool(re.match(pattern, name))
else:
pattern = str(pattern)
if not self.case_sensitive:
name = name.lower()
pattern = pattern.lower()
return fnmatch(name, pattern)
def compare_list(name, pattern):
try:
subResult = [
len(name) == len(pattern),
isinstance(pattern, list),
]
for subName, subPattern in zip(name, pattern):
subResult.append(compare(subName, subPattern))
except Exception:
subResult = [False]
return all(subResult)
def compare_complex(name, pattern):
sub_result = []
compare_type = None
try:
for compare_type, patterns in pattern.items():
for sub_pattern in patterns:
if isinstance(name, list):
sub_result.append(compare_list(name, sub_pattern))
else:
sub_result.append(compare(name, sub_pattern))
except Exception:
sub_result = [False]
if compare_type == "any":
return any(sub_result)
else:
return False
def compare_float(name, pattern):
try:
comparison = list(pattern.keys())[0]
name_float = float(name)
sub_pattern = pattern[list(pattern.keys())[0]]
if comparison in ["btwe", "btw"]:
if not isinstance(sub_pattern, list):
raise ValueError("You should be using a list "
"for float comparison "
f"with key {comparison}. "
f"Error val: {sub_pattern}")
if len(sub_pattern) != 2:
raise ValueError(f"List for key {comparison} "
"should have two values. "
f"Error val: {sub_pattern}")
elif comparison == "btwe":
return name_float >= float(sub_pattern[0]) and name_float <= float(sub_pattern[1])
elif comparison == "btw":
return name_float > float(sub_pattern[0]) and name_float < float(sub_pattern[1])
if isinstance(sub_pattern, list):
if len(sub_pattern) != 1:
raise ValueError(f"List for key {comparison} "
"should have only one value. "
"Error val: {sub_pattern}")
sub_pattern = float(sub_pattern[0])
else:
sub_pattern = float(sub_pattern)
if comparison == 'gt':
return sub_pattern < name_float
elif comparison == 'lt':
return sub_pattern > name_float
elif comparison == 'ge':
return sub_pattern <= name_float
elif comparison == 'le':
return sub_pattern >= name_float
except Exception:
return False
result = []
for tag, pattern in criteria.items():
name = data.get(tag, '')
if isinstance(pattern, dict):
if len(pattern.keys()) == 1:
if "any" in pattern.keys():
result.append(compare_complex(name, pattern))
elif list(pattern.keys())[0] in compare_float_keys:
result.append(compare_float(name, pattern))
else:
self.logger.warning(f"This key {list(pattern.keys())[0]} "
"is not allowed.")
else:
raise ValueError("Dictionary used as criteria should be "
"using only one key.")
elif isinstance(name, list):
result.append(compare_list(name, pattern))
else:
result.append(compare(name, pattern))
return all(result)
def build_acquisitions(self, participant):
"""
Args:
participant (Participant): Participant object to create acquisitions
Returns:
A list of acquisition objects
"""
acquisitions_id = []
acquisitions = []
self.logger.info("Sidecar pairing".upper())
for sidecar, valid_descriptions in self.graph.items():
sidecarName = os.path.basename(sidecar.root)
# only one description for the sidecar
if len(valid_descriptions) == 1:
desc = valid_descriptions[0]
desc, sidecar = self.searchDcmTagEntity(sidecar, desc)
acq = Acquisition(participant,
src_sidecar=sidecar, **desc)
acq.setDstFile()
if acq.id:
acquisitions_id.append(acq)
else:
acquisitions.append(acq)
self.logger.info(
f"{acq.dstFile.replace(f'{acq.participant.prefix}-', '')}"
f" <- {sidecarName}")
elif len(valid_descriptions) == 0:
self.logger.info(f"No Pairing <- {sidecarName}")
else:
self.logger.warning(f"Several Pairing <- {sidecarName}")
for desc in valid_descriptions:
acq = Acquisition(participant,
**desc)
self.logger.warning(f" -> {acq.suffix}")
self.acquisitions = acquisitions_id + acquisitions
return self.acquisitions
def searchDcmTagEntity(self, sidecar, desc):
"""
Add DCM Tag to custom_entities
"""
descWithTask = desc.copy()
concatenated_matches = {}
entities = []
if "custom_entities" in desc.keys() or self.auto_extract_entities:
if 'custom_entities' in desc.keys():
if isinstance(descWithTask["custom_entities"], str):
descWithTask["custom_entities"] = [descWithTask["custom_entities"]]
else:
descWithTask["custom_entities"] = []
if self.auto_extract_entities:
self.extractors.update(DEFAULT.auto_extractors)
for dcmTag in self.extractors:
if dcmTag in sidecar.data.keys():
dcmInfo = sidecar.data.get(dcmTag)
for regex in self.extractors[dcmTag]:
compile_regex = re.compile(regex)
if not isinstance(dcmInfo, list):
if compile_regex.search(str(dcmInfo)) is not None:
concatenated_matches.update(
compile_regex.search(str(dcmInfo)).groupdict())
else:
for curr_dcmInfo in dcmInfo:
if compile_regex.search(curr_dcmInfo) is not None:
concatenated_matches.update(
compile_regex.search(curr_dcmInfo).groupdict())
break
if "custom_entities" in desc.keys():
entities = set(concatenated_matches.keys()).union(set(descWithTask["custom_entities"]))
if self.auto_extract_entities:
auto_acq = '_'.join([descWithTask['datatype'], descWithTask["suffix"]])
if auto_acq in DEFAULT.auto_entities:
# Check if these auto entities have been found before merging
auto_entities = set(concatenated_matches.keys()).intersection(set(DEFAULT.auto_entities[auto_acq]))
left_auto_entities = auto_entities.symmetric_difference(set(DEFAULT.auto_entities[auto_acq]))
if left_auto_entities:
self.logger.warning(f"{left_auto_entities} have not been found for datatype '{descWithTask['datatype']}' "
f"and suffix '{descWithTask['suffix']}'.")
else:
entities = list(entities) + DEFAULT.auto_entities[auto_acq]
entities = list(set(entities))
descWithTask["custom_entities"] = entities
for curr_entity in entities:
if curr_entity in concatenated_matches.keys():
if curr_entity == 'dir':
descWithTask["custom_entities"] = list(map(lambda x: x.replace(curr_entity, '-'.join([curr_entity, convert_dir(concatenated_matches[curr_entity])])), descWithTask["custom_entities"]))
elif curr_entity == 'task':
sidecar.data['TaskName'] = concatenated_matches[curr_entity]
descWithTask["custom_entities"] = list(map(lambda x: x.replace(curr_entity, '-'.join([curr_entity, concatenated_matches[curr_entity]])), descWithTask["custom_entities"]))
else:
descWithTask["custom_entities"] = list(map(lambda x: x.replace(curr_entity, '-'.join([curr_entity, concatenated_matches[curr_entity]])), descWithTask["custom_entities"]))
# Remove entities without -
for curr_entity in descWithTask["custom_entities"]:
if '-' not in curr_entity:
self.logger.info(f"Removing entity '{curr_entity}' since it "
"does not fit the basic BIDS specification "
"(Entity-Value)")
descWithTask["custom_entities"].remove(curr_entity)
return descWithTask, sidecar
def find_runs(self):
"""
Check if there is duplicate destination roots in the acquisitions
and add '_run-' to the custom_entities of the acquisition
"""
def duplicates(seq):
""" Find duplicate items in a list
Args:
seq (list)
Yield:
A tuple of 2 items (item, list of index)
ref: http://stackoverflow.com/a/5419576
"""
tally = defaultdict(list)
for i, item in enumerate(seq):
tally[item].append(i)
for key, locs in tally.items():
if len(locs) > 1:
yield key, locs
dstRoots = [_.dstRoot for _ in self.acquisitions]
templateDup = DEFAULT.runTpl
if self.dup_method == 'dup':
templateDup = DEFAULT.dupTpl
for dstRoot, dup in duplicates(dstRoots):
self.logger.info(f"{dstRoot} has {len(dup)} runs")
self.logger.info(f"Adding {self.dup_method} information to the acquisition")
if self.dup_method == 'dup':
dup = dup[0:-1]
for runNum, acqInd in enumerate(dup):
runStr = templateDup.format(runNum+1)
self.acquisitions[acqInd].custom_entities += runStr
self.acquisitions[acqInd].setDstFile()
|