/
confounds.py
797 lines (696 loc) · 32.5 KB
/
confounds.py
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
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
Calculate BOLD confounds
^^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: init_bold_confs_wf
.. autofunction:: init_ica_aroma_wf
"""
from os import getenv
from nipype.algorithms import confounds as nac
from nipype.interfaces import utility as niu, fsl
from nipype.pipeline import engine as pe
from templateflow.api import get as get_template
from ...config import DEFAULT_MEMORY_MIN_GB
from ...interfaces import (
GatherConfounds, ICAConfounds, FMRISummary, DerivativesDataSink
)
def init_bold_confs_wf(
mem_gb,
metadata,
regressors_all_comps,
regressors_dvars_th,
regressors_fd_th,
freesurfer=False,
name="bold_confs_wf",
):
"""
Build a workflow to generate and write out confounding signals.
This workflow calculates confounds for a BOLD series, and aggregates them
into a :abbr:`TSV (tab-separated value)` file, for use as nuisance
regressors in a :abbr:`GLM (general linear model)`.
The following confounds are calculated, with column headings in parentheses:
#. Region-wise average signal (``csf``, ``white_matter``, ``global_signal``)
#. DVARS - original and standardized variants (``dvars``, ``std_dvars``)
#. Framewise displacement, based on head-motion parameters
(``framewise_displacement``)
#. Temporal CompCor (``t_comp_cor_XX``)
#. Anatomical CompCor (``a_comp_cor_XX``)
#. Cosine basis set for high-pass filtering w/ 0.008 Hz cut-off
(``cosine_XX``)
#. Non-steady-state volumes (``non_steady_state_XX``)
#. Estimated head-motion parameters, in mm and rad
(``trans_x``, ``trans_y``, ``trans_z``, ``rot_x``, ``rot_y``, ``rot_z``)
Prior to estimating aCompCor and tCompCor, non-steady-state volumes are
censored and high-pass filtered using a :abbr:`DCT (discrete cosine
transform)` basis.
The cosine basis, as well as one regressor per censored volume, are included
for convenience.
Workflow Graph
.. workflow::
:graph2use: orig
:simple_form: yes
from fmriprep.workflows.bold.confounds import init_bold_confs_wf
wf = init_bold_confs_wf(
mem_gb=1,
metadata={},
regressors_all_comps=False,
regressors_dvars_th=1.5,
regressors_fd_th=0.5,
)
Parameters
----------
mem_gb : :obj:`float`
Size of BOLD file in GB - please note that this size
should be calculated after resamplings that may extend
the FoV
metadata : :obj:`dict`
BIDS metadata for BOLD file
name : :obj:`str`
Name of workflow (default: ``bold_confs_wf``)
regressors_all_comps : :obj:`bool`
Indicates whether CompCor decompositions should return all
components instead of the minimal number of components necessary
to explain 50 percent of the variance in the decomposition mask.
regressors_dvars_th : :obj:`float`
Criterion for flagging DVARS outliers
regressors_fd_th : :obj:`float`
Criterion for flagging framewise displacement outliers
Inputs
------
bold
BOLD image, after the prescribed corrections (STC, HMC and SDC)
when available.
bold_mask
BOLD series mask
movpar_file
SPM-formatted motion parameters file
rmsd_file
Framewise displacement as measured by ``fsl_motion_outliers``.
skip_vols
number of non steady state volumes
t1w_mask
Mask of the skull-stripped template image
t1w_tpms
List of tissue probability maps in T1w space
t1_bold_xform
Affine matrix that maps the T1w space into alignment with
the native BOLD space
Outputs
-------
confounds_file
TSV of all aggregated confounds
rois_report
Reportlet visualizing white-matter/CSF mask used for aCompCor,
the ROI for tCompCor and the BOLD brain mask.
confounds_metadata
Confounds metadata dictionary.
"""
from niworkflows.engine.workflows import LiterateWorkflow as Workflow
from niworkflows.interfaces.confounds import ExpandModel, SpikeRegressors
from niworkflows.interfaces.fixes import FixHeaderApplyTransforms as ApplyTransforms
from niworkflows.interfaces.images import SignalExtraction
from niworkflows.interfaces.masks import ROIsPlot
from niworkflows.interfaces.nibabel import ApplyMask, Binarize
from niworkflows.interfaces.patches import (
RobustACompCor as ACompCor,
RobustTCompCor as TCompCor,
)
from niworkflows.interfaces.plotting import (
CompCorVariancePlot, ConfoundsCorrelationPlot
)
from niworkflows.interfaces.utils import (
AddTSVHeader, TSV2JSON, DictMerge
)
from ...interfaces.confounds import aCompCorMasks
gm_desc = (
"dilating a GM mask extracted from the FreeSurfer's *aseg* segmentation" if freesurfer
else "thresholding the corresponding partial volume map at 0.05"
)
workflow = Workflow(name=name)
workflow.__desc__ = f"""\
Several confounding time-series were calculated based on the
*preprocessed BOLD*: framewise displacement (FD), DVARS and
three region-wise global signals.
FD was computed using two formulations following Power (absolute sum of
relative motions, @power_fd_dvars) and Jenkinson (relative root mean square
displacement between affines, @mcflirt).
FD and DVARS are calculated for each functional run, both using their
implementations in *Nipype* [following the definitions by @power_fd_dvars].
The three global signals are extracted within the CSF, the WM, and
the whole-brain masks.
Additionally, a set of physiological regressors were extracted to
allow for component-based noise correction [*CompCor*, @compcor].
Principal components are estimated after high-pass filtering the
*preprocessed BOLD* time-series (using a discrete cosine filter with
128s cut-off) for the two *CompCor* variants: temporal (tCompCor)
and anatomical (aCompCor).
tCompCor components are then calculated from the top 2% variable
voxels within the brain mask.
For aCompCor, three probabilistic masks (CSF, WM and combined CSF+WM)
are generated in anatomical space.
The implementation differs from that of Behzadi et al. in that instead
of eroding the masks by 2 pixels on BOLD space, the aCompCor masks are
subtracted a mask of pixels that likely contain a volume fraction of GM.
This mask is obtained by {gm_desc}, and it ensures components are not extracted
from voxels containing a minimal fraction of GM.
Finally, these masks are resampled into BOLD space and binarized by
thresholding at 0.99 (as in the original implementation).
Components are also calculated separately within the WM and CSF masks.
For each CompCor decomposition, the *k* components with the largest singular
values are retained, such that the retained components' time series are
sufficient to explain 50 percent of variance across the nuisance mask (CSF,
WM, combined, or temporal). The remaining components are dropped from
consideration.
The head-motion estimates calculated in the correction step were also
placed within the corresponding confounds file.
The confound time series derived from head motion estimates and global
signals were expanded with the inclusion of temporal derivatives and
quadratic terms for each [@confounds_satterthwaite_2013].
Frames that exceeded a threshold of {regressors_fd_th} mm FD or
{regressors_dvars_th} standardised DVARS were annotated as motion outliers.
"""
inputnode = pe.Node(niu.IdentityInterface(
fields=['bold', 'bold_mask', 'movpar_file', 'rmsd_file',
'skip_vols', 't1w_mask', 't1w_tpms', 't1_bold_xform']),
name='inputnode')
outputnode = pe.Node(niu.IdentityInterface(
fields=['confounds_file', 'confounds_metadata', 'acompcor_masks', 'tcompcor_mask']),
name='outputnode')
# DVARS
dvars = pe.Node(nac.ComputeDVARS(save_nstd=True, save_std=True, remove_zerovariance=True),
name="dvars", mem_gb=mem_gb)
# Frame displacement
fdisp = pe.Node(nac.FramewiseDisplacement(parameter_source="SPM"),
name="fdisp", mem_gb=mem_gb)
# Generate aCompCor probseg maps
acc_masks = pe.Node(aCompCorMasks(is_aseg=freesurfer), name="acc_masks")
# Resample probseg maps in BOLD space via T1w-to-BOLD transform
acc_msk_tfm = pe.MapNode(ApplyTransforms(
interpolation='Gaussian', float=False), iterfield=["input_image"],
name='acc_msk_tfm', mem_gb=0.1)
acc_msk_brain = pe.MapNode(ApplyMask(), name="acc_msk_brain",
iterfield=["in_file"])
acc_msk_bin = pe.MapNode(Binarize(thresh_low=0.99), name='acc_msk_bin',
iterfield=["in_file"])
acompcor = pe.Node(
ACompCor(components_file='acompcor.tsv', header_prefix='a_comp_cor_', pre_filter='cosine',
save_pre_filter=True, save_metadata=True, mask_names=['CSF', 'WM', 'combined'],
merge_method='none', failure_mode='NaN'),
name="acompcor", mem_gb=mem_gb)
tcompcor = pe.Node(
TCompCor(components_file='tcompcor.tsv', header_prefix='t_comp_cor_', pre_filter='cosine',
save_pre_filter=True, save_metadata=True, percentile_threshold=.02,
failure_mode='NaN'),
name="tcompcor", mem_gb=mem_gb)
# Set number of components
if regressors_all_comps:
acompcor.inputs.num_components = 'all'
tcompcor.inputs.num_components = 'all'
else:
acompcor.inputs.variance_threshold = 0.5
tcompcor.inputs.variance_threshold = 0.5
# Set TR if present
if 'RepetitionTime' in metadata:
tcompcor.inputs.repetition_time = metadata['RepetitionTime']
acompcor.inputs.repetition_time = metadata['RepetitionTime']
# Global and segment regressors
signals_class_labels = [
"global_signal", "csf", "white_matter", "csf_wm", "tcompcor",
]
merge_rois = pe.Node(niu.Merge(3, ravel_inputs=True), name='merge_rois',
run_without_submitting=True)
signals = pe.Node(SignalExtraction(class_labels=signals_class_labels),
name="signals", mem_gb=mem_gb)
# Arrange confounds
add_dvars_header = pe.Node(
AddTSVHeader(columns=["dvars"]),
name="add_dvars_header", mem_gb=0.01, run_without_submitting=True)
add_std_dvars_header = pe.Node(
AddTSVHeader(columns=["std_dvars"]),
name="add_std_dvars_header", mem_gb=0.01, run_without_submitting=True)
add_motion_headers = pe.Node(
AddTSVHeader(columns=["trans_x", "trans_y", "trans_z", "rot_x", "rot_y", "rot_z"]),
name="add_motion_headers", mem_gb=0.01, run_without_submitting=True)
add_rmsd_header = pe.Node(
AddTSVHeader(columns=["rmsd"]),
name="add_rmsd_header", mem_gb=0.01, run_without_submitting=True)
concat = pe.Node(GatherConfounds(), name="concat", mem_gb=0.01, run_without_submitting=True)
# CompCor metadata
tcc_metadata_fmt = pe.Node(
TSV2JSON(index_column='component', drop_columns=['mask'], output=None,
additional_metadata={'Method': 'tCompCor'}, enforce_case=True),
name='tcc_metadata_fmt')
acc_metadata_fmt = pe.Node(
TSV2JSON(index_column='component', output=None,
additional_metadata={'Method': 'aCompCor'}, enforce_case=True),
name='acc_metadata_fmt')
mrg_conf_metadata = pe.Node(niu.Merge(3), name='merge_confound_metadata',
run_without_submitting=True)
mrg_conf_metadata.inputs.in3 = {label: {'Method': 'Mean'}
for label in signals_class_labels}
mrg_conf_metadata2 = pe.Node(DictMerge(), name='merge_confound_metadata2',
run_without_submitting=True)
# Expand model to include derivatives and quadratics
model_expand = pe.Node(ExpandModel(
model_formula='(dd1(rps + wm + csf + gsr))^^2 + others'),
name='model_expansion')
# Add spike regressors
spike_regress = pe.Node(SpikeRegressors(
fd_thresh=regressors_fd_th,
dvars_thresh=regressors_dvars_th),
name='spike_regressors')
# Generate reportlet (ROIs)
mrg_compcor = pe.Node(niu.Merge(2, ravel_inputs=True),
name='mrg_compcor', run_without_submitting=True)
rois_plot = pe.Node(ROIsPlot(colors=['b', 'magenta'], generate_report=True),
name='rois_plot', mem_gb=mem_gb)
ds_report_bold_rois = pe.Node(
DerivativesDataSink(desc='rois', datatype="figures", dismiss_entities=("echo",)),
name='ds_report_bold_rois', run_without_submitting=True,
mem_gb=DEFAULT_MEMORY_MIN_GB)
# Generate reportlet (CompCor)
mrg_cc_metadata = pe.Node(niu.Merge(2), name='merge_compcor_metadata',
run_without_submitting=True)
compcor_plot = pe.Node(
CompCorVariancePlot(variance_thresholds=(0.5, 0.7, 0.9),
metadata_sources=['tCompCor', 'aCompCor']),
name='compcor_plot')
ds_report_compcor = pe.Node(
DerivativesDataSink(desc='compcorvar', datatype="figures", dismiss_entities=("echo",)),
name='ds_report_compcor', run_without_submitting=True,
mem_gb=DEFAULT_MEMORY_MIN_GB)
# Generate reportlet (Confound correlation)
conf_corr_plot = pe.Node(
ConfoundsCorrelationPlot(reference_column='global_signal', max_dim=20),
name='conf_corr_plot')
ds_report_conf_corr = pe.Node(
DerivativesDataSink(desc='confoundcorr', datatype="figures", dismiss_entities=("echo",)),
name='ds_report_conf_corr', run_without_submitting=True,
mem_gb=DEFAULT_MEMORY_MIN_GB)
def _last(inlist):
return inlist[-1]
def _select_cols(table):
import pandas as pd
return [
col for col in pd.read_table(table, nrows=2).columns
if not col.startswith(("a_comp_cor_", "t_comp_cor_", "std_dvars"))
]
workflow.connect([
# connect inputnode to each non-anatomical confound node
(inputnode, dvars, [('bold', 'in_file'),
('bold_mask', 'in_mask')]),
(inputnode, fdisp, [('movpar_file', 'in_file')]),
# aCompCor
(inputnode, acompcor, [("bold", "realigned_file"),
("skip_vols", "ignore_initial_volumes")]),
(inputnode, acc_masks, [("t1w_tpms", "in_vfs"),
(("bold", _get_zooms), "bold_zooms")]),
(inputnode, acc_msk_tfm, [("t1_bold_xform", "transforms"),
("bold_mask", "reference_image")]),
(inputnode, acc_msk_brain, [("bold_mask", "in_mask")]),
(acc_masks, acc_msk_tfm, [("out_masks", "input_image")]),
(acc_msk_tfm, acc_msk_brain, [("output_image", "in_file")]),
(acc_msk_brain, acc_msk_bin, [("out_file", "in_file")]),
(acc_msk_bin, acompcor, [("out_file", "mask_files")]),
# tCompCor
(inputnode, tcompcor, [("bold", "realigned_file"),
("skip_vols", "ignore_initial_volumes"),
("bold_mask", "mask_files")]),
# Global signals extraction (constrained by anatomy)
(inputnode, signals, [('bold', 'in_file')]),
(inputnode, merge_rois, [('bold_mask', 'in1')]),
(acc_msk_bin, merge_rois, [('out_file', 'in2')]),
(tcompcor, merge_rois, [('high_variance_masks', 'in3')]),
(merge_rois, signals, [('out', 'label_files')]),
# Collate computed confounds together
(inputnode, add_motion_headers, [('movpar_file', 'in_file')]),
(inputnode, add_rmsd_header, [('rmsd_file', 'in_file')]),
(dvars, add_dvars_header, [('out_nstd', 'in_file')]),
(dvars, add_std_dvars_header, [('out_std', 'in_file')]),
(signals, concat, [('out_file', 'signals')]),
(fdisp, concat, [('out_file', 'fd')]),
(tcompcor, concat, [('components_file', 'tcompcor'),
('pre_filter_file', 'cos_basis')]),
(acompcor, concat, [('components_file', 'acompcor')]),
(add_motion_headers, concat, [('out_file', 'motion')]),
(add_rmsd_header, concat, [('out_file', 'rmsd')]),
(add_dvars_header, concat, [('out_file', 'dvars')]),
(add_std_dvars_header, concat, [('out_file', 'std_dvars')]),
# Confounds metadata
(tcompcor, tcc_metadata_fmt, [('metadata_file', 'in_file')]),
(acompcor, acc_metadata_fmt, [('metadata_file', 'in_file')]),
(tcc_metadata_fmt, mrg_conf_metadata, [('output', 'in1')]),
(acc_metadata_fmt, mrg_conf_metadata, [('output', 'in2')]),
(mrg_conf_metadata, mrg_conf_metadata2, [('out', 'in_dicts')]),
# Expand the model with derivatives, quadratics, and spikes
(concat, model_expand, [('confounds_file', 'confounds_file')]),
(model_expand, spike_regress, [('confounds_file', 'confounds_file')]),
# Set outputs
(spike_regress, outputnode, [('confounds_file', 'confounds_file')]),
(mrg_conf_metadata2, outputnode, [('out_dict', 'confounds_metadata')]),
(tcompcor, outputnode, [("high_variance_masks", "tcompcor_mask")]),
(acc_msk_bin, outputnode, [("out_file", "acompcor_masks")]),
(inputnode, rois_plot, [('bold', 'in_file'),
('bold_mask', 'in_mask')]),
(tcompcor, mrg_compcor, [('high_variance_masks', 'in1')]),
(acc_msk_bin, mrg_compcor, [(('out_file', _last), 'in2')]),
(mrg_compcor, rois_plot, [('out', 'in_rois')]),
(rois_plot, ds_report_bold_rois, [('out_report', 'in_file')]),
(tcompcor, mrg_cc_metadata, [('metadata_file', 'in1')]),
(acompcor, mrg_cc_metadata, [('metadata_file', 'in2')]),
(mrg_cc_metadata, compcor_plot, [('out', 'metadata_files')]),
(compcor_plot, ds_report_compcor, [('out_file', 'in_file')]),
(concat, conf_corr_plot, [('confounds_file', 'confounds_file'),
(('confounds_file', _select_cols), 'columns')]),
(conf_corr_plot, ds_report_conf_corr, [('out_file', 'in_file')]),
])
return workflow
def init_carpetplot_wf(mem_gb, metadata, cifti_output, name="bold_carpet_wf"):
"""
Build a workflow to generate *carpet* plots.
Resamples the MNI parcellation (ad-hoc parcellation derived from the
Harvard-Oxford template and others).
Parameters
----------
mem_gb : :obj:`float`
Size of BOLD file in GB - please note that this size
should be calculated after resamplings that may extend
the FoV
metadata : :obj:`dict`
BIDS metadata for BOLD file
name : :obj:`str`
Name of workflow (default: ``bold_carpet_wf``)
Inputs
------
bold
BOLD image, after the prescribed corrections (STC, HMC and SDC)
when available.
bold_mask
BOLD series mask
confounds_file
TSV of all aggregated confounds
t1_bold_xform
Affine matrix that maps the T1w space into alignment with
the native BOLD space
std2anat_xfm
ANTs-compatible affine-and-warp transform file
cifti_bold
BOLD image in CIFTI format, to be used in place of volumetric BOLD
Outputs
-------
out_carpetplot
Path of the generated SVG file
"""
from niworkflows.engine.workflows import LiterateWorkflow as Workflow
from niworkflows.interfaces.fixes import FixHeaderApplyTransforms as ApplyTransforms
inputnode = pe.Node(niu.IdentityInterface(
fields=['bold', 'bold_mask', 'confounds_file',
't1_bold_xform', 'std2anat_xfm', 'cifti_bold']),
name='inputnode')
outputnode = pe.Node(niu.IdentityInterface(
fields=['out_carpetplot']), name='outputnode')
# List transforms
mrg_xfms = pe.Node(niu.Merge(2), name='mrg_xfms')
# Warp segmentation into EPI space
resample_parc = pe.Node(ApplyTransforms(
dimension=3,
input_image=str(get_template(
'MNI152NLin2009cAsym', resolution=1, desc='carpet',
suffix='dseg', extension=['.nii', '.nii.gz'])),
interpolation='MultiLabel'),
name='resample_parc')
# Carpetplot and confounds plot
conf_plot = pe.Node(FMRISummary(
tr=metadata['RepetitionTime'],
confounds_list=[
('global_signal', None, 'GS'),
('csf', None, 'GSCSF'),
('white_matter', None, 'GSWM'),
('std_dvars', None, 'DVARS'),
('framewise_displacement', 'mm', 'FD')]),
name='conf_plot', mem_gb=mem_gb)
ds_report_bold_conf = pe.Node(
DerivativesDataSink(desc='carpetplot', datatype="figures", extension="svg",
dismiss_entities=("echo",)),
name='ds_report_bold_conf', run_without_submitting=True,
mem_gb=DEFAULT_MEMORY_MIN_GB)
workflow = Workflow(name=name)
# no need for segmentations if using CIFTI
if cifti_output:
workflow.connect(inputnode, 'cifti_bold', conf_plot, 'in_func')
else:
workflow.connect([
(inputnode, mrg_xfms, [('t1_bold_xform', 'in1'),
('std2anat_xfm', 'in2')]),
(inputnode, resample_parc, [('bold_mask', 'reference_image')]),
(mrg_xfms, resample_parc, [('out', 'transforms')]),
# Carpetplot
(inputnode, conf_plot, [
('bold', 'in_func'),
('bold_mask', 'in_mask')]),
(resample_parc, conf_plot, [('output_image', 'in_segm')])
])
workflow.connect([
(inputnode, conf_plot, [('confounds_file', 'confounds_file')]),
(conf_plot, ds_report_bold_conf, [('out_file', 'in_file')]),
(conf_plot, outputnode, [('out_file', 'out_carpetplot')]),
])
return workflow
def init_ica_aroma_wf(
mem_gb,
metadata,
omp_nthreads,
aroma_melodic_dim=-200,
err_on_aroma_warn=False,
name='ica_aroma_wf',
susan_fwhm=6.0,
):
"""
Build a workflow that runs `ICA-AROMA`_.
This workflow wraps `ICA-AROMA`_ to identify and remove motion-related
independent components from a BOLD time series.
The following steps are performed:
#. Remove non-steady state volumes from the bold series.
#. Smooth data using FSL `susan`, with a kernel width FWHM=6.0mm.
#. Run FSL `melodic` outside of ICA-AROMA to generate the report
#. Run ICA-AROMA
#. Aggregate identified motion components (aggressive) to TSV
#. Return ``classified_motion_ICs`` and ``melodic_mix`` for user to complete
non-aggressive denoising in T1w space
#. Calculate ICA-AROMA-identified noise components
(columns named ``AROMAAggrCompXX``)
Additionally, non-aggressive denoising is performed on the BOLD series
resampled into MNI space.
There is a current discussion on whether other confounds should be extracted
before or after denoising `here
<http://nbviewer.jupyter.org/github/nipreps/fmriprep-notebooks/blob/922e436429b879271fa13e76767a6e73443e74d9/issue-817_aroma_confounds.ipynb>`__.
.. _ICA-AROMA: https://github.com/maartenmennes/ICA-AROMA
Workflow Graph
.. workflow::
:graph2use: orig
:simple_form: yes
from fmriprep.workflows.bold.confounds import init_ica_aroma_wf
wf = init_ica_aroma_wf(
mem_gb=3,
metadata={'RepetitionTime': 1.0},
omp_nthreads=1)
Parameters
----------
metadata : :obj:`dict`
BIDS metadata for BOLD file
mem_gb : :obj:`float`
Size of BOLD file in GB
omp_nthreads : :obj:`int`
Maximum number of threads an individual process may use
name : :obj:`str`
Name of workflow (default: ``bold_tpl_trans_wf``)
susan_fwhm : :obj:`float`
Kernel width (FWHM in mm) for the smoothing step with
FSL ``susan`` (default: 6.0mm)
err_on_aroma_warn : :obj:`bool`
Do not fail on ICA-AROMA errors
aroma_melodic_dim : :obj:`int`
Set the dimensionality of the MELODIC ICA decomposition.
Negative numbers set a maximum on automatic dimensionality estimation.
Positive numbers set an exact number of components to extract.
(default: -200, i.e., estimate <=200 components)
Inputs
------
itk_bold_to_t1
Affine transform from ``ref_bold_brain`` to T1 space (ITK format)
anat2std_xfm
ANTs-compatible affine-and-warp transform file
name_source
BOLD series NIfTI file
Used to recover original information lost during processing
skip_vols
number of non steady state volumes
bold_split
Individual 3D BOLD volumes, not motion corrected
bold_mask
BOLD series mask in template space
hmc_xforms
List of affine transforms aligning each volume to ``ref_image`` in ITK format
movpar_file
SPM-formatted motion parameters file
Outputs
-------
aroma_confounds
TSV of confounds identified as noise by ICA-AROMA
aroma_noise_ics
CSV of noise components identified by ICA-AROMA
melodic_mix
FSL MELODIC mixing matrix
nonaggr_denoised_file
BOLD series with non-aggressive ICA-AROMA denoising applied
"""
from niworkflows.engine.workflows import LiterateWorkflow as Workflow
from niworkflows.interfaces.segmentation import ICA_AROMARPT
from niworkflows.interfaces.utility import KeySelect
from niworkflows.interfaces.utils import TSV2JSON
workflow = Workflow(name=name)
workflow.__postdesc__ = """\
Automatic removal of motion artifacts using independent component analysis
[ICA-AROMA, @aroma] was performed on the *preprocessed BOLD on MNI space*
time-series after removal of non-steady state volumes and spatial smoothing
with an isotropic, Gaussian kernel of 6mm FWHM (full-width half-maximum).
Corresponding "non-aggresively" denoised runs were produced after such
smoothing.
Additionally, the "aggressive" noise-regressors were collected and placed
in the corresponding confounds file.
"""
inputnode = pe.Node(niu.IdentityInterface(
fields=[
'bold_std',
'bold_mask_std',
'movpar_file',
'name_source',
'skip_vols',
'spatial_reference',
]), name='inputnode')
outputnode = pe.Node(niu.IdentityInterface(
fields=['aroma_confounds', 'aroma_noise_ics', 'melodic_mix',
'nonaggr_denoised_file', 'aroma_metadata']), name='outputnode')
# extract out to BOLD base
select_std = pe.Node(KeySelect(fields=['bold_mask_std', 'bold_std']),
name='select_std', run_without_submitting=True)
select_std.inputs.key = 'MNI152NLin6Asym_res-2'
rm_non_steady_state = pe.Node(niu.Function(function=_remove_volumes,
output_names=['bold_cut']),
name='rm_nonsteady')
calc_median_val = pe.Node(fsl.ImageStats(op_string='-k %s -p 50'), name='calc_median_val')
calc_bold_mean = pe.Node(fsl.MeanImage(), name='calc_bold_mean')
def _getusans_func(image, thresh):
return [tuple([image, thresh])]
getusans = pe.Node(niu.Function(function=_getusans_func, output_names=['usans']),
name='getusans', mem_gb=0.01)
smooth = pe.Node(fsl.SUSAN(fwhm=susan_fwhm), name='smooth')
# melodic node
melodic = pe.Node(fsl.MELODIC(
no_bet=True, tr_sec=float(metadata['RepetitionTime']), mm_thresh=0.5, out_stats=True,
dim=aroma_melodic_dim), name="melodic")
# ica_aroma node
ica_aroma = pe.Node(ICA_AROMARPT(
denoise_type='nonaggr', generate_report=True, TR=metadata['RepetitionTime'],
args='-np'), name='ica_aroma')
add_non_steady_state = pe.Node(niu.Function(function=_add_volumes,
output_names=['bold_add']),
name='add_nonsteady')
# extract the confound ICs from the results
ica_aroma_confound_extraction = pe.Node(ICAConfounds(err_on_aroma_warn=err_on_aroma_warn),
name='ica_aroma_confound_extraction')
ica_aroma_metadata_fmt = pe.Node(
TSV2JSON(index_column='IC', output=None, enforce_case=True,
additional_metadata={'Method': {
'Name': 'ICA-AROMA',
'Version': getenv('AROMA_VERSION', 'n/a')}}),
name='ica_aroma_metadata_fmt')
ds_report_ica_aroma = pe.Node(
DerivativesDataSink(desc='aroma', datatype="figures", dismiss_entities=("echo",)),
name='ds_report_ica_aroma', run_without_submitting=True,
mem_gb=DEFAULT_MEMORY_MIN_GB)
def _getbtthresh(medianval):
return 0.75 * medianval
# connect the nodes
workflow.connect([
(inputnode, select_std, [('spatial_reference', 'keys'),
('bold_std', 'bold_std'),
('bold_mask_std', 'bold_mask_std')]),
(inputnode, ica_aroma, [('movpar_file', 'motion_parameters')]),
(inputnode, rm_non_steady_state, [
('skip_vols', 'skip_vols')]),
(select_std, rm_non_steady_state, [
('bold_std', 'bold_file')]),
(select_std, calc_median_val, [
('bold_mask_std', 'mask_file')]),
(rm_non_steady_state, calc_median_val, [
('bold_cut', 'in_file')]),
(rm_non_steady_state, calc_bold_mean, [
('bold_cut', 'in_file')]),
(calc_bold_mean, getusans, [('out_file', 'image')]),
(calc_median_val, getusans, [('out_stat', 'thresh')]),
# Connect input nodes to complete smoothing
(rm_non_steady_state, smooth, [
('bold_cut', 'in_file')]),
(getusans, smooth, [('usans', 'usans')]),
(calc_median_val, smooth, [(('out_stat', _getbtthresh), 'brightness_threshold')]),
# connect smooth to melodic
(smooth, melodic, [('smoothed_file', 'in_files')]),
(select_std, melodic, [
('bold_mask_std', 'mask')]),
# connect nodes to ICA-AROMA
(smooth, ica_aroma, [('smoothed_file', 'in_file')]),
(select_std, ica_aroma, [
('bold_mask_std', 'report_mask'),
('bold_mask_std', 'mask')]),
(melodic, ica_aroma, [('out_dir', 'melodic_dir')]),
# generate tsvs from ICA-AROMA
(ica_aroma, ica_aroma_confound_extraction, [('out_dir', 'in_directory')]),
(inputnode, ica_aroma_confound_extraction, [
('skip_vols', 'skip_vols')]),
(ica_aroma_confound_extraction, ica_aroma_metadata_fmt, [
('aroma_metadata', 'in_file')]),
# output for processing and reporting
(ica_aroma_confound_extraction, outputnode, [('aroma_confounds', 'aroma_confounds'),
('aroma_noise_ics', 'aroma_noise_ics'),
('melodic_mix', 'melodic_mix')]),
(ica_aroma_metadata_fmt, outputnode, [('output', 'aroma_metadata')]),
(ica_aroma, add_non_steady_state, [
('nonaggr_denoised_file', 'bold_cut_file')]),
(select_std, add_non_steady_state, [
('bold_std', 'bold_file')]),
(inputnode, add_non_steady_state, [
('skip_vols', 'skip_vols')]),
(add_non_steady_state, outputnode, [('bold_add', 'nonaggr_denoised_file')]),
(ica_aroma, ds_report_ica_aroma, [('out_report', 'in_file')]),
])
return workflow
def _remove_volumes(bold_file, skip_vols):
"""Remove skip_vols from bold_file."""
import nibabel as nb
from nipype.utils.filemanip import fname_presuffix
if skip_vols == 0:
return bold_file
out = fname_presuffix(bold_file, suffix='_cut')
bold_img = nb.load(bold_file)
bold_img.__class__(bold_img.dataobj[..., skip_vols:],
bold_img.affine, bold_img.header).to_filename(out)
return out
def _add_volumes(bold_file, bold_cut_file, skip_vols):
"""Prepend skip_vols from bold_file onto bold_cut_file."""
import nibabel as nb
import numpy as np
from nipype.utils.filemanip import fname_presuffix
if skip_vols == 0:
return bold_cut_file
bold_img = nb.load(bold_file)
bold_cut_img = nb.load(bold_cut_file)
bold_data = np.concatenate((bold_img.dataobj[..., :skip_vols],
bold_cut_img.dataobj), axis=3)
out = fname_presuffix(bold_cut_file, suffix='_addnonsteady')
bold_img.__class__(bold_data, bold_img.affine, bold_img.header).to_filename(out)
return out
def _get_zooms(in_file):
import nibabel as nb
return tuple(nb.load(in_file).header.get_zooms()[:3])