-
-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathfunc_preproc.py
More file actions
1920 lines (1559 loc) · 66.1 KB
/
Copy pathfunc_preproc.py
File metadata and controls
1920 lines (1559 loc) · 66.1 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-2025 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/>.
"""Functional preprocessing."""
# pylint: disable=ungrouped-imports,wrong-import-order,wrong-import-position
from nipype.interfaces import afni, ants, fsl, utility as util
from nipype.interfaces.afni import preprocess, utils as afni_utils
from CPAC.func_preproc.utils import nullify
from CPAC.pipeline import nipype_pipeline_engine as pe
from CPAC.pipeline.nodeblock import nodeblock
from CPAC.utils.interfaces import Function
from CPAC.utils.interfaces.ants import (
AI, # niworkflows
PrintHeader,
SetDirectionByMatrix,
)
from CPAC.utils.utils import add_afni_prefix
def collect_arguments(*args):
"""Collect arguments."""
command_args = []
if args[0]:
command_args += [args[1]]
command_args += args[2:]
return " ".join(command_args)
def anat_refined_mask(init_bold_mask=True, wf_name="init_bold_mask"):
"""Generate an anatomically refined mask."""
wf = pe.Workflow(name=wf_name)
input_node = pe.Node(
util.IdentityInterface(
fields=[
"func",
"anatomical_brain_mask",
"anat_brain",
"init_func_brain_mask",
]
),
name="inputspec",
)
output_node = pe.Node(
util.IdentityInterface(fields=["func_brain_mask"]), name="outputspec"
)
# 1 Take single volume of func
func_single_volume = pe.Node(interface=afni.Calc(), name="func_single_volume")
# TODO add an option to select volume
func_single_volume.inputs.set(expr="a", single_idx=1, outputtype="NIFTI_GZ")
wf.connect(input_node, "func", func_single_volume, "in_file_a")
# 2 get temporary func brain
func_tmp_brain = pe.Node(interface=afni_utils.Calc(), name="func_tmp_brain")
func_tmp_brain.inputs.expr = "a*b"
func_tmp_brain.inputs.outputtype = "NIFTI_GZ"
wf.connect(func_single_volume, "out_file", func_tmp_brain, "in_file_a")
# 2.1 get a tmp func brain mask
if init_bold_mask:
# 2.1.1 N4BiasFieldCorrection single volume of raw_func
func_single_volume_n4_corrected = pe.Node(
interface=ants.N4BiasFieldCorrection(
dimension=3, copy_header=True, bspline_fitting_distance=200
),
shrink_factor=2,
name="func_single_volume_n4_corrected",
)
func_single_volume_n4_corrected.inputs.args = "-r True"
wf.connect(
func_single_volume,
"out_file",
func_single_volume_n4_corrected,
"input_image",
)
# 2.1.2 bet n4 corrected image - generate tmp func brain mask
func_tmp_brain_mask = pe.Node(
interface=fsl.BET(), name="func_tmp_brain_mask_pre"
)
func_tmp_brain_mask.inputs.mask = True
wf.connect(
func_single_volume_n4_corrected,
"output_image",
func_tmp_brain_mask,
"in_file",
)
# 2.1.3 dilate func tmp brain mask
func_tmp_brain_mask_dil = pe.Node(
interface=fsl.ImageMaths(), name="func_tmp_brain_mask_dil"
)
func_tmp_brain_mask_dil.inputs.op_string = "-dilM"
wf.connect(func_tmp_brain_mask, "mask_file", func_tmp_brain_mask_dil, "in_file")
wf.connect(func_tmp_brain_mask_dil, "out_file", func_tmp_brain, "in_file_b")
else:
# 2.1.1 connect dilated init func brain mask
wf.connect(input_node, "init_func_brain_mask", func_tmp_brain, "in_file_b")
# 3. get transformation of anat to func
# 3.1 Register func tmp brain to anat brain to get func2anat matrix
linear_reg_func_to_anat = pe.Node(
interface=fsl.FLIRT(), name="func_to_anat_linear_reg"
)
linear_reg_func_to_anat.inputs.cost = "mutualinfo"
linear_reg_func_to_anat.inputs.dof = 6
wf.connect(func_tmp_brain, "out_file", linear_reg_func_to_anat, "in_file")
wf.connect(input_node, "anat_brain", linear_reg_func_to_anat, "reference")
# 3.2 Inverse func to anat affine
inv_func_to_anat_affine = pe.Node(
interface=fsl.ConvertXFM(), name="inv_func2anat_affine"
)
inv_func_to_anat_affine.inputs.invert_xfm = True
wf.connect(
linear_reg_func_to_anat, "out_matrix_file", inv_func_to_anat_affine, "in_file"
)
# 4. anat mask to func space
# Transform anatomical mask to functional space to get BOLD mask
reg_anat_mask_to_func = pe.Node(interface=fsl.FLIRT(), name="reg_anat_mask_to_func")
reg_anat_mask_to_func.inputs.apply_xfm = True
reg_anat_mask_to_func.inputs.cost = "mutualinfo"
reg_anat_mask_to_func.inputs.dof = 6
reg_anat_mask_to_func.inputs.interp = "nearestneighbour"
wf.connect(input_node, "anatomical_brain_mask", reg_anat_mask_to_func, "in_file")
wf.connect(func_tmp_brain, "out_file", reg_anat_mask_to_func, "reference")
wf.connect(
inv_func_to_anat_affine, "out_file", reg_anat_mask_to_func, "in_matrix_file"
)
# 5. get final func mask: refine func tmp mask with anat_mask_in_func mask
func_mask = pe.Node(interface=fsl.MultiImageMaths(), name="func_mask")
func_mask.inputs.op_string = "-mul %s"
wf.connect(reg_anat_mask_to_func, "out_file", func_mask, "operand_files")
if init_bold_mask:
wf.connect(func_tmp_brain_mask_dil, "out_file", func_mask, "in_file")
else:
wf.connect(input_node, "init_func_brain_mask", func_mask, "in_file")
wf.connect(func_mask, "out_file", output_node, "func_brain_mask")
return wf
def anat_based_mask(wf_name="bold_mask"):
"""Generate a functional mask from anatomical data.
Reference `DCAN lab BOLD mask <https://github.com/DCAN-Labs/DCAN-HCP/blob/a8d495a/fMRIVolume/scripts/DistortionCorrectionAndEPIToT1wReg_FLIRTBBRAndFreeSurferBBRbased.sh>`_.
"""
wf = pe.Workflow(name=wf_name)
input_node = pe.Node(
util.IdentityInterface(fields=["func", "anat_brain", "anat_head"]),
name="inputspec",
)
output_node = pe.Node(
util.IdentityInterface(fields=["func_brain_mask"]), name="outputspec"
)
# 0. Take single volume of func
func_single_volume = pe.Node(interface=afni.Calc(), name="func_single_volume")
func_single_volume.inputs.set(expr="a", single_idx=1, outputtype="NIFTI_GZ")
wf.connect(input_node, "func", func_single_volume, "in_file_a")
# 1. Register func head to anat head to get func2anat matrix
linear_reg_func_to_anat = pe.Node(
interface=fsl.FLIRT(), name="func_to_anat_linear_reg"
)
linear_reg_func_to_anat.inputs.dof = 6
linear_reg_func_to_anat.inputs.interp = "spline"
linear_reg_func_to_anat.inputs.searchr_x = [30, 30]
linear_reg_func_to_anat.inputs.searchr_y = [30, 30]
linear_reg_func_to_anat.inputs.searchr_z = [30, 30]
wf.connect(func_single_volume, "out_file", linear_reg_func_to_anat, "in_file")
wf.connect(input_node, "anat_head", linear_reg_func_to_anat, "reference")
# 2. Inverse func to anat affine, to get anat-to-func transform
inv_func_to_anat_affine = pe.Node(
interface=fsl.ConvertXFM(), name="inv_func2anat_affine"
)
inv_func_to_anat_affine.inputs.invert_xfm = True
wf.connect(
linear_reg_func_to_anat, "out_matrix_file", inv_func_to_anat_affine, "in_file"
)
# 3. get BOLD mask
# 3.1 Apply anat-to-func transform to transfer anatomical brain to functional space
reg_anat_brain_to_func = pe.Node(
interface=fsl.ApplyWarp(), name="reg_anat_brain_to_func"
)
reg_anat_brain_to_func.inputs.interp = "nn"
reg_anat_brain_to_func.inputs.relwarp = True
wf.connect(input_node, "anat_brain", reg_anat_brain_to_func, "in_file")
wf.connect(input_node, "func", reg_anat_brain_to_func, "ref_file")
wf.connect(inv_func_to_anat_affine, "out_file", reg_anat_brain_to_func, "premat")
# 3.2 Binarize transfered image and fill holes to get BOLD mask.
# Binarize
func_mask_bin = pe.Node(interface=fsl.ImageMaths(), name="func_mask")
func_mask_bin.inputs.op_string = "-bin"
wf.connect(reg_anat_brain_to_func, "out_file", func_mask_bin, "in_file")
wf.connect(func_mask_bin, "out_file", output_node, "func_brain_mask")
return wf
def create_scale_func_wf(scaling_factor, wf_name="scale_func"):
"""Workflow to scale func data.
Workflow Inputs::
inputspec.func : func file or a list of func/rest nifti file
User input functional(T2*) Image
Workflow Outputs::
outputspec.scaled_func : str (nifti file)
Path to Output image with scaled data
Order of commands:
- Scale the size of the dataset voxels by the factor 'fac'. For details see `3dcalc <https://afni.nimh.nih.gov/pub/dist/doc/program_help/3drefit.html>`_::
3drefit -xyzscale fac rest.nii.gz
Parameters
----------
scaling_factor : float
Scale the size of the dataset voxels by the factor.
wf_name : str
name of the workflow
"""
# allocate a workflow object
preproc = pe.Workflow(name=wf_name)
# configure the workflow's input spec
inputNode = pe.Node(util.IdentityInterface(fields=["func"]), name="inputspec")
# configure the workflow's output spec
outputNode = pe.Node(
util.IdentityInterface(fields=["scaled_func"]), name="outputspec"
)
# allocate a node to edit the functional file
func_scale = pe.Node(interface=afni_utils.Refit(), name="func_scale")
func_scale.inputs.xyzscale = scaling_factor
# wire in the func_get_idx node
preproc.connect(inputNode, "func", func_scale, "in_file")
# wire the output
preproc.connect(func_scale, "out_file", outputNode, "scaled_func")
return preproc
def create_wf_edit_func(wf_name="edit_func"):
"""Workflow to edit the scan to the proscribed TRs.
Workflow Inputs::
inputspec.func : func file or a list of func/rest nifti file
User input functional(T2*) Image
inputspec.start_idx : str
Starting volume/slice of the functional image (optional)
inputspec.stop_idx : str
Last volume/slice of the functional image (optional)
Workflow Outputs::
outputspec.edited_func : str (nifti file)
Path to Output image with the initial few slices dropped
Order of commands:
- Get the start and the end volume index of the functional run. If not defined by the user, return the first and last volume.
get_idx(in_files, stop_idx, start_idx)
- Dropping the initial TRs. For details see `3dcalc <http://afni.nimh.nih.gov/pub/dist/doc/program_help/3dcalc.html>`_::
3dcalc -a rest.nii.gz[4..299]
-expr 'a'
-prefix rest_3dc.nii.gz
"""
# allocate a workflow object
preproc = pe.Workflow(name=wf_name)
# configure the workflow's input spec
inputNode = pe.Node(
util.IdentityInterface(fields=["func", "start_idx", "stop_idx"]),
name="inputspec",
)
# configure the workflow's output spec
outputNode = pe.Node(
util.IdentityInterface(fields=["edited_func"]), name="outputspec"
)
# allocate a node to check that the requested edits are
# reasonable given the data
func_get_idx = pe.Node(
Function(
input_names=["in_files", "stop_idx", "start_idx"],
output_names=["stopidx", "startidx"],
function=get_idx,
),
name="func_get_idx",
)
# wire in the func_get_idx node
preproc.connect(inputNode, "func", func_get_idx, "in_files")
preproc.connect(inputNode, "start_idx", func_get_idx, "start_idx")
preproc.connect(inputNode, "stop_idx", func_get_idx, "stop_idx")
# allocate a node to edit the functional file
func_drop_trs = pe.Node(
interface=afni_utils.Calc(),
name="func_drop_trs",
mem_gb=0.37,
mem_x=(739971956005215 / 151115727451828646838272, "in_file_a"),
)
func_drop_trs.inputs.expr = "a"
func_drop_trs.inputs.outputtype = "NIFTI_GZ"
# wire in the inputs
preproc.connect(inputNode, "func", func_drop_trs, "in_file_a")
preproc.connect(func_get_idx, "startidx", func_drop_trs, "start_idx")
preproc.connect(func_get_idx, "stopidx", func_drop_trs, "stop_idx")
# wire the output
preproc.connect(func_drop_trs, "out_file", outputNode, "edited_func")
return preproc
def slice_timing_wf(name="slice_timing", tpattern=None, tzero=None):
"""Calculate corrected slice-timing."""
# allocate a workflow object
wf = pe.Workflow(name=name)
# configure the workflow's input spec
inputNode = pe.Node(
util.IdentityInterface(fields=["func_ts", "tr", "tpattern"]), name="inputspec"
)
# configure the workflow's output spec
outputNode = pe.Node(
util.IdentityInterface(fields=["slice_time_corrected"]), name="outputspec"
)
# create TShift AFNI node
func_slice_timing_correction = pe.Node(
interface=preprocess.TShift(),
name="slice_timing",
mem_gb=0.45,
mem_x=(5247073869855161 / 604462909807314587353088, "in_file"),
)
func_slice_timing_correction.inputs.outputtype = "NIFTI_GZ"
if tzero is not None:
func_slice_timing_correction.inputs.tzero = tzero
wf.connect(
[
(
inputNode,
func_slice_timing_correction,
[
("func_ts", "in_file"),
# (
# # add the @ prefix to the tpattern file going into
# # AFNI 3dTshift - needed this so the tpattern file
# # output from get_scan_params would be tied downstream
# # via a connection (to avoid poofing)
# ('tpattern', nullify, add_afni_prefix),
# 'tpattern'
# ),
(("tr", nullify), "tr"),
],
),
]
)
if tpattern is not None:
func_slice_timing_correction.inputs.tpattern = tpattern
else:
wf.connect(
inputNode,
("tpattern", nullify, add_afni_prefix),
func_slice_timing_correction,
"tpattern",
)
wf.connect(
func_slice_timing_correction, "out_file", outputNode, "slice_time_corrected"
)
return wf
def get_idx(in_files, stop_idx=None, start_idx=None):
"""Get the first and the last slice for the functional run.
Verify the user specified first and last slice. If the values are not valid,
calculate and return the very first and the last slice.
Parameters
----------
in_file : str (nifti file)
Path to input functional run
stop_idx : int
Last volume to be considered, specified by user
in the configuration file
stop_idx : int
First volume to be considered, specified by user
in the configuration file
Returns
-------
stop_idx : int
Value of first slice to consider for the functional run
start_idx : int
Value of last slice to consider for the functional run
"""
# Import packages
from nibabel import load
# Init variables
img = load(in_files)
hdr = img.header
shape = hdr.get_data_shape()
# Check to make sure the input file is 4-dimensional
if len(shape) != 4: # noqa: PLR2004
raise TypeError("Input nifti file: %s is not a 4D file" % in_files)
# Grab the number of volumes
nvols = int(hdr.get_data_shape()[3])
if (start_idx is None) or (int(start_idx) < 0) or (int(start_idx) > (nvols - 1)):
startidx = 0
else:
startidx = int(start_idx)
if (stop_idx in [None, "End"]) or (int(stop_idx) > (nvols - 1)):
stopidx = nvols - 1
else:
stopidx = int(stop_idx)
return stopidx, startidx
def fsl_afni_subworkflow(cfg, pipe_num, opt=None):
wf = pe.Workflow(name=f"fsl_afni_subworkflow_{pipe_num}")
inputNode = pe.Node(
util.IdentityInterface(
fields=[
"FSL-AFNI-bold-ref",
"FSL-AFNI-brain-mask",
"FSL-AFNI-brain-probseg",
"motion-basefile",
]
),
name="inputspec",
)
outputNode = pe.Node(
util.IdentityInterface(
fields=["space-bold_desc-brain_mask", "desc-unifized_bold"]
),
name="outputspec",
)
# Initialize transforms with antsAI
init_aff = pe.Node(
AI(
metric=("Mattes", 32, "Regular", 0.2),
transform=("Affine", 0.1),
search_factor=(20, 0.12),
principal_axes=False,
convergence=(10, 1e-6, 10),
verbose=True,
),
name=f"init_aff_{pipe_num}",
n_procs=cfg.pipeline_setup["system_config"]["num_OMP_threads"],
)
init_aff.inputs.search_grid = (40, (0, 40, 40))
# Set up spatial normalization
norm = pe.Node(
ants.Registration(
winsorize_upper_quantile=0.98,
winsorize_lower_quantile=0.05,
float=True,
metric=["Mattes"],
metric_weight=[1],
radius_or_number_of_bins=[64],
transforms=["Affine"],
transform_parameters=[[0.1]],
number_of_iterations=[[200]],
convergence_window_size=[10],
convergence_threshold=[1.0e-9],
sampling_strategy=["Random", "Random"],
smoothing_sigmas=[[2]],
sigma_units=["mm", "mm", "mm"],
shrink_factors=[[2]],
sampling_percentage=[0.2],
use_histogram_matching=[True],
),
name=f"norm_{pipe_num}",
n_procs=cfg.pipeline_setup["system_config"]["num_OMP_threads"],
)
map_brainmask = pe.Node(
ants.ApplyTransforms(
interpolation="BSpline",
float=True,
),
name=f"map_brainmask_{pipe_num}",
)
binarize_mask = pe.Node(
interface=fsl.maths.MathsCommand(), name=f"binarize_mask_{pipe_num}"
)
binarize_mask.inputs.args = "-thr 0.85 -bin"
# Dilate pre_mask
pre_dilate = pe.Node(
fsl.DilateImage(
operation="max",
kernel_shape="sphere",
kernel_size=3.0,
internal_datatype="char",
),
name=f"pre_mask_dilate_{pipe_num}",
)
# Fix precision errors
# https://github.com/ANTsX/ANTs/wiki/Inputs-do-not-occupy-the-same-physical-space#fixing-precision-errors
print_header = pe.Node(
PrintHeader(what_information=4), name=f"print_header_{pipe_num}"
)
set_direction = pe.Node(SetDirectionByMatrix(), name=f"set_direction_{pipe_num}")
# Run N4 normally, force num_threads=1 for stability (images are
# small, no need for >1)
n4_correct = pe.Node(
ants.N4BiasFieldCorrection(
dimension=3, copy_header=True, bspline_fitting_distance=200
),
shrink_factor=2,
rescale_intensities=True,
name=f"n4_correct_{pipe_num}",
n_procs=1,
)
# Create a generous BET mask out of the bias-corrected EPI
skullstrip_first_pass = pe.Node(
fsl.BET(frac=0.2, mask=True, functional=False),
name=f"skullstrip_first_pass_{pipe_num}",
)
bet_dilate = pe.Node(
fsl.DilateImage(
operation="max",
kernel_shape="sphere",
kernel_size=6.0,
internal_datatype="char",
),
name=f"skullstrip_first_dilate_{pipe_num}",
)
bet_mask = pe.Node(fsl.ApplyMask(), name=f"skullstrip_first_mask_{pipe_num}")
# Use AFNI's unifize for T2 constrast
unifize = pe.Node(
afni_utils.Unifize(
t2=True,
outputtype="NIFTI_GZ",
args="-clfrac 0.2 -rbt 18.3 65.0 90.0",
out_file="uni.nii.gz",
),
name=f"unifize_{pipe_num}",
)
# Run ANFI's 3dAutomask to extract a refined brain mask
skullstrip_second_pass = pe.Node(
preprocess.Automask(dilate=1, outputtype="NIFTI_GZ"),
name=f"skullstrip_second_pass_{pipe_num}",
)
# Take intersection of both masks
combine_masks = pe.Node(
fsl.BinaryMaths(operation="mul"), name=f"combine_masks_{pipe_num}"
)
# Compute masked brain
apply_mask = pe.Node(fsl.ApplyMask(), name=f"extract_ref_brain_bold_{pipe_num}")
wf.connect(
[
(inputNode, init_aff, [("FSL-AFNI-bold-ref", "fixed_image")]),
(inputNode, init_aff, [("FSL-AFNI-brain-mask", "fixed_image_mask")]),
(inputNode, init_aff, [("motion-basefile", "moving_image")]),
(init_aff, norm, [("output_transform", "initial_moving_transform")]),
(inputNode, norm, [("FSL-AFNI-bold-ref", "fixed_image")]),
(inputNode, norm, [("motion-basefile", "moving_image")]),
# Use the higher resolution and probseg for numerical stability in rounding
(inputNode, map_brainmask, [("FSL-AFNI-brain-probseg", "input_image")]),
(inputNode, map_brainmask, [("motion-basefile", "reference_image")]),
(
norm,
map_brainmask,
[
("reverse_invert_flags", "invert_transform_flags"),
("reverse_transforms", "transforms"),
],
),
(map_brainmask, binarize_mask, [("output_image", "in_file")]),
(binarize_mask, pre_dilate, [("out_file", "in_file")]),
(pre_dilate, print_header, [("out_file", "image")]),
(print_header, set_direction, [("header", "direction")]),
(
inputNode,
set_direction,
[("motion-basefile", "infile"), ("motion-basefile", "outfile")],
),
(set_direction, n4_correct, [("outfile", "mask_image")]),
(inputNode, n4_correct, [("motion-basefile", "input_image")]),
(n4_correct, skullstrip_first_pass, [("output_image", "in_file")]),
(skullstrip_first_pass, bet_dilate, [("mask_file", "in_file")]),
(bet_dilate, bet_mask, [("out_file", "mask_file")]),
(skullstrip_first_pass, bet_mask, [("out_file", "in_file")]),
(bet_mask, unifize, [("out_file", "in_file")]),
(unifize, skullstrip_second_pass, [("out_file", "in_file")]),
(skullstrip_first_pass, combine_masks, [("mask_file", "in_file")]),
(skullstrip_second_pass, combine_masks, [("out_file", "operand_file")]),
(unifize, apply_mask, [("out_file", "in_file")]),
(combine_masks, apply_mask, [("out_file", "mask_file")]),
(combine_masks, outputNode, [("out_file", "space-bold_desc-brain_mask")]),
(apply_mask, outputNode, [("out_file", "desc-unifized_bold")]),
]
)
return wf
@nodeblock(
name="func_reorient",
config=["functional_preproc", "update_header"],
switch=["run"],
inputs=["bold"],
outputs=["desc-preproc_bold", "desc-reorient_bold"],
)
def func_reorient(wf, cfg, strat_pool, pipe_num, opt=None):
"""Reorient functional timeseries."""
func_deoblique = pe.Node(
interface=afni_utils.Refit(),
name=f"func_deoblique_{pipe_num}",
mem_gb=0.68,
mem_x=(4664065662093477 / 1208925819614629174706176, "in_file"),
)
func_deoblique.inputs.deoblique = True
node, out = strat_pool.get_data("bold")
wf.connect(node, out, func_deoblique, "in_file")
func_reorient = cfg.orientation_node(f"func_reorient_{pipe_num}")
wf.connect(func_deoblique, "out_file", func_reorient, "in_file")
outputs = {
"desc-preproc_bold": (func_reorient, "out_file"),
"desc-reorient_bold": (func_reorient, "out_file"),
}
return (wf, outputs)
@nodeblock(
name="func_scaling",
config=["functional_preproc", "scaling"],
switch=["run"],
inputs=["desc-preproc_bold"],
outputs=["desc-preproc_bold"],
)
def func_scaling(wf, cfg, strat_pool, pipe_num, opt=None):
"""Scale functional timeseries."""
scale_func_wf = create_scale_func_wf(
scaling_factor=cfg.scaling_factor, wf_name=f"scale_func_{pipe_num}"
)
node, out = strat_pool.get_data("desc-preproc_bold")
wf.connect(node, out, scale_func_wf, "inputspec.func")
outputs = {"desc-preproc_bold": (scale_func_wf, "outputspec.scaled_func")}
return (wf, outputs)
@nodeblock(
name="func_truncate",
config=["functional_preproc", "truncation"],
inputs=["desc-preproc_bold"],
outputs={
"desc-preproc_bold": {
"Description": "Truncated functional time-series BOLD data."
}
},
)
def func_truncate(wf, cfg, strat_pool, pipe_num, opt=None):
"""Truncate functional timeseries."""
# if cfg.functional_preproc['truncation']['start_tr'] == 0 and \
# cfg.functional_preproc['truncation']['stop_tr'] == None:
# data, key = strat_pool.get_data("desc-preproc_bold",
# True)
# outputs = {key: data}
# return (wf, outputs)
trunc_wf = create_wf_edit_func(wf_name=f"edit_func_{pipe_num}")
trunc_wf.inputs.inputspec.start_idx = cfg.functional_preproc["truncation"][
"start_tr"
]
trunc_wf.inputs.inputspec.stop_idx = cfg.functional_preproc["truncation"]["stop_tr"]
node, out = strat_pool.get_data("desc-preproc_bold")
wf.connect(node, out, trunc_wf, "inputspec.func")
outputs = {"desc-preproc_bold": (trunc_wf, "outputspec.edited_func")}
return (wf, outputs)
@nodeblock(
name="func_despike",
config=["functional_preproc", "despiking"],
switch=["run"],
option_key=["space"],
option_val=["native"],
inputs=["desc-preproc_bold"],
outputs={
"desc-preproc_bold": {
"Description": "De-spiked BOLD time-series via AFNI 3dDespike."
}
},
)
def func_despike(wf, cfg, strat_pool, pipe_num, opt=None):
"""Generate de-spiked functional timeseries in native space with AFNI."""
despike = pe.Node(
interface=preprocess.Despike(),
name=f"func_despiked_{pipe_num}",
mem_gb=0.66,
mem_x=(8251808479088459 / 1208925819614629174706176, "in_file"),
)
despike.inputs.outputtype = "NIFTI_GZ"
node, out = strat_pool.get_data("desc-preproc_bold")
wf.connect(node, out, despike, "in_file")
outputs = {"desc-preproc_bold": (despike, "out_file")}
return (wf, outputs)
@nodeblock(
name="func_despike_template",
config=["functional_preproc", "despiking"],
switch=["run"],
option_key=["space"],
option_val=["template"],
inputs=[
(
"space-template_desc-preproc_bold",
"space-template_res-derivative_desc-preproc_bold",
),
"T1w-template-funcreg",
"T1w-template-deriv",
],
outputs={
"space-template_desc-preproc_bold": {
"Description": "De-spiked BOLD time-series via AFNI 3dDespike.",
"Template": "T1w-template-funcreg",
},
"space-template_res-derivative_desc-preproc_bold": {
"Description": "De-spiked BOLD time-series via AFNI 3dDespike.",
"Template": "T1w-template-deriv",
},
},
)
def func_despike_template(wf, cfg, strat_pool, pipe_num, opt=None):
"""Generate de-spiked functional timeseries in template space with AFNI."""
despike = pe.Node(
interface=preprocess.Despike(),
name=f"func_despiked_template_{pipe_num}",
mem_gb=0.66,
mem_x=(8251808479088459 / 1208925819614629174706176, "in_file"),
)
despike.inputs.outputtype = "NIFTI_GZ"
node, out = strat_pool.get_data("space-template_desc-preproc_bold")
wf.connect(node, out, despike, "in_file")
outputs = {"space-template_desc-preproc_bold": (despike, "out_file")}
if strat_pool.get_data("space-template_res-derivative_desc-preproc_bold"):
despike_funcderiv = pe.Node(
interface=preprocess.Despike(),
name=f"func_deriv_despiked_template_{pipe_num}",
mem_gb=0.66,
mem_x=(8251808479088459 / 1208925819614629174706176, "in_file"),
)
despike_funcderiv.inputs.outputtype = "NIFTI_GZ"
node, out = strat_pool.get_data(
"space-template_res-derivative_desc-preproc_bold"
)
wf.connect(node, out, despike_funcderiv, "in_file")
outputs.update(
{
"space-template_res-derivative_desc-preproc_bold": (
despike_funcderiv,
"out_file",
)
}
)
return (wf, outputs)
@nodeblock(
name="func_slice_time",
config=["functional_preproc", "slice_timing_correction"],
switch=["run"],
inputs=["desc-preproc_bold", "TR", "tpattern"],
outputs={
"desc-preproc_bold": {
"Description": "Slice-time corrected BOLD time-series via AFNI 3dTShift."
},
"desc-stc_bold": {
"Description": "Slice-time corrected BOLD time-series via AFNI 3dTShift."
},
},
)
def func_slice_time(wf, cfg, strat_pool, pipe_num, opt=None):
"""Genetare slice-time correctied timeseries."""
slice_time = slice_timing_wf(
name=f"func_slice_timing_correction_{pipe_num}",
tpattern=cfg.functional_preproc["slice_timing_correction"]["tpattern"],
tzero=cfg.functional_preproc["slice_timing_correction"]["tzero"],
)
node, out = strat_pool.get_data("desc-preproc_bold")
wf.connect(node, out, slice_time, "inputspec.func_ts")
node, out = strat_pool.get_data("TR")
wf.connect(node, out, slice_time, "inputspec.tr")
node, out = strat_pool.get_data("tpattern")
wf.connect(node, out, slice_time, "inputspec.tpattern")
outputs = {
"desc-preproc_bold": (slice_time, "outputspec.slice_time_corrected"),
"desc-stc_bold": (slice_time, "outputspec.slice_time_corrected"),
}
return (wf, outputs)
@nodeblock(
name="bold_mask_afni",
switch=[
["functional_preproc", "run"],
["functional_preproc", "func_masking", "run"],
],
option_key=["functional_preproc", "func_masking", "using"],
option_val="AFNI",
inputs=["desc-preproc_bold"],
outputs={
"space-bold_desc-brain_mask": {
"Description": "Binary brain mask of the BOLD functional time-series created by AFNI 3dAutomask."
}
},
)
def bold_mask_afni(wf, cfg, strat_pool, pipe_num, opt=None):
"""Generate a functional mask with AFNI."""
func_get_brain_mask = pe.Node(
interface=preprocess.Automask(), name=f"func_get_brain_mask_AFNI_{pipe_num}"
)
func_get_brain_mask.inputs.outputtype = "NIFTI_GZ"
node, out = strat_pool.get_data("desc-preproc_bold")
wf.connect(node, out, func_get_brain_mask, "in_file")
outputs = {"space-bold_desc-brain_mask": (func_get_brain_mask, "out_file")}
return (wf, outputs)
@nodeblock(
name="bold_mask_fsl",
switch=[
["functional_preproc", "run"],
["functional_preproc", "func_masking", "run"],
],
option_key=["functional_preproc", "func_masking", "using"],
option_val="FSL",
inputs=["desc-preproc_bold"],
outputs=["space-bold_desc-brain_mask"],
)
def bold_mask_fsl(wf, cfg, strat_pool, pipe_num, opt=None):
"""Generate functional mask with FSL."""
inputnode_bet = pe.Node(
util.IdentityInterface(
fields=[
"frac",
"mesh_boolean",
"outline",
"padding",
"radius",
"reduce_bias",
"remove_eyes",
"robust",
"skull",
"surfaces",
"threshold",
"vertical_gradient",
]
),
name=f"BET_options_{pipe_num}",
)
func_get_brain_mask = pe.Node(
interface=fsl.BET(), name=f"func_get_brain_mask_BET_{pipe_num}"
)
func_get_brain_mask.inputs.output_type = "NIFTI_GZ"
func_get_brain_mask.inputs.mask = True
inputnode_bet.inputs.set(
frac=cfg.functional_preproc["func_masking"]["FSL-BET"]["frac"],
mesh_boolean=cfg.functional_preproc["func_masking"]["FSL-BET"]["mesh_boolean"],
outline=cfg.functional_preproc["func_masking"]["FSL-BET"]["outline"],
padding=cfg.functional_preproc["func_masking"]["FSL-BET"]["padding"],
radius=cfg.functional_preproc["func_masking"]["FSL-BET"]["radius"],
reduce_bias=cfg.functional_preproc["func_masking"]["FSL-BET"]["reduce_bias"],
remove_eyes=cfg.functional_preproc["func_masking"]["FSL-BET"]["remove_eyes"],
robust=cfg.functional_preproc["func_masking"]["FSL-BET"]["robust"],
skull=cfg.functional_preproc["func_masking"]["FSL-BET"]["skull"],