-
-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathengine.py
More file actions
2305 lines (1989 loc) · 103 KB
/
Copy pathengine.py
File metadata and controls
2305 lines (1989 loc) · 103 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
# Copyright (C) 2021-2023 C-PAC Developers
# This file is part of C-PAC.
# C-PAC is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
# C-PAC is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
# License for more details.
# You should have received a copy of the GNU Lesser General Public
# License along with C-PAC. If not, see <https://www.gnu.org/licenses/>.
import ast
import copy
from itertools import chain
import os
import re
from types import FunctionType
from typing import Tuple, Union
import warnings
from CPAC.pipeline import \
nipype_pipeline_engine as pe # pylint: disable=ungrouped-imports
from nipype.interfaces.utility import \
Rename # pylint: disable=wrong-import-order
from CPAC.func_preproc.func_preproc import motion_estimate_filter
from CPAC.image_utils.spatial_smoothing import spatial_smoothing
from CPAC.image_utils.statistical_transforms import z_score_standardize, \
fisher_z_score_standardize
from CPAC.pipeline.check_outputs import ExpectedOutputs
from CPAC.pipeline.utils import source_set
from CPAC.registration.registration import transform_derivative
from CPAC.utils.bids_utils import insert_entity, res_in_filename
from CPAC.utils.datasource import (
create_anat_datasource,
create_func_datasource,
ingress_func_metadata,
create_general_datasource,
resolve_resolution
)
from CPAC.utils.docs import grab_docstring_dct
from CPAC.utils.interfaces.function import Function
from CPAC.utils.interfaces.datasink import DataSink
from CPAC.utils.monitoring import getLogger, LOGTAIL, \
WARNING_FREESURFER_OFF_WITH_DATA
from CPAC.utils.outputs import Outputs
from CPAC.utils.utils import check_prov_for_regtool, \
create_id_string, get_last_prov_entry, read_json, write_output_json
from CPAC.resources.templates.lookup_table import lookup_identifier
logger = getLogger('nipype.workflow')
class ResourcePool:
def __init__(self, rpool=None, name=None, cfg=None, pipe_list=None):
if not rpool:
self.rpool = {}
else:
self.rpool = rpool
if not pipe_list:
self.pipe_list = []
else:
self.pipe_list = pipe_list
self.name = name
self.info = {}
if cfg:
self.cfg = cfg
self.logdir = cfg.pipeline_setup['log_directory']['path']
self.num_cpus = cfg.pipeline_setup['system_config'][
'max_cores_per_participant']
self.num_ants_cores = cfg.pipeline_setup['system_config'][
'num_ants_threads']
self.ants_interp = cfg.registration_workflows[
'functional_registration']['func_registration_to_template'][
'ANTs_pipelines']['interpolation']
self.fsl_interp = cfg.registration_workflows[
'functional_registration']['func_registration_to_template'][
'FNIRT_pipelines']['interpolation']
self.func_reg = cfg.registration_workflows[
'functional_registration']['func_registration_to_template'][
'run']
self.run_smoothing = 'smoothed' in cfg.post_processing[
'spatial_smoothing']['output']
self.smoothing_bool = cfg.post_processing['spatial_smoothing']['run']
self.run_zscoring = 'z-scored' in cfg.post_processing[
'z-scoring']['output']
self.zscoring_bool = cfg.post_processing['z-scoring']['run']
self.fwhm = cfg.post_processing['spatial_smoothing']['fwhm']
self.smooth_opts = cfg.post_processing['spatial_smoothing'][
'smoothing_method']
self.xfm = ['alff', 'desc-sm_alff', 'desc-zstd_alff',
'desc-sm-zstd_alff',
'falff', 'desc-sm_falff', 'desc-zstd_falff',
'desc-sm-zstd_falff',
'reho', 'desc-sm_reho', 'desc-zstd_reho',
'desc-sm-zstd_reho']
def append_name(self, name):
self.name.append(name)
def back_propogate_template_name(self, resource_idx: str, json_info: dict,
id_string: 'pe.Node') -> None:
"""Find and apply the template name from a resource's provenance
Parameters
----------
resource_idx : str
json_info : dict
id_string : pe.Node
Returns
-------
None
"""
if 'Template' in json_info:
id_string.inputs.template_desc = json_info['Template']
elif ('template' in resource_idx and
len(json_info.get('CpacProvenance', [])) > 1):
for resource in source_set(json_info['CpacProvenance']):
source, value = resource.split(':', 1)
if value.startswith('template_'
) and source != 'FSL-AFNI-bold-ref':
# 'FSL-AFNI-bold-ref' is currently allowed to be in
# a different space, so don't use it as the space for
# descendents
try:
anscestor_json = list(self.rpool.get(source).items()
)[0][1].get('json', {})
if 'Description' in anscestor_json:
id_string.inputs.template_desc = anscestor_json[
'Description']
return
except (IndexError, KeyError):
pass
return
def get_name(self):
return self.name
def check_rpool(self, resource):
if not isinstance(resource, list):
resource = [resource]
for name in resource:
if name in self.rpool:
return True
return False
def get_pipe_number(self, pipe_idx):
return self.pipe_list.index(pipe_idx)
def get_pool_info(self):
return self.info
def set_pool_info(self, info_dct):
self.info.update(info_dct)
def get_entire_rpool(self):
return self.rpool
def get_resources(self):
return self.rpool.keys()
def copy_rpool(self):
return ResourcePool(rpool=copy.deepcopy(self.get_entire_rpool()),
name=self.name,
cfg=self.cfg,
pipe_list=copy.deepcopy(self.pipe_list))
def get_raw_label(self, resource):
# remove desc-* label
for tag in resource.split('_'):
if 'desc-' in tag:
resource = resource.replace(f'{tag}_', '')
break
return resource
def get_strat_info(self, prov, label=None, logdir=None):
strat_info = {}
for entry in prov:
if isinstance(entry, list):
strat_info[entry[-1].split(':')[0]] = entry
elif isinstance(entry, str):
strat_info[entry.split(':')[0]] = entry.split(':')[1]
if label:
if not logdir:
logdir = self.logdir
print(f'\n\nPrinting out strategy info for {label} in {logdir}\n')
write_output_json(strat_info, f'{label}_strat_info',
indent=4, basedir=logdir)
def set_json_info(self, resource, pipe_idx, key, val):
#TODO: actually should probably be able to inititialize resource/pipe_idx
if pipe_idx not in self.rpool[resource]:
raise Exception('\n[!] DEV: The pipeline/strat ID does not exist '
f'in the resource pool.\nResource: {resource}'
f'Pipe idx: {pipe_idx}\nKey: {key}\nVal: {val}\n')
else:
if 'json' not in self.rpool[resource][pipe_idx]:
self.rpool[resource][pipe_idx]['json'] = {}
self.rpool[resource][pipe_idx]['json'][key] = val
def get_json_info(self, resource, pipe_idx, key):
#TODO: key checks
if not pipe_idx:
for pipe_idx, val in self.rpool[resource].items():
return val['json'][key]
return self.rpool[resource][pipe_idx][key]
def get_resource_from_prov(self, prov):
# each resource (i.e. "desc-cleaned_bold" AKA nuisance-regressed BOLD
# data) has its own provenance list. the name of the resource, and
# the node that produced it, is always the last item in the provenance
# list, with the two separated by a colon :
if not len(prov):
return None
if isinstance(prov[-1], list):
return prov[-1][-1].split(':')[0]
elif isinstance(prov[-1], str):
return prov[-1].split(':')[0]
def set_data(self, resource, node, output, json_info, pipe_idx, node_name,
fork=False, inject=False):
json_info = json_info.copy()
cpac_prov = []
if 'CpacProvenance' in json_info:
cpac_prov = json_info['CpacProvenance']
current_prov_list = list(cpac_prov)
new_prov_list = list(cpac_prov) # <---- making a copy, it was already a list
if not inject:
new_prov_list.append(f'{resource}:{node_name}')
try:
res, new_pipe_idx = self.generate_prov_string(new_prov_list)
except IndexError:
raise IndexError(f'\n\nThe set_data() call for {resource} has no '
'provenance information and should not be an '
'injection.')
if not json_info:
json_info = {'RawSources': [resource]} # <---- this will be repopulated to the full file path at the end of the pipeline building, in gather_pipes()
json_info['CpacProvenance'] = new_prov_list
if resource not in self.rpool.keys():
self.rpool[resource] = {}
else:
if not fork: # <--- in the event of multiple strategies/options, this will run for every option; just keep in mind
search = False
if self.get_resource_from_prov(current_prov_list) == resource:
pipe_idx = self.generate_prov_string(current_prov_list)[1] # CHANGING PIPE_IDX, BE CAREFUL DOWNSTREAM IN THIS FUNCTION
if pipe_idx not in self.rpool[resource].keys():
search = True
else:
search = True
if search:
for idx in current_prov_list:
if self.get_resource_from_prov(idx) == resource:
if isinstance(idx, list):
pipe_idx = self.generate_prov_string(idx)[1] # CHANGING PIPE_IDX, BE CAREFUL DOWNSTREAM IN THIS FUNCTION
elif isinstance(idx, str):
pipe_idx = idx
break
if pipe_idx in self.rpool[resource].keys(): # <--- in case the resource name is now new, and not the original
del self.rpool[resource][pipe_idx] # <--- remove old keys so we don't end up with a new strat for every new node unit (unless we fork)
if new_pipe_idx not in self.rpool[resource]:
self.rpool[resource][new_pipe_idx] = {}
if new_pipe_idx not in self.pipe_list:
self.pipe_list.append(new_pipe_idx)
self.rpool[resource][new_pipe_idx]['data'] = (node, output)
self.rpool[resource][new_pipe_idx]['json'] = json_info
def get(self, resource, pipe_idx=None, report_fetched=False,
optional=False):
# NOTE!!!
# if this is the main rpool, this will return a dictionary of strats, and inside those, are dictionaries like {'data': (node, out), 'json': info}
# BUT, if this is a sub rpool (i.e. a strat_pool), this will return a one-level dictionary of {'data': (node, out), 'json': info} WITHOUT THE LEVEL OF STRAT KEYS ABOVE IT
info_msg = "\n\n[!] C-PAC says: None of the listed resources are in " \
f"the resource pool:\n\n {resource}\n\nOptions:\n- You " \
"can enable a node block earlier in the pipeline which " \
"produces these resources. Check the 'outputs:' field in " \
"a node block's documentation.\n- You can directly " \
"provide this required data by pulling it from another " \
"BIDS directory using 'source_outputs_dir:' in the " \
"pipeline configuration, or by placing it directly in " \
"your C-PAC output directory.\n- If you have done these, " \
"and you still get this message, please let us know " \
"through any of our support channels at: " \
"https://fcp-indi.github.io/\n"
if isinstance(resource, list):
# if a list of potential inputs are given, pick the first one
# found
for label in resource:
if label in self.rpool.keys():
if report_fetched:
return (self.rpool[label], label)
return self.rpool[label]
else:
if optional:
if report_fetched:
return (None, None)
return None
raise LookupError(info_msg)
else:
if resource not in self.rpool.keys():
if optional:
if report_fetched:
return (None, None)
return None
raise LookupError(info_msg)
if report_fetched:
if pipe_idx:
return (self.rpool[resource][pipe_idx], resource)
return (self.rpool[resource], resource)
if pipe_idx:
return self.rpool[resource][pipe_idx]
return self.rpool[resource]
def get_data(self, resource, pipe_idx=None, report_fetched=False,
quick_single=False):
if report_fetched:
if pipe_idx:
connect, fetched = self.get(resource, pipe_idx=pipe_idx,
report_fetched=report_fetched)
return (connect['data'], fetched)
connect, fetched =self.get(resource,
report_fetched=report_fetched)
return (connect['data'], fetched)
elif pipe_idx:
return self.get(resource, pipe_idx=pipe_idx)['data']
elif quick_single or len(self.get(resource)) == 1:
for key, val in self.get(resource).items():
return val['data']
return self.get(resource)['data']
def copy_resource(self, resource, new_name):
try:
self.rpool[new_name] = self.rpool[resource]
except KeyError:
raise Exception(f"[!] {resource} not in the resource pool.")
def update_resource(self, resource, new_name):
# move over any new pipe_idx's
self.rpool[new_name].update(self.rpool[resource])
def get_pipe_idxs(self, resource):
return self.rpool[resource].keys()
def get_json(self, resource, strat=None):
# NOTE: resource_strat_dct has to be entered properly by the developer
# it has to either be rpool[resource][strat] or strat_pool[resource]
if strat:
resource_strat_dct = self.rpool[resource][strat]
else:
# for strat_pools mainly, where there is no 'strat' key level
resource_strat_dct = self.rpool[resource]
# TODO: the below hits the exception if you use get_cpac_provenance on
# TODO: the main rpool (i.e. if strat=None)
if 'json' in resource_strat_dct:
strat_json = resource_strat_dct['json']
else:
raise Exception('\n[!] Developer info: the JSON '
f'information for {resource} and {strat} '
f'is incomplete.\n')
return strat_json
def get_cpac_provenance(self, resource, strat=None):
# NOTE: resource_strat_dct has to be entered properly by the developer
# it has to either be rpool[resource][strat] or strat_pool[resource]
json_data = self.get_json(resource, strat)
return json_data['CpacProvenance']
def generate_prov_string(self, prov):
# this will generate a string from a SINGLE RESOURCE'S dictionary of
# MULTIPLE PRECEDING RESOURCES (or single, if just one)
# NOTE: this DOES NOT merge multiple resources!!! (i.e. for merging-strat pipe_idx generation)
if not isinstance(prov, list):
raise Exception('\n[!] Developer info: the CpacProvenance '
f'entry for {prov} has to be a list.\n')
last_entry = get_last_prov_entry(prov)
resource = last_entry.split(':')[0]
return (resource, str(prov))
def generate_prov_list(self, prov_str):
if not isinstance(prov_str, str):
raise Exception('\n[!] Developer info: the CpacProvenance '
f'entry for {str(prov_str)} has to be a string.\n')
return ast.literal_eval(prov_str)
def get_resource_strats_from_prov(self, prov):
# if you provide the provenance of a resource pool output, this will
# return a dictionary of all the preceding resource pool entries that
# led to that one specific output:
# {rpool entry}: {that entry's provenance}
# {rpool entry}: {that entry's provenance}
resource_strat_dct = {}
if isinstance(prov, str):
resource = prov.split(':')[0]
resource_strat_dct[resource] = prov
else:
for spot, entry in enumerate(prov):
if isinstance(entry, list):
resource = entry[-1].split(':')[0]
resource_strat_dct[resource] = entry
elif isinstance(entry, str):
resource = entry.split(':')[0]
resource_strat_dct[resource] = entry
return resource_strat_dct
def flatten_prov(self, prov):
if isinstance(prov, str):
return [prov]
elif isinstance(prov, list):
flat_prov = []
for entry in prov:
if isinstance(entry, list):
flat_prov += self.flatten_prov(entry)
else:
flat_prov.append(entry)
return flat_prov
def get_strats(self, resources, debug=False):
# TODO: NOTE: NOT COMPATIBLE WITH SUB-RPOOL/STRAT_POOLS
# TODO: (and it doesn't have to be)
import itertools
linked_resources = []
resource_list = []
if debug:
verbose_logger = getLogger('engine')
verbose_logger.debug('\nresources: %s', resources)
for resource in resources:
# grab the linked-input tuples
if isinstance(resource, tuple):
linked = []
for label in list(resource):
rp_dct, fetched_resource = self.get(label,
report_fetched=True,
optional=True)
if not rp_dct:
continue
linked.append(fetched_resource)
resource_list += linked
if len(linked) < 2:
continue
linked_resources.append(linked)
else:
resource_list.append(resource)
total_pool = []
variant_pool = {}
len_inputs = len(resource_list)
if debug:
verbose_logger = getLogger('engine')
verbose_logger.debug('linked_resources: %s',
linked_resources)
verbose_logger.debug('resource_list: %s', resource_list)
for resource in resource_list:
rp_dct, fetched_resource = self.get(resource,
report_fetched=True, # <---- rp_dct has the strats/pipe_idxs as the keys on first level, then 'data' and 'json' on each strat level underneath
optional=True) # oh, and we make the resource fetching in get_strats optional so we can have optional inputs, but they won't be optional in the node block unless we want them to be
if not rp_dct:
len_inputs -= 1
continue
sub_pool = []
if debug:
verbose_logger = getLogger('engine')
verbose_logger.debug('%s len(rp_dct): %s\n', resource, len(rp_dct))
for strat in rp_dct.keys():
json_info = self.get_json(fetched_resource, strat)
cpac_prov = json_info['CpacProvenance']
sub_pool.append(cpac_prov)
if fetched_resource not in variant_pool:
variant_pool[fetched_resource] = []
if 'CpacVariant' in json_info:
for key, val in json_info['CpacVariant'].items():
if val not in variant_pool[fetched_resource]:
variant_pool[fetched_resource] += val
variant_pool[fetched_resource].append(
f'NO-{val[0]}')
if debug:
verbose_logger.debug('%s sub_pool: %s\n', resource, sub_pool)
total_pool.append(sub_pool)
if not total_pool:
raise LookupError('\n\n[!] C-PAC says: None of the listed '
'resources in the node block being connected '
'exist in the resource pool.\n\nResources:\n'
'%s\n\n' % resource_list)
# TODO: right now total_pool is:
# TODO: [[[T1w:anat_ingress, desc-preproc_T1w:anatomical_init, desc-preproc_T1w:acpc_alignment], [T1w:anat_ingress,desc-preproc_T1w:anatomical_init]],
# TODO: [[T1w:anat_ingress, desc-preproc_T1w:anatomical_init, desc-preproc_T1w:acpc_alignment, desc-brain_mask:brain_mask_afni], [T1w:anat_ingress, desc-preproc_T1w:anatomical_init, desc-brain_mask:brain_mask_afni]]]
# TODO: and the code below thinks total_pool is a list of lists, like [[pipe_idx, pipe_idx], [pipe_idx, pipe_idx, pipe_idx], etc.]
# TODO: and the actual resource is encoded in the tag: of the last item, every time!
# keying the strategies to the resources, inverting it
if len_inputs > 1:
strats = itertools.product(*total_pool)
# we now currently have "strats", the combined permutations of all the strategies, as a list of tuples, each tuple combining one version of input each, being one of the permutations.
# OF ALL THE DIFFERENT INPUTS. and they are tagged by their fetched inputs with {name}:{strat}.
# so, each tuple has ONE STRAT FOR EACH INPUT, so if there are three inputs, each tuple will have 3 items.
new_strats = {}
# get rid of duplicates - TODO: refactor .product
strat_str_list = []
strat_list_list = []
for strat_tuple in strats:
strat_list = list(copy.deepcopy(strat_tuple))
strat_str = str(strat_list)
if strat_str not in strat_str_list:
strat_str_list.append(strat_str)
strat_list_list.append(strat_list)
if debug:
verbose_logger.debug('len(strat_list_list): %s\n',
len(strat_list_list))
for strat_list in strat_list_list:
json_dct = {}
for strat in strat_list:
# strat is a prov list for a single resource/input
strat_resource, strat_idx = \
self.generate_prov_string(strat)
strat_json = self.get_json(strat_resource,
strat=strat_idx)
json_dct[strat_resource] = strat_json
drop = False
if linked_resources:
for linked in linked_resources: # <--- 'linked' is each tuple
if drop:
break
for xlabel in linked:
if drop:
break
xjson = copy.deepcopy(json_dct[xlabel])
for ylabel in linked:
if xlabel == ylabel:
continue
yjson = copy.deepcopy(json_dct[ylabel])
if 'CpacVariant' not in xjson:
xjson['CpacVariant'] = {}
if 'CpacVariant' not in yjson:
yjson['CpacVariant'] = {}
current_strat = []
for key, val in xjson['CpacVariant'].items():
if isinstance(val, list):
current_strat.append(val[0])
else:
current_strat.append(val)
current_spread = list(set(variant_pool[xlabel]))
for spread_label in current_spread:
if 'NO-' in spread_label:
continue
if spread_label not in current_strat:
current_strat.append(f'NO-{spread_label}')
other_strat = []
for key, val in yjson['CpacVariant'].items():
if isinstance(val, list):
other_strat.append(val[0])
else:
other_strat.append(val)
other_spread = list(set(variant_pool[ylabel]))
for spread_label in other_spread:
if 'NO-' in spread_label:
continue
if spread_label not in other_strat:
other_strat.append(f'NO-{spread_label}')
for variant in current_spread:
in_current_strat = False
in_other_strat = False
in_other_spread = False
if variant is None:
in_current_strat = True
if None in other_spread:
in_other_strat = True
if variant in current_strat:
in_current_strat = True
if variant in other_strat:
in_other_strat = True
if variant in other_spread:
in_other_spread = True
if not in_other_strat:
if in_other_spread:
if in_current_strat:
drop = True
break
if in_other_strat:
if in_other_spread:
if not in_current_strat:
drop = True
break
if drop:
break
if drop:
continue
# make the merged strat label from the multiple inputs
# strat_list is actually the merged CpacProvenance lists
pipe_idx = str(strat_list)
new_strats[pipe_idx] = ResourcePool() # <----- new_strats is A DICTIONARY OF RESOURCEPOOL OBJECTS!
# placing JSON info at one level higher only for copy convenience
new_strats[pipe_idx].rpool['json'] = {}
new_strats[pipe_idx].rpool['json']['subjson'] = {}
new_strats[pipe_idx].rpool['json']['CpacProvenance'] = strat_list
# now just invert resource:strat to strat:resource for each resource:strat
for cpac_prov in strat_list:
resource, strat = self.generate_prov_string(cpac_prov)
resource_strat_dct = self.rpool[resource][strat] # <----- remember, this is the dct of 'data' and 'json'.
new_strats[pipe_idx].rpool[resource] = resource_strat_dct # <----- new_strats is A DICTIONARY OF RESOURCEPOOL OBJECTS! each one is a new slice of the resource pool combined together.
self.pipe_list.append(pipe_idx)
if 'CpacVariant' in resource_strat_dct['json']:
if 'CpacVariant' not in new_strats[pipe_idx].rpool['json']:
new_strats[pipe_idx].rpool['json']['CpacVariant'] = {}
for younger_resource, variant_list in resource_strat_dct['json']['CpacVariant'].items():
if younger_resource not in new_strats[pipe_idx].rpool['json']['CpacVariant']:
new_strats[pipe_idx].rpool['json']['CpacVariant'][younger_resource] = variant_list
# preserve each input's JSON info also
data_type = resource.split('_')[-1]
if data_type not in new_strats[pipe_idx].rpool['json']['subjson']:
new_strats[pipe_idx].rpool['json']['subjson'][data_type] = {}
new_strats[pipe_idx].rpool['json']['subjson'][data_type].update(copy.deepcopy(resource_strat_dct['json']))
else:
new_strats = {}
for resource_strat_list in total_pool: # total_pool will have only one list of strats, for the one input
for cpac_prov in resource_strat_list: # <------- cpac_prov here doesn't need to be modified, because it's not merging with other inputs
resource, pipe_idx = self.generate_prov_string(cpac_prov)
resource_strat_dct = self.rpool[resource][pipe_idx] # <----- remember, this is the dct of 'data' and 'json'.
new_strats[pipe_idx] = ResourcePool(rpool={resource: resource_strat_dct}) # <----- again, new_strats is A DICTIONARY OF RESOURCEPOOL OBJECTS!
# placing JSON info at one level higher only for copy convenience
new_strats[pipe_idx].rpool['json'] = resource_strat_dct['json'] # TODO: WARNING- THIS IS A LEVEL HIGHER THAN THE ORIGINAL 'JSON' FOR EASE OF ACCESS IN CONNECT_BLOCK WITH THE .GET(JSON)
new_strats[pipe_idx].rpool['json']['subjson'] = {}
new_strats[pipe_idx].rpool['json']['CpacProvenance'] = cpac_prov
# preserve each input's JSON info also
data_type = resource.split('_')[-1]
if data_type not in new_strats[pipe_idx].rpool['json']['subjson']:
new_strats[pipe_idx].rpool['json']['subjson'][data_type] = {}
new_strats[pipe_idx].rpool['json']['subjson'][data_type].update(copy.deepcopy(resource_strat_dct['json']))
return new_strats
def derivative_xfm(self, wf, label, connection, json_info, pipe_idx,
pipe_x):
if label in self.xfm:
json_info = dict(json_info)
# get the bold-to-template transform from the current strat_pool
# info
xfm_idx = None
xfm_label = 'from-bold_to-template_mode-image_xfm'
for entry in json_info['CpacProvenance']:
if isinstance(entry, list):
if entry[-1].split(':')[0] == xfm_label:
xfm_prov = entry
xfm_idx = self.generate_prov_string(xfm_prov)[1]
break
# but if the resource doesn't have the bold-to-template transform
# in its provenance/strategy, find the appropriate one for this
# current pipe_idx/strat
if not xfm_idx:
xfm_info = []
for pipe_idx, entry in self.get(xfm_label).items():
xfm_info.append((pipe_idx, entry['json']['CpacProvenance']))
else:
xfm_info = [(xfm_idx, xfm_prov)]
for num, xfm_entry in enumerate(xfm_info):
xfm_idx, xfm_prov = xfm_entry
reg_tool = check_prov_for_regtool(xfm_prov)
xfm = transform_derivative(f'{label}_xfm_{pipe_x}_{num}',
label, reg_tool, self.num_cpus,
self.num_ants_cores,
ants_interp=self.ants_interp,
fsl_interp=self.fsl_interp,
opt=None)
wf.connect(connection[0], connection[1],
xfm, 'inputspec.in_file')
node, out = self.get_data("T1w-brain-template-deriv",
quick_single=True)
wf.connect(node, out, xfm, 'inputspec.reference')
node, out = self.get_data('from-bold_to-template_mode-image_xfm',
pipe_idx=xfm_idx)
wf.connect(node, out, xfm, 'inputspec.transform')
label = f'space-template_{label}'
json_info['Template'] = self.get_json_info('T1w-brain-template-deriv',
None, 'Description')
new_prov = json_info['CpacProvenance'] + xfm_prov
json_info['CpacProvenance'] = new_prov
new_pipe_idx = self.generate_prov_string(new_prov)
self.set_data(label, xfm, 'outputspec.out_file', json_info,
new_pipe_idx, f'{label}_xfm_{num}', fork=True)
return wf
def post_process(self, wf, label, connection, json_info, pipe_idx, pipe_x,
outs):
input_type = 'func_derivative'
post_labels = [(label, connection[0], connection[1])]
if re.match(r'(.*_)?[ed]c[bw]$', label) or re.match(r'(.*_)?lfcd[bw]$',
label):
# suffix: [eigenvector or degree] centrality [binarized or weighted]
# or lfcd [binarized or weighted]
mask = 'template-specification-file'
elif 'space-template' in label:
mask = 'space-template_res-derivative_desc-bold_mask'
else:
mask = 'space-bold_desc-brain_mask'
mask_idx = None
for entry in json_info['CpacProvenance']:
if isinstance(entry, list):
if entry[-1].split(':')[0] == mask:
mask_prov = entry
mask_idx = self.generate_prov_string(mask_prov)[1]
break
if self.smoothing_bool:
if label in Outputs.to_smooth:
for smooth_opt in self.smooth_opts:
sm = spatial_smoothing(f'{label}_smooth_{smooth_opt}_'
f'{pipe_x}',
self.fwhm, input_type, smooth_opt)
wf.connect(connection[0], connection[1],
sm, 'inputspec.in_file')
node, out = self.get_data(mask, pipe_idx=mask_idx,
quick_single=mask_idx is None)
wf.connect(node, out, sm, 'inputspec.mask')
if 'desc-' not in label:
if 'space-' in label:
for tag in label.split('_'):
if 'space-' in tag:
smlabel = label.replace(tag,
f'{tag}_desc-sm')
break
else:
smlabel = f'desc-sm_{label}'
else:
for tag in label.split('_'):
if 'desc-' in tag:
newtag = f'{tag}-sm'
smlabel = label.replace(tag, newtag)
break
post_labels.append((smlabel, sm, 'outputspec.out_file'))
self.set_data(smlabel, sm, 'outputspec.out_file',
json_info, pipe_idx,
f'spatial_smoothing_{smooth_opt}',
fork=True)
self.set_data('fwhm', sm, 'outputspec.fwhm', json_info,
pipe_idx, f'spatial_smoothing_{smooth_opt}',
fork=True)
if self.zscoring_bool:
for label_con_tpl in post_labels:
label = label_con_tpl[0]
connection = (label_con_tpl[1], label_con_tpl[2])
if label in Outputs.to_zstd:
zstd = z_score_standardize(f'{label}_zstd_{pipe_x}',
input_type)
wf.connect(connection[0], connection[1],
zstd, 'inputspec.in_file')
node, out = self.get_data(mask, pipe_idx=mask_idx)
wf.connect(node, out, zstd, 'inputspec.mask')
if 'desc-' not in label:
if 'space-template' in label:
new_label = label.replace('space-template',
'space-template_desc-zstd')
else:
new_label = f'desc-zstd_{label}'
else:
for tag in label.split('_'):
if 'desc-' in tag:
newtag = f'{tag}-zstd'
new_label = label.replace(tag, newtag)
break
post_labels.append((new_label, zstd, 'outputspec.out_file'))
self.set_data(new_label, zstd, 'outputspec.out_file',
json_info, pipe_idx, f'zscore_standardize',
fork=True)
elif label in Outputs.to_fisherz:
zstd = fisher_z_score_standardize(f'{label}_zstd_{pipe_x}',
label, input_type)
wf.connect(connection[0], connection[1],
zstd, 'inputspec.correlation_file')
# if the output is 'space-template_desc-MeanSCA_correlations', we want
# 'desc-MeanSCA_timeseries'
oned = label.replace('correlations', 'timeseries')
node, out = outs[oned]
wf.connect(node, out, zstd, 'inputspec.timeseries_oned')
post_labels.append((new_label, zstd, 'outputspec.out_file'))
self.set_data(new_label, zstd, 'outputspec.out_file',
json_info, pipe_idx,
'fisher_zscore_standardize',
fork=True)
return (wf, post_labels)
def gather_pipes(self, wf, cfg, all=False, add_incl=None, add_excl=None):
excl = []
substring_excl = []
outputs_logger = getLogger(f'{cfg["subject_id"]}_expectedOutputs')
expected_outputs = ExpectedOutputs()
movement_filter_keys = grab_docstring_dct(motion_estimate_filter).get(
'outputs', [])
if add_excl:
excl += add_excl
if 'unsmoothed' not in cfg.post_processing['spatial_smoothing'][
'output']:
excl += Outputs.native_nonsmooth
excl += Outputs.template_nonsmooth
if 'raw' not in cfg.post_processing['z-scoring']['output']:
excl += Outputs.native_raw
excl += Outputs.template_raw
if not cfg.pipeline_setup['output_directory']['write_debugging_outputs']:
# substring_excl.append(['bold'])
excl += Outputs.debugging
for resource in self.rpool.keys():
if resource not in Outputs.any:
continue
if resource in excl:
continue
drop = False
for substring_list in substring_excl:
bool_list = []
for substring in substring_list:
if substring in resource:
bool_list.append(True)
else:
bool_list.append(False)
for item in bool_list:
if not item:
break
else:
drop = True
if drop:
break
if drop:
continue
subdir = 'other'
if resource in Outputs.anat:
subdir = 'anat'
#TODO: get acq- etc.
elif resource in Outputs.func:
subdir = 'func'
#TODO: other stuff like acq- etc.
for pipe_idx in self.rpool[resource]:
unique_id = self.get_name()
part_id = unique_id.split('_')[0]
ses_id = unique_id.split('_')[1]
if 'ses-' not in ses_id:
ses_id = f"ses-{ses_id}"
out_dir = cfg.pipeline_setup['output_directory']['path']
pipe_name = cfg.pipeline_setup['pipeline_name']
container = os.path.join(f'pipeline_{pipe_name}', part_id,
ses_id)
filename = f'{unique_id}_{res_in_filename(self.cfg, resource)}'
out_path = os.path.join(out_dir, container, subdir, filename)
out_dct = {
'unique_id': unique_id,
'out_dir': out_dir,
'container': container,
'subdir': subdir,
'filename': filename,
'out_path': out_path
}
self.rpool[resource][pipe_idx]['out'] = out_dct
# TODO: have to link the pipe_idx's here. and call up 'desc-preproc_T1w' from a Sources in a json and replace. here.
# TODO: can do the pipeline_description.json variants here too!
for resource in self.rpool.keys():
if resource not in Outputs.any:
continue
if resource in excl:
continue
drop = False
for substring_list in substring_excl:
bool_list = []
for substring in substring_list:
if substring in resource:
bool_list.append(True)
else:
bool_list.append(False)
for item in bool_list:
if not item:
break
else:
drop = True
if drop:
break
if drop:
continue
num_variant = 0
if len(self.rpool[resource]) == 1:
num_variant = ""
all_jsons = [self.rpool[resource][pipe_idx]['json'] for pipe_idx in
self.rpool[resource]]
unlabelled = set(key for json_info in all_jsons for key in
json_info.get('CpacVariant', {}).keys() if
key not in (*movement_filter_keys, 'regressors'))
if 'bold' in unlabelled:
all_bolds = list(
chain.from_iterable(json_info['CpacVariant']['bold'] for
json_info in all_jsons if
'CpacVariant' in json_info and
'bold' in json_info['CpacVariant']))
# not any(not) because all is overloaded as a parameter here
if not any(not re.match(r'apply_(phasediff|blip)_to_'
r'timeseries_separately_.*', _bold)
for _bold in all_bolds):
# this fork point should only result in 0 or 1 forks
unlabelled.remove('bold')
del all_bolds
all_forks = {key: set(
chain.from_iterable(json_info['CpacVariant'][key] for
json_info in all_jsons if
'CpacVariant' in json_info and
key in json_info['CpacVariant'])) for
key in unlabelled}
# del all_jsons
for key, forks in all_forks.items():
if len(forks) < 2: # no int suffix needed if only one fork
unlabelled.remove(key)
# del all_forks
for pipe_idx in self.rpool[resource]:
pipe_x = self.get_pipe_number(pipe_idx)
json_info = self.rpool[resource][pipe_idx]['json']
out_dct = self.rpool[resource][pipe_idx]['out']
try: