-
-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathnuisance.py
More file actions
2845 lines (2331 loc) · 119 KB
/
Copy pathnuisance.py
File metadata and controls
2845 lines (2331 loc) · 119 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) 2012-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 re
import os
import numpy as np
import nibabel as nb
# pylint: disable=wrong-import-order
from CPAC.pipeline import nipype_pipeline_engine as pe
import nipype.interfaces.utility as util
import CPAC
from nipype import logging
from nipype.interfaces import fsl
from nipype.interfaces import ants
from nipype.interfaces import c3
from nipype.interfaces import afni
from nipype.interfaces.afni import utils as afni_utils
from scipy.fftpack import fft, ifft
from CPAC.utils.interfaces.function import Function
from CPAC.utils.interfaces.masktool import MaskTool
from CPAC.utils.interfaces.pc import PC
from CPAC.registration.registration import warp_timeseries_to_T1template, \
warp_timeseries_to_EPItemplate, apply_transform
from CPAC.aroma.aroma import create_aroma
from CPAC.nuisance.utils import (
find_offending_time_points,
generate_summarize_tissue_mask,
temporal_variance_mask)
from CPAC.nuisance.utils.compcor import (
calc_compcor_components,
cosine_filter,
TR_string_to_float)
from CPAC.seg_preproc.utils import erosion, mask_erosion
from CPAC.utils.datasource import check_for_s3
from CPAC.utils.utils import check_prov_for_regtool
from .bandpass import (bandpass_voxels, afni_1dBandpass)
logger = logging.getLogger('nipype.workflow')
def choose_nuisance_blocks(cfg, generate_only=False):
'''
Function to handle selecting appropriate blocks based on
existing config and resource pool
Parameters
----------
cfg : CPAC.utils.configuration.Configuration
generate_only : boolean
generate but don't run
Returns
-------
nuisance : list
'''
nuisance = []
to_template_cfg = cfg.registration_workflows['functional_registration'][
'func_registration_to_template']
apply_transform_using = to_template_cfg['apply_transform']['using']
input_interface = {
'default': ('desc-preproc_bold', ['desc-preproc_bold', 'bold']),
'abcd': ('desc-preproc_bold', 'bold'),
'single_step_resampling_from_stc': ("desc-preproc_bold",
"desc-stc_bold")
}.get(apply_transform_using)
if input_interface is not None:
if 'T1_template' in to_template_cfg['target_template']['using']:
nuisance.append((nuisance_regressors_generation_T1w,
input_interface))
if 'EPI_template' in to_template_cfg['target_template']['using']:
nuisance.append((nuisance_regressors_generation_EPItemplate,
input_interface))
if not generate_only and 'native' in cfg['nuisance_corrections',
'2-nuisance_regression',
'space']:
nuisance.append((nuisance_regression_native, input_interface))
return nuisance
def erode_mask(name, segmentmap=True):
wf = pe.Workflow(name=name)
inputspec = pe.Node(util.IdentityInterface(fields=['mask',
'erode_mm',
'erode_prop',
'brain_mask',
'mask_erode_mm']),
name='inputspec')
outputspec = pe.Node(util.IdentityInterface(fields=['eroded_mask']),
name='outputspec')
def form_mask_erosion_prop(erosion_prop):
if not isinstance(erosion_prop, (int, float)):
erosion_prop = 0
return erosion_prop ** 3
ero_imports = ['import scipy.ndimage as nd', 'import numpy as np',
'import nibabel as nb', 'import os',
'from CPAC.seg_preproc.utils import _erode']
eroded_mask = pe.Node(util.Function(
input_names=['roi_mask', 'skullstrip_mask', 'mask_erosion_mm',
'mask_erosion_prop'],
output_names=['output_roi_mask', 'eroded_skullstrip_mask'],
function=mask_erosion,
imports=ero_imports),
name='erode_skullstrip_mask',
mem_gb=2.3,
mem_x=(4664065662093477 / 2417851639229258349412352,
'roi_mask'))
wf.connect(inputspec, 'brain_mask', eroded_mask, 'skullstrip_mask')
wf.connect(inputspec, 'mask', eroded_mask, 'roi_mask')
wf.connect(inputspec, ('erode_prop', form_mask_erosion_prop), eroded_mask,
'mask_erosion_prop')
wf.connect(inputspec, 'mask_erode_mm', eroded_mask, 'mask_erosion_mm')
if not segmentmap:
wf.connect(eroded_mask, 'output_roi_mask', outputspec, 'eroded_mask')
if segmentmap:
erosion_segmentmap = pe.Node(util.Function(input_names=['roi_mask',
'erosion_mm',
'erosion_prop'
],
output_names=[
'eroded_roi_mask'],
function=erosion,
imports=ero_imports),
name='erode_mask')
wf.connect(eroded_mask, 'output_roi_mask', erosion_segmentmap, 'roi_mask')
wf.connect(inputspec, 'erode_prop', erosion_segmentmap, 'erosion_prop')
wf.connect(inputspec, 'erode_mm', erosion_segmentmap, 'erosion_mm')
wf.connect(erosion_segmentmap, 'eroded_roi_mask',
outputspec, 'eroded_mask')
return wf
def gather_nuisance(functional_file_path,
selector,
grey_matter_summary_file_path=None,
white_matter_summary_file_path=None,
csf_summary_file_path=None,
acompcor_file_path=None,
tcompcor_file_path=None,
global_summary_file_path=None,
motion_parameters_file_path=None,
custom_file_paths=None,
censor_file_path=None):
"""
Gathers the various nuisance regressors together into a single tab-
separated values file that is an appropriate for input into
3dTproject
:param functional_file_path: path to file that the regressors are
being calculated for, is used to calculate the length of the
regressors for error checking and in particular for calculating
spike regressors
:param output_file_path: path to output TSV that will contain the
various nuisance regressors as columns
:param grey_matter_summary_file_path: path to TSV that includes
summary of grey matter time courses, e.g. output of
mask_summarize_time_course
:param white_matter_summary_file_path: path to TSV that includes
summary of white matter time courses, e.g. output of
mask_summarize_time_course
:param csf_summary_file_path: path to TSV that includes summary of
csf time courses, e.g. output of mask_summarize_time_course
:param acompcor_file_path: path to TSV that includes acompcor time
courses, e.g. output of mask_summarize_time_course
:param tcompcor_file_path: path to TSV that includes tcompcor time
courses, e.g. output of mask_summarize_time_course
:param global_summary_file_path: path to TSV that includes summary
of global time courses, e.g. output of mask_summarize_time_course
:param motion_parameters_file_path: path to TSV that includes
motion parameters
:param custom_file_paths: path to CSV/TSV files to use as regressors
:param censor_file_path: path to TSV with a single column with '1's
for indices that should be retained and '0's for indices that
should be censored
:return: out_file (str), censor_indices (list)
"""
# Basic checks for the functional image
if not functional_file_path or \
(not functional_file_path.endswith(".nii") and
not functional_file_path.endswith(".nii.gz")):
raise ValueError("Invalid value for input_file ({}). Should be a nifti "
"file and should exist".format(functional_file_path))
try:
functional_image = nb.load(functional_file_path)
except:
raise ValueError("Invalid value for input_file ({}). Should be a nifti "
"file and should exist".format(functional_file_path))
if len(functional_image.shape) < 4 or functional_image.shape[3] < 2:
raise ValueError("Invalid input_file ({}). Expected 4D file."
.format(functional_file_path))
regressor_length = functional_image.shape[3]
#selector = selector.selector
if not isinstance(selector, dict):
raise ValueError("Invalid type for selectors {0}, expecting dict"
.format(type(selector)))
regressor_files = {
'aCompCor': acompcor_file_path,
'tCompCor': tcompcor_file_path,
'GlobalSignal': global_summary_file_path,
'GreyMatter': grey_matter_summary_file_path,
'WhiteMatter': white_matter_summary_file_path,
'CerebrospinalFluid': csf_summary_file_path,
'Motion': motion_parameters_file_path,
}
regressors_order = [
'Motion',
'GlobalSignal',
'aCompCor',
'tCompCor',
'CerebrospinalFluid',
'WhiteMatter',
'GreyMatter',
]
motion_labels = ['RotY', 'RotX', 'RotZ', 'Y', 'X', 'Z']
# Compile regressors into a matrix
column_names = []
nuisance_regressors = []
for regressor_type in regressors_order:
if regressor_type not in selector:
continue
regressor_file = regressor_files[regressor_type]
regressor_selector = selector.get(regressor_type) or {}
if 'summary' in regressor_selector:
if type(regressor_selector['summary']) is str:
regressor_selector['summary'] = {
'method': regressor_selector['summary'],
}
if not regressor_file or not os.path.isfile(regressor_file):
raise ValueError("Regressor type {0} specified in selectors "
"but the corresponding file was not found!"
.format(regressor_type))
try:
regressors = np.loadtxt(regressor_file)
except:
print("Could not read regressor {0} from {1}."
.format(regressor_type, regressor_file))
raise
if regressors.shape[0] != regressor_length:
raise ValueError("Number of time points in {0} ({1}) is "
"inconsistent with length of functional "
"file {2} ({3})"
.format(regressor_file,
regressors.shape[0],
functional_file_path,
regressor_length))
if regressor_type == "Motion":
num_regressors = 6
elif not regressor_selector.get('summary', {}).get('components'):
num_regressors = 1
else:
num_regressors = regressor_selector['summary']['components']
if len(regressors.shape) == 1:
regressors = np.expand_dims(regressors, axis=1)
regressors = regressors[:, 0:num_regressors]
if regressors.shape[1] != num_regressors:
raise ValueError("Expecting {0} regressors for {1}, but "
"found {2} in file {3}."
.format(num_regressors,
regressor_type,
regressors.shape[1],
regressor_file))
# Add in the regressors, making sure to also add in the column name
for regressor_index in range(regressors.shape[1]):
if regressor_type == "Motion":
regressor_name = motion_labels[regressor_index]
else:
summary_method = regressor_selector['summary']
if type(summary_method) is dict:
summary_method = summary_method['method']
regressor_name = "{0}{1}{2}".format(regressor_type,
summary_method,
regressor_index)
column_names.append(regressor_name)
nuisance_regressors.append(regressors[:, regressor_index])
if regressor_selector.get('include_delayed', False):
column_names.append("{0}Delay".format(regressor_name))
nuisance_regressors.append(
np.append([0.0], regressors[0:-1, regressor_index])
)
if regressor_selector.get('include_backdiff', False):
column_names.append("{0}BackDiff".format(regressor_name))
nuisance_regressors.append(
np.append([0.0], np.diff(regressors[:, regressor_index], n=1))
)
if regressor_selector.get('include_squared', False):
column_names.append("{0}Sq".format(regressor_name))
nuisance_regressors.append(
np.square(regressors[:, regressor_index])
)
if regressor_selector.get('include_delayed_squared', False):
column_names.append("{0}DelaySq".format(regressor_name))
nuisance_regressors.append(
np.square(
np.append([0.0], regressors[0:-1, regressor_index])
)
)
if regressor_selector.get('include_backdiff_squared', False):
column_names.append("{0}BackDiffSq".format(regressor_name))
nuisance_regressors.append(
np.square(
np.append([0.0], np.diff(regressors[:, regressor_index], n=1))
)
)
# Add custom regressors
if custom_file_paths:
for custom_file_path in custom_file_paths:
try:
custom_regressor = np.loadtxt(custom_file_path)
except:
raise ValueError("Could not read regressor {0} from {1}."
.format('Custom', custom_file_path))
if (len(custom_regressor.shape) > 1 and custom_regressor.shape[1] > 1):
raise ValueError(
"Invalid format for censor file {0}, should be a single "
"column containing 1s for volumes to keep and 0s for volumes "
"to censor.".format(custom_file_path)
)
column_names.append(custom_file_path)
nuisance_regressors.append(custom_regressor)
censor_indices = []
# Add spike regressors
if selector.get('Censor', {}).get('method') == 'SpikeRegression':
selector = selector['Censor']
regressor_file = censor_file_path
if not regressor_file:
# ↓ This section is gross and temporary ↓
num_thresh = len(selector['thresholds'])
plural_s = '' if num_thresh == 1 else 's'
thresh_list = [
thresh.get('value') for thresh in selector['thresholds']
]
print(f"{selector['method']} Censor "
"specified with "
f"{'no ' if num_thresh == 0 else ''}threshold"
f"{plural_s} {str(thresh_list)} in selectors but "
f" threshold was not reached.")
# ↑ This section is gross and temporary ↑
# All good to pass through if nothing to censor
censor_volumes = np.ones((regressor_length,), dtype=int)
else:
try:
censor_volumes = np.loadtxt(regressor_file)
except:
raise ValueError("Could not read regressor {0} from {1}."
.format(regressor_type, regressor_file))
if (len(censor_volumes.shape) > 1 and censor_volumes.shape[1] > 1) or \
not np.all(np.isin(censor_volumes, [0, 1])):
raise ValueError(
"Invalid format for censor file {0}, should be a single "
"column containing 1s for volumes to keep and 0s for volumes "
"to censor.".format(regressor_file)
)
censor_volumes = censor_volumes.flatten()
censor_indices = np.where(censor_volumes == 0)[0]
out_of_range_censors = censor_indices >= regressor_length
if np.any(out_of_range_censors):
raise ValueError(
"Censor volumes {0} are out of range"
"on censor file {1}, calculated "
"regressor length is {2}".format(
censor_indices[out_of_range_censors],
regressor_file,
regressor_length
)
)
if len(censor_indices) > 0:
# if number_of_previous_trs_to_censor and number_of_subsequent_trs_to_censor
# are not set, assume they should be zero
previous_trs_to_censor = \
selector.get('number_of_previous_trs_to_censor', 0)
subsequent_trs_to_censor = \
selector.get('number_of_subsequent_trs_to_censor', 0)
spike_regressors = np.zeros(regressor_length)
for censor_index in censor_indices:
censor_begin_index = censor_index - previous_trs_to_censor
if censor_begin_index < 0:
censor_begin_index = 0
censor_end_index = censor_index + subsequent_trs_to_censor
if censor_end_index >= regressor_length:
censor_end_index = regressor_length - 1
spike_regressors[censor_begin_index:censor_end_index + 1] = 1
for censor_index in np.where(spike_regressors == 1)[0]:
column_names.append("SpikeRegression{0}".format(censor_index))
spike_regressor_index = np.zeros(regressor_length)
spike_regressor_index[censor_index] = 1
nuisance_regressors.append(spike_regressor_index.flatten())
if len(nuisance_regressors) == 0:
return None
# Compile columns into regressor file
output_file_path = os.path.join(os.getcwd(), "nuisance_regressors.1D")
with open(output_file_path, "w") as ofd:
# write out the header information
ofd.write("# C-PAC {0}\n".format(CPAC.__version__))
ofd.write("# Nuisance regressors:\n")
ofd.write("# " + "\t".join(column_names) + "\n")
nuisance_regressors = np.array(nuisance_regressors)
np.savetxt(ofd, nuisance_regressors.T, fmt='%.18f', delimiter='\t')
return output_file_path, censor_indices
def create_regressor_workflow(nuisance_selectors,
use_ants,
ventricle_mask_exist,
csf_mask_exist,
all_bold=False,
name='nuisance_regressors'):
"""
Workflow for the removal of various signals considered to be noise from resting state
fMRI data. The residual signals for linear regression denoising is performed in a single
model. Therefore the residual time-series will be orthogonal to all signals.
Parameters
----------
:param nuisance_selectors: dictionary describing nuisance regression to be performed
:param use_ants: flag indicating whether FNIRT or ANTS is used
:param name: Name of the workflow, defaults to 'nuisance'
:return: nuisance : nipype.pipeline.engine.Workflow
Nuisance workflow.
Notes
-----
Workflow Inputs
---------------
Workflow Inputs::
inputspec.functional_file_path : string (nifti file)
Path to realigned and motion corrected functional image (nifti) file.
inputspec.functional_brain_mask_file_path : string (nifti file)
Whole brain mask corresponding to the functional data.
inputspec.anatomical_file_path : string (nifti file)
Corresponding preprocessed anatomical.
inputspec.wm_mask_file_path : string (nifti file)
Corresponding white matter mask.
inputspec.csf_mask_file_path : string (nifti file)
Corresponding cerebral spinal fluid mask.
inputspec.gm_mask_file_path : string (nifti file)
Corresponding grey matter mask.
inputspec.lat_ventricles_mask_file_path : string (nifti file)
Mask of lateral ventricles calculated from the Harvard Oxford Atlas.
inputspec.mni_to_anat_linear_xfm_file_path: string (nifti file)
FLIRT Linear MNI to Anat transform
inputspec.anat_to_mni_initial_xfm_file_path: string (nifti file)
ANTS initial transform from anat to MNI
inputspec.anat_to_mni_rigid_xfm_file_path: string (nifti file)
ANTS rigid (6 parameter, no scaling) transform from anat to MNI
inputspec.anat_to_mni_affine_xfm_file_path: string (nifti file)
ANTS affine (13 parameter, scales and shears) transform from anat to MNI
inputspec.func_to_anat_linear_xfm_file_path: string (nifti file)
FLIRT Linear Transform between functional and anatomical spaces
inputspec.motion_parameter_file_path : string (text file)
Corresponding rigid-body motion parameters. Matrix in the file should be of shape
(`T`, `R`), `T` time points and `R` motion parameters.
inputspec.fd_j_file_path : string (text file)
Framewise displacement calculated from the volume alignment.
inputspec.fd_p_file_path : string (text file)
Framewise displacement calculated from the motion parameters.
inputspec.dvars_file_path : string (text file)
DVARS calculated from the functional data.
inputspec.selector : Dictionary containing configuration parameters for nuisance regression.
To not run a type of nuisance regression, it may be ommited from the dictionary.
selector = {
aCompCor: {
summary: {
filter: 'cosine', Principal components are estimated after using a discrete cosine filter with 128s cut-off,
Leave filter field blank, if selected aCompcor method is 'DetrendPC'
method: 'DetrendPC', aCompCor will extract the principal components from
detrended tissues signal,
components: number of components to retain,
},
tissues: list of tissues to extract regressors.
Valid values are: 'WhiteMatter', 'CerebrospinalFluid',
extraction_resolution: None | floating point value indicating isotropic
resolution (ex. 2 for 2mm x 2mm x 2mm that data should be extracted at,
the corresponding tissue mask will be resampled to this resolution. The
functional data will also be resampled to this resolution, and the
extraction will occur at this new resolution. The goal is to avoid
contamination from undesired tissue components when extracting nuisance
regressors,
erode_mask: True | False, whether or not the mask should be eroded to
further avoid a mask overlapping with a different tissue class,
include_delayed: True | False, whether or not to include a one-frame delay regressor,
default to False,
include_squared: True | False, whether or not to include a squared regressor,
default to False,
include_delayed_squared: True | False, whether or not to include a squared one-frame
delay regressor, default to False,
include_backdiff: True | False, whether or not to include a one-lag difference,
default to False,
include_backdiff_squared: True | False, whether or not to include a squared one-frame
delay regressor, default to False,
},
tCompCor: {
summary: {
filter: 'cosine', Principal components are estimated after using a discrete cosine filter with 128s cut-off,
Leave filter field blank, if selected tCompcor method is 'DetrendPC'
method: 'DetrendPC', tCompCor will extract the principal components from
detrended tissues signal,
components: number of components to retain,
},
threshold:
floating point number = cutoff as raw variance value,
floating point number followed by SD (ex. 1.5SD) = mean + a multiple of the SD,
floating point number followed by PCT (ex. 2PCT) = percentile from the top (ex is top 2%),
by_slice: True | False, whether or not the threshold criterion should be applied
by slice or across the entire volume, makes most sense for thresholds
using SD or PCT,
include_delayed: True | False (same as for aCompCor),
include_squared: True | False (same as for aCompCor),
include_delayed_squared: True | False (same as for aCompCor),
include_backdiff: True | False (same as for aCompCor),
include_backdiff_squared: True | False (same as for aCompCor),
},
WhiteMatter: {
summary: {
method: 'PC', 'DetrendPC', 'Mean', 'NormMean' or 'DetrendNormMean',
components: number of components to retain, if PC,
},
extraction_resolution: None | floating point value (same as for aCompCor),
erode_mask: True | False (same as for aCompCor),
include_delayed: True | False (same as for aCompCor),
include_squared: True | False (same as for aCompCor),
include_delayed_squared: True | False (same as for aCompCor),
include_backdiff: True | False (same as for aCompCor),
include_backdiff_squared: True | False (same as for aCompCor),
},
CerebrospinalFluid: {
summary: {
method: 'PC', 'DetrendPC', 'Mean', 'NormMean' or 'DetrendNormMean',
components: number of components to retain, if PC,
},
extraction_resolution: None | floating point value (same as for aCompCor),
erode_mask: True | False (same as for aCompCor),
include_delayed: True | False (same as for aCompCor),
include_squared: True | False (same as for aCompCor),
include_delayed_squared: True | False (same as for aCompCor),
include_backdiff: True | False (same as for aCompCor),
include_backdiff_squared: True | False (same as for aCompCor),
},
GreyMatter: {
summary: {
method: 'PC', 'DetrendPC', 'Mean', 'NormMean' or 'DetrendNormMean',
components: number of components to retain, if PC,
},
extraction_resolution: None | floating point value (same as for aCompCor),
erode_mask: True | False (same as for aCompCor),
include_delayed: True | False (same as for aCompCor),
include_squared: True | False (same as for aCompCor),
include_delayed_squared: True | False (same as for aCompCor),
include_backdiff: True | False (same as for aCompCor),
include_backdiff_squared: True | False (same as for aCompCor),
},
GlobalSignal: {
summary: {
method: 'PC', 'DetrendPC', 'Mean', 'NormMean' or 'DetrendNormMean',
components: number of components to retain, if PC,
},
include_delayed: True | False (same as for aCompCor),
include_squared: True | False (same as for aCompCor),
include_delayed_squared: True | False (same as for aCompCor),
include_backdiff: True | False (same as for aCompCor),
include_backdiff_squared: True | False (same as for aCompCor),
},
Motion: None | {
include_delayed: True | False (same as for aCompCor),
include_squared: True | False (same as for aCompCor),
include_delayed_squared: True | False (same as for aCompCor),
include_backdiff: True | False (same as for aCompCor),
include_backdiff_squared: True | False (same as for aCompCor),
},
Censor: {
method: 'Kill', 'Zero', 'Interpolate', 'SpikeRegression',
thresholds: list of dictionary, {
type: 'FD_J', 'FD_P', 'DVARS',
value: threshold value to be applied to metric
},
number_of_previous_trs_to_censor: integer, number of previous
TRs to censor (remove or regress, if spike regression)
number_of_subsequent_trs_to_censor: integer, number of
subsequent TRs to censor (remove or regress, if spike
regression)
},
PolyOrt: {
degree: integer, polynomial degree up to which will be removed,
e.g. 2 means constant + linear + quadratic, practically
that is probably, the most that will be need especially
if band pass filtering
},
Bandpass: {
bottom_frequency: floating point value, frequency in hertz of
the highpass part of the pass band, frequencies below this
will be removed,
top_frequency: floating point value, frequency in hertz of the
lowpass part of the pass band, frequencies above this
will be removed
},
Custom: [
{
file: file containing the regressors. It can be a CSV file,
with one regressor per column, or a Nifti image, with
one regressor per voxel.
convolve: perform the convolution operation of the given
regressor with the timeseries.
}
]
}
Workflow Outputs::
outputspec.residual_file_path : string (nifti file)
Path of residual file in nifti format
outputspec.regressors_file_path : string (TSV file)
Path of TSV file of regressors used. Column name indicates the regressors included .
outputspec.censor_indices : list
Indices of censored volumes
Nuisance Procedure:
1. Compute nuisance regressors based on input selections.
2. Calculate residuals with respect to these nuisance regressors in a
single model for every voxel.
High Level Workflow Graph:
.. exec::
from CPAC.nuisance import create_regressor_workflow
wf = create_regressor_workflow({
'PolyOrt': {'degree': 2},
'tCompCor': {'summary': {'method': 'PC', 'components': 5}, 'threshold': '1.5SD', 'by_slice': True},
'aCompCor': {'summary': {'method': 'PC', 'components': 5}, 'tissues': ['WhiteMatter', 'CerebrospinalFluid'], 'extraction_resolution': 2},
'WhiteMatter': {'summary': {'method': 'PC', 'components': 5}, 'extraction_resolution': 2},
'CerebrospinalFluid': {'summary': {'method': 'PC', 'components': 5}, 'extraction_resolution': 2, 'erode_mask': True},
'GreyMatter': {'summary': {'method': 'PC', 'components': 5}, 'extraction_resolution': 2, 'erode_mask': True},
'GlobalSignal': {'summary': 'Mean', 'include_delayed': True, 'include_squared': True, 'include_delayed_squared': True},
'Motion': {'include_delayed': True, 'include_squared': True, 'include_delayed_squared': True},
'Censor': {'method': 'Interpolate', 'thresholds': [{'type': 'FD_J', 'value': 0.5}, {'type': 'DVARS', 'value': 0.7}]}
}, use_ants=False)
wf.write_graph(
graph2use='orig',
dotfilename='./images/generated/nuisance.dot'
)
.. image:: ../../images/generated/nuisance.png
:width: 1000
Detailed Workflow Graph:
.. image:: ../../images/generated/nuisance_detailed.png
:width: 1000
"""
nuisance_wf = pe.Workflow(name=name)
inputspec = pe.Node(util.IdentityInterface(fields=[
'selector',
'functional_file_path',
'anatomical_file_path',
'anatomical_eroded_brain_mask_file_path',
'gm_mask_file_path',
'wm_mask_file_path',
'csf_mask_file_path',
'lat_ventricles_mask_file_path',
'functional_brain_mask_file_path',
'func_to_anat_linear_xfm_file_path',
'anat_to_func_linear_xfm_file_path',
'mni_to_anat_linear_xfm_file_path',
'anat_to_mni_linear_xfm_file_path',
'motion_parameters_file_path',
'fd_j_file_path',
'fd_p_file_path',
'dvars_file_path',
'creds_path',
'dl_dir',
'tr',
]), name='inputspec')
outputspec = pe.Node(util.IdentityInterface(
fields=['regressors_file_path', 'censor_indices']), name='outputspec')
functional_mean = pe.Node(interface=afni_utils.TStat(),
name='functional_mean')
functional_mean.inputs.options = '-mean'
functional_mean.inputs.outputtype = 'NIFTI_GZ'
nuisance_wf.connect(inputspec, 'functional_file_path',
functional_mean, 'in_file')
# Resources to create regressors
pipeline_resource_pool = {
"Anatomical": (inputspec, 'anatomical_file_path'),
"AnatomicalErodedMask": (inputspec, 'anatomical_eroded_brain_mask_file_path'),
"Functional": (inputspec, 'functional_file_path'),
"Functional_mean" : (functional_mean, 'out_file'),
"GlobalSignal": (inputspec, 'functional_brain_mask_file_path'),
"WhiteMatter": (inputspec, 'wm_mask_file_path'),
"CerebrospinalFluid": (inputspec, 'csf_mask_file_path'),
"GreyMatter": (inputspec, 'gm_mask_file_path'),
"Ventricles": (inputspec, 'lat_ventricles_mask_file_path'),
"Transformations": {
"func_to_anat_linear_xfm": (inputspec, "func_to_anat_linear_xfm_file_path"),
"anat_to_func_linear_xfm": (inputspec, "anat_to_func_linear_xfm_file_path"),
"mni_to_anat_linear_xfm": (inputspec, "mni_to_anat_linear_xfm_file_path"),
"anat_to_mni_linear_xfm": (inputspec, "anat_to_mni_linear_xfm_file_path")
},
"DVARS": (inputspec, 'dvars_file_path'),
"FD_J": (inputspec, 'framewise_displacement_j_file_path'),
"FD_P": (inputspec, 'framewise_displacement_p_file_path'),
"Motion": (inputspec, 'motion_parameters_file_path'),
}
# Regressor map to simplify construction of the needed regressors
regressors = {
'GreyMatter': ['grey_matter_summary_file_path', (), 'ort'],
'WhiteMatter': ['white_matter_summary_file_path', (), 'ort'],
'CerebrospinalFluid': ['csf_summary_file_path', (), 'ort'],
'aCompCor': ['acompcor_file_path', (), 'ort'],
'tCompCor': ['tcompcor_file_path', (), 'ort'],
'GlobalSignal': ['global_summary_file_path', (), 'ort'],
'Custom': ['custom_file_paths', (), 'ort'],
'VoxelCustom': ['custom_file_paths', (), 'dsort'],
'DVARS': ['dvars_file_path', (), 'ort'],
'FD_J': ['framewise_displacement_j_file_path', (), 'ort'],
'FD_P': ['framewise_displacement_p_file_path', (), 'ort'],
'Motion': ['motion_parameters_file_path', (), 'ort']
}
motion = ['DVARS', 'FD_J', 'FD_P', 'Motion']
derived = ['tCompCor', 'aCompCor']
tissues = ['GreyMatter', 'WhiteMatter', 'CerebrospinalFluid']
for regressor_type, regressor_resource in regressors.items():
if regressor_type not in nuisance_selectors:
continue
regressor_selector = nuisance_selectors[regressor_type]
if regressor_type == 'Custom':
custom_ort_check_s3_nodes = []
custom_dsort_check_s3_nodes = []
custom_dsort_convolve_nodes = []
for file_num, custom_regressor in enumerate(sorted(
regressor_selector, key=lambda c: c['file']
)):
custom_regressor_file = custom_regressor['file']
custom_check_s3_node = pe.Node(Function(
input_names=[
'file_path',
'creds_path',
'dl_dir',
'img_type'
],
output_names=[
'local_path'
],
function=check_for_s3,
as_module=True),
name=f'custom_check_for_s3_{name}_{file_num}')
custom_check_s3_node.inputs.set(
file_path=custom_regressor_file,
img_type='func'
)
if (
custom_regressor_file.endswith('.nii.gz') or
custom_regressor_file.endswith('.nii')
):
if custom_regressor.get('convolve'):
custom_dsort_convolve_nodes += [custom_check_s3_node]
else:
custom_dsort_check_s3_nodes += [custom_check_s3_node]
else:
custom_ort_check_s3_nodes += [custom_check_s3_node]
if len(custom_ort_check_s3_nodes) > 0:
custom_ort_merge = pe.Node(
util.Merge(len(custom_ort_check_s3_nodes)),
name='custom_ort_merge'
)
for i, custom_check_s3_node in enumerate(custom_ort_check_s3_nodes):
nuisance_wf.connect(
custom_check_s3_node, 'local_path',
custom_ort_merge, "in{}".format(i + 1)
)
pipeline_resource_pool['custom_ort_file_paths'] = \
(custom_ort_merge, 'out')
regressors['Custom'][1] = \
pipeline_resource_pool['custom_ort_file_paths']
if len(custom_dsort_convolve_nodes) > 0:
custom_dsort_convolve_merge = pe.Node(
util.Merge(len(custom_dsort_convolve_nodes)),
name='custom_dsort_convolve_merge'
)
for i, custom_check_s3_node in enumerate(custom_dsort_convolve_nodes):
nuisance_wf.connect(
custom_check_s3_node, 'local_path',
custom_dsort_convolve_merge, "in{}".format(i + 1)
)
if len(custom_dsort_check_s3_nodes) > 0:
images_to_merge = len(custom_dsort_check_s3_nodes)
if len(custom_dsort_convolve_nodes) > 0:
images_to_merge += 1
custom_dsort_merge = pe.Node(
util.Merge(images_to_merge),
name='custom_dsort_merge'
)
for i, custom_check_s3_node in enumerate(custom_dsort_check_s3_nodes):
nuisance_wf.connect(
custom_check_s3_node, 'local_path',
custom_dsort_merge, "in{}".format(i + 1)
)
if len(custom_dsort_convolve_nodes) > 0:
nuisance_wf.connect(
custom_dsort_convolve_merge, 'out',
custom_dsort_merge, "in{}".format(i + 1)
)
pipeline_resource_pool['custom_dsort_file_paths'] = \
(custom_dsort_merge, 'out')
regressors['VoxelCustom'][1] = \
pipeline_resource_pool['custom_dsort_file_paths']
continue
if regressor_type in motion:
regressor_resource[1] = \
pipeline_resource_pool[regressor_type]
continue
# Set summary method for tCompCor and aCompCor
if regressor_type in derived:
if 'summary' not in regressor_selector:
regressor_selector['summary'] = {}
if type(regressor_selector['summary']) is not dict:
raise ValueError("Regressor {0} requires PC summary method, "
"but {1} specified"
.format(regressor_type,
regressor_selector['summary']))
if not regressor_selector['summary'].get('components'):
regressor_selector['summary']['components'] = 1
# If regressor is not present, build up the regressor
if not regressor_resource[1]:
# We don't have the regressor, look for it in the resource pool,
# build a corresponding key, this is seperated in to a mask key
# and an extraction key, which when concatenated provide the
# resource key for the regressor
regressor_descriptor = {'tissue': regressor_type}
if regressor_type == 'aCompCor':
if not regressor_selector.get('tissues'):
raise ValueError("Tissue type required for aCompCor, "
"but none specified")
regressor_descriptor = {
'tissue': regressor_selector['tissues']
}
if regressor_type == 'tCompCor':
if not regressor_selector.get('threshold'):
raise ValueError("Threshold required for tCompCor, "
"but none specified.")
regressor_descriptor = {
'tissue': 'FunctionalVariance-{}'
.format(regressor_selector['threshold'])
}
if regressor_selector.get('by_slice'):
regressor_descriptor['tissue'] += '-BySlice'
else:
regressor_selector['by_slice'] = False
if regressor_selector.get('erode_mask_mm'):
erosion_mm = regressor_selector['erode_mask_mm']
else: