-
Notifications
You must be signed in to change notification settings - Fork 521
/
preprocess.py
4508 lines (3999 loc) · 152 KB
/
preprocess.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
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
# -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""AFNI preprocessing interfaces."""
import os
import os.path as op
from ...utils.filemanip import load_json, save_json, split_filename, fname_presuffix
from ..base import (
CommandLineInputSpec,
CommandLine,
TraitedSpec,
traits,
isdefined,
File,
InputMultiPath,
Undefined,
Str,
InputMultiObject,
)
from .base import (
AFNICommandBase,
AFNICommand,
AFNICommandInputSpec,
AFNICommandOutputSpec,
AFNIPythonCommandInputSpec,
AFNIPythonCommand,
Info,
no_afni,
)
from ... import logging
iflogger = logging.getLogger("nipype.interface")
class CentralityInputSpec(AFNICommandInputSpec):
"""Common input spec class for all centrality-related commands"""
mask = File(desc="mask file to mask input data", argstr="-mask %s", exists=True)
thresh = traits.Float(
desc="threshold to exclude connections where corr <= thresh",
argstr="-thresh %f",
)
polort = traits.Int(desc="", argstr="-polort %d")
autoclip = traits.Bool(
desc="Clip off low-intensity regions in the dataset", argstr="-autoclip"
)
automask = traits.Bool(
desc="Mask the dataset to target brain-only voxels", argstr="-automask"
)
class AlignEpiAnatPyInputSpec(AFNIPythonCommandInputSpec):
in_file = File(
desc="EPI dataset to align",
argstr="-epi %s",
mandatory=True,
exists=True,
copyfile=False,
)
anat = File(
desc="name of structural dataset",
argstr="-anat %s",
mandatory=True,
exists=True,
copyfile=False,
)
epi_base = traits.Either(
traits.Range(low=0),
traits.Enum("mean", "median", "max"),
desc="the epi base used in alignment"
"should be one of (0/mean/median/max/subbrick#)",
mandatory=True,
argstr="-epi_base %s",
)
anat2epi = traits.Bool(
desc="align anatomical to EPI dataset (default)", argstr="-anat2epi"
)
epi2anat = traits.Bool(desc="align EPI to anatomical dataset", argstr="-epi2anat")
save_skullstrip = traits.Bool(
desc="save skull-stripped (not aligned)", argstr="-save_skullstrip"
)
suffix = traits.Str(
"_al",
desc="append suffix to the original anat/epi dataset to use"
'in the resulting dataset names (default is "_al")',
usedefault=True,
argstr="-suffix %s",
)
epi_strip = traits.Enum(
("3dSkullStrip", "3dAutomask", "None"),
desc="method to mask brain in EPI data"
"should be one of[3dSkullStrip]/3dAutomask/None)",
argstr="-epi_strip %s",
)
volreg = traits.Enum(
"on",
"off",
usedefault=True,
desc="do volume registration on EPI dataset before alignment"
"should be 'on' or 'off', defaults to 'on'",
argstr="-volreg %s",
)
tshift = traits.Enum(
"on",
"off",
usedefault=True,
desc="do time shifting of EPI dataset before alignment"
"should be 'on' or 'off', defaults to 'on'",
argstr="-tshift %s",
)
class AlignEpiAnatPyOutputSpec(TraitedSpec):
anat_al_orig = File(desc="A version of the anatomy that is aligned to the EPI")
epi_al_orig = File(desc="A version of the EPI dataset aligned to the anatomy")
epi_tlrc_al = File(
desc="A version of the EPI dataset aligned to a standard template"
)
anat_al_mat = File(desc="matrix to align anatomy to the EPI")
epi_al_mat = File(desc="matrix to align EPI to anatomy")
epi_vr_al_mat = File(desc="matrix to volume register EPI")
epi_reg_al_mat = File(desc="matrix to volume register and align epi to anatomy")
epi_al_tlrc_mat = File(
desc="matrix to volume register and align epi"
"to anatomy and put into standard space"
)
epi_vr_motion = File(
desc="motion parameters from EPI time-series"
"registration (tsh included in name if slice"
"timing correction is also included)."
)
skullstrip = File(desc="skull-stripped (not aligned) volume")
class AlignEpiAnatPy(AFNIPythonCommand):
"""Align EPI to anatomical datasets or vice versa.
This Python script computes the alignment between two datasets, typically
an EPI and an anatomical structural dataset, and applies the resulting
transformation to one or the other to bring them into alignment.
This script computes the transforms needed to align EPI and
anatomical datasets using a cost function designed for this purpose. The
script combines multiple transformations, thereby minimizing the amount of
interpolation applied to the data.
Basic Usage::
align_epi_anat.py -anat anat+orig -epi epi+orig -epi_base 5
The user must provide :abbr:`EPI (echo-planar imaging)` and anatomical datasets
and specify the EPI sub-brick to use as a base in the alignment.
Internally, the script always aligns the anatomical to the EPI dataset,
and the resulting transformation is saved to a 1D file.
As a user option, the inverse of this transformation may be applied to the
EPI dataset in order to align it to the anatomical data instead.
This program generates several kinds of output in the form of datasets
and transformation matrices which can be applied to other datasets if
needed. Time-series volume registration, oblique data transformations and
Talairach (standard template) transformations will be combined as needed
and requested (with options to turn on and off each of the steps) in
order to create the aligned datasets.
Examples
--------
>>> from nipype.interfaces import afni
>>> al_ea = afni.AlignEpiAnatPy()
>>> al_ea.inputs.anat = "structural.nii"
>>> al_ea.inputs.in_file = "functional.nii"
>>> al_ea.inputs.epi_base = 0
>>> al_ea.inputs.epi_strip = '3dAutomask'
>>> al_ea.inputs.volreg = 'off'
>>> al_ea.inputs.tshift = 'off'
>>> al_ea.inputs.save_skullstrip = True
>>> al_ea.cmdline # doctest: +ELLIPSIS
'python2 ...align_epi_anat.py -anat structural.nii -epi_base 0 -epi_strip 3dAutomask -epi \
functional.nii -save_skullstrip -suffix _al -tshift off -volreg off'
>>> res = allineate.run() # doctest: +SKIP
See Also
--------
For complete details, see the `align_epi_anat.py documentation.
<https://afni.nimh.nih.gov/pub/dist/doc/program_help/align_epi_anat.py.html>`__.
"""
_cmd = "align_epi_anat.py"
input_spec = AlignEpiAnatPyInputSpec
output_spec = AlignEpiAnatPyOutputSpec
def _list_outputs(self):
outputs = self.output_spec().get()
anat_prefix = self._gen_fname(self.inputs.anat)
epi_prefix = self._gen_fname(self.inputs.in_file)
if "+" in anat_prefix:
anat_prefix = "".join(anat_prefix.split("+")[:-1])
if "+" in epi_prefix:
epi_prefix = "".join(epi_prefix.split("+")[:-1])
outputtype = self.inputs.outputtype
if outputtype == "AFNI":
ext = ".HEAD"
else:
ext = Info.output_type_to_ext(outputtype)
matext = ".1D"
suffix = self.inputs.suffix
if self.inputs.anat2epi:
outputs["anat_al_orig"] = self._gen_fname(
anat_prefix, suffix=suffix + "+orig", ext=ext
)
outputs["anat_al_mat"] = self._gen_fname(
anat_prefix, suffix=suffix + "_mat.aff12", ext=matext
)
if self.inputs.epi2anat:
outputs["epi_al_orig"] = self._gen_fname(
epi_prefix, suffix=suffix + "+orig", ext=ext
)
outputs["epi_al_mat"] = self._gen_fname(
epi_prefix, suffix=suffix + "_mat.aff12", ext=matext
)
if self.inputs.volreg == "on":
outputs["epi_vr_al_mat"] = self._gen_fname(
epi_prefix, suffix="_vr" + suffix + "_mat.aff12", ext=matext
)
if self.inputs.tshift == "on":
outputs["epi_vr_motion"] = self._gen_fname(
epi_prefix, suffix="tsh_vr_motion", ext=matext
)
elif self.inputs.tshift == "off":
outputs["epi_vr_motion"] = self._gen_fname(
epi_prefix, suffix="vr_motion", ext=matext
)
if self.inputs.volreg == "on" and self.inputs.epi2anat:
outputs["epi_reg_al_mat"] = self._gen_fname(
epi_prefix, suffix="_reg" + suffix + "_mat.aff12", ext=matext
)
if self.inputs.save_skullstrip:
outputs.skullstrip = self._gen_fname(
anat_prefix, suffix="_ns" + "+orig", ext=ext
)
return outputs
class AllineateInputSpec(AFNICommandInputSpec):
in_file = File(
desc="input file to 3dAllineate",
argstr="-source %s",
mandatory=True,
exists=True,
copyfile=False,
)
reference = File(
exists=True,
argstr="-base %s",
desc="file to be used as reference, the first volume will be used if "
"not given the reference will be the first volume of in_file.",
)
out_file = File(
desc="output file from 3dAllineate",
argstr="-prefix %s",
name_template="%s_allineate",
name_source="in_file",
hash_files=False,
xor=["allcostx"],
)
out_param_file = File(
argstr="-1Dparam_save %s",
desc="Save the warp parameters in ASCII (.1D) format.",
xor=["in_param_file", "allcostx"],
)
in_param_file = File(
exists=True,
argstr="-1Dparam_apply %s",
desc="Read warp parameters from file and apply them to "
"the source dataset, and produce a new dataset",
xor=["out_param_file"],
)
out_matrix = File(
argstr="-1Dmatrix_save %s",
desc="Save the transformation matrix for each volume.",
xor=["in_matrix", "allcostx"],
)
in_matrix = File(
desc="matrix to align input file",
argstr="-1Dmatrix_apply %s",
position=-3,
xor=["out_matrix"],
)
overwrite = traits.Bool(
desc="overwrite output file if it already exists", argstr="-overwrite"
)
allcostx = File(
desc="Compute and print ALL available cost functionals for the un-warped inputs"
"AND THEN QUIT. If you use this option none of the other expected outputs will be produced",
argstr="-allcostx |& tee %s",
position=-1,
xor=["out_file", "out_matrix", "out_param_file", "out_weight_file"],
)
_cost_funcs = [
"leastsq",
"ls",
"mutualinfo",
"mi",
"corratio_mul",
"crM",
"norm_mutualinfo",
"nmi",
"hellinger",
"hel",
"corratio_add",
"crA",
"corratio_uns",
"crU",
]
cost = traits.Enum(
*_cost_funcs,
argstr="-cost %s",
desc="Defines the 'cost' function that defines the matching between "
"the source and the base"
)
_interp_funcs = ["nearestneighbour", "linear", "cubic", "quintic", "wsinc5"]
interpolation = traits.Enum(
*_interp_funcs[:-1],
argstr="-interp %s",
desc="Defines interpolation method to use during matching"
)
final_interpolation = traits.Enum(
*_interp_funcs,
argstr="-final %s",
desc="Defines interpolation method used to create the output dataset"
)
# TECHNICAL OPTIONS (used for fine control of the program):
nmatch = traits.Int(
argstr="-nmatch %d",
desc="Use at most n scattered points to match the datasets.",
)
no_pad = traits.Bool(
argstr="-nopad", desc="Do not use zero-padding on the base image."
)
zclip = traits.Bool(
argstr="-zclip",
desc="Replace negative values in the input datasets (source & base) "
"with zero.",
)
convergence = traits.Float(
argstr="-conv %f", desc="Convergence test in millimeters (default 0.05mm)."
)
usetemp = traits.Bool(argstr="-usetemp", desc="temporary file use")
check = traits.List(
traits.Enum(*_cost_funcs),
argstr="-check %s",
desc="After cost functional optimization is done, start at the final "
"parameters and RE-optimize using this new cost functions. If "
"the results are too different, a warning message will be "
"printed. However, the final parameters from the original "
"optimization will be used to create the output dataset.",
)
# ** PARAMETERS THAT AFFECT THE COST OPTIMIZATION STRATEGY **
one_pass = traits.Bool(
argstr="-onepass",
desc="Use only the refining pass -- do not try a coarse resolution "
"pass first. Useful if you know that only small amounts of "
"image alignment are needed.",
)
two_pass = traits.Bool(
argstr="-twopass",
desc="Use a two pass alignment strategy for all volumes, searching "
"for a large rotation+shift and then refining the alignment.",
)
two_blur = traits.Float(
argstr="-twoblur %f", desc="Set the blurring radius for the first pass in mm."
)
two_first = traits.Bool(
argstr="-twofirst",
desc="Use -twopass on the first image to be registered, and "
"then on all subsequent images from the source dataset, "
"use results from the first image's coarse pass to start "
"the fine pass.",
)
two_best = traits.Int(
argstr="-twobest %d",
desc="In the coarse pass, use the best 'bb' set of initial"
"points to search for the starting point for the fine"
"pass. If bb==0, then no search is made for the best"
"starting point, and the identity transformation is"
"used as the starting point. [Default=5; min=0 max=11]",
)
fine_blur = traits.Float(
argstr="-fineblur %f",
desc="Set the blurring radius to use in the fine resolution "
"pass to 'x' mm. A small amount (1-2 mm?) of blurring at "
"the fine step may help with convergence, if there is "
"some problem, especially if the base volume is very noisy. "
"[Default == 0 mm = no blurring at the final alignment pass]",
)
center_of_mass = Str(
argstr="-cmass%s",
desc="Use the center-of-mass calculation to bracket the shifts.",
)
autoweight = Str(
argstr="-autoweight%s",
desc="Compute a weight function using the 3dAutomask "
"algorithm plus some blurring of the base image.",
)
automask = traits.Int(
argstr="-automask+%d",
desc="Compute a mask function, set a value for dilation or 0.",
)
autobox = traits.Bool(
argstr="-autobox",
desc="Expand the -automask function to enclose a rectangular "
"box that holds the irregular mask.",
)
nomask = traits.Bool(
argstr="-nomask",
desc="Don't compute the autoweight/mask; if -weight is not "
"also used, then every voxel will be counted equally.",
)
weight_file = File(
argstr="-weight %s",
exists=True,
deprecated="1.0.0",
new_name="weight",
desc="Set the weighting for each voxel in the base dataset; "
"larger weights mean that voxel count more in the cost function. "
"Must be defined on the same grid as the base dataset",
)
weight = traits.Either(
File(exists=True),
traits.Float(),
argstr="-weight %s",
desc="Set the weighting for each voxel in the base dataset; "
"larger weights mean that voxel count more in the cost function. "
"If an image file is given, the volume must be defined on the "
"same grid as the base dataset",
)
out_weight_file = File(
argstr="-wtprefix %s",
desc="Write the weight volume to disk as a dataset",
xor=["allcostx"],
)
source_mask = File(
exists=True, argstr="-source_mask %s", desc="mask the input dataset"
)
source_automask = traits.Int(
argstr="-source_automask+%d",
desc="Automatically mask the source dataset with dilation or 0.",
)
warp_type = traits.Enum(
"shift_only",
"shift_rotate",
"shift_rotate_scale",
"affine_general",
argstr="-warp %s",
desc="Set the warp type.",
)
warpfreeze = traits.Bool(
argstr="-warpfreeze",
desc="Freeze the non-rigid body parameters after first volume.",
)
replacebase = traits.Bool(
argstr="-replacebase",
desc="If the source has more than one volume, then after the first "
"volume is aligned to the base.",
)
replacemeth = traits.Enum(
*_cost_funcs,
argstr="-replacemeth %s",
desc="After first volume is aligned, switch method for later volumes. "
"For use with '-replacebase'."
)
epi = traits.Bool(
argstr="-EPI",
desc="Treat the source dataset as being composed of warped "
"EPI slices, and the base as comprising anatomically "
"'true' images. Only phase-encoding direction image "
"shearing and scaling will be allowed with this option.",
)
maxrot = traits.Float(
argstr="-maxrot %f", desc="Maximum allowed rotation in degrees."
)
maxshf = traits.Float(argstr="-maxshf %f", desc="Maximum allowed shift in mm.")
maxscl = traits.Float(argstr="-maxscl %f", desc="Maximum allowed scaling factor.")
maxshr = traits.Float(argstr="-maxshr %f", desc="Maximum allowed shearing factor.")
master = File(
exists=True,
argstr="-master %s",
desc="Write the output dataset on the same grid as this file.",
)
newgrid = traits.Float(
argstr="-newgrid %f",
desc="Write the output dataset using isotropic grid spacing in mm.",
)
# Non-linear experimental
_nwarp_types = [
"bilinear",
"cubic",
"quintic",
"heptic",
"nonic",
"poly3",
"poly5",
"poly7",
"poly9",
] # same non-hellenistic
nwarp = traits.Enum(
*_nwarp_types,
argstr="-nwarp %s",
desc="Experimental nonlinear warping: bilinear or legendre poly."
)
_dirs = ["X", "Y", "Z", "I", "J", "K"]
nwarp_fixmot = traits.List(
traits.Enum(*_dirs),
argstr="-nwarp_fixmot%s...",
desc="To fix motion along directions.",
)
nwarp_fixdep = traits.List(
traits.Enum(*_dirs),
argstr="-nwarp_fixdep%s...",
desc="To fix non-linear warp dependency along directions.",
)
verbose = traits.Bool(argstr="-verb", desc="Print out verbose progress reports.")
quiet = traits.Bool(
argstr="-quiet", desc="Don't print out verbose progress reports."
)
class AllineateOutputSpec(TraitedSpec):
out_file = File(exists=True, desc="output image file name")
out_matrix = File(exists=True, desc="matrix to align input file")
out_param_file = File(exists=True, desc="warp parameters")
out_weight_file = File(exists=True, desc="weight volume")
allcostx = File(
desc="Compute and print ALL available cost functionals for the un-warped inputs"
)
class Allineate(AFNICommand):
"""Program to align one dataset (the 'source') to a base dataset
For complete details, see the `3dAllineate Documentation.
<https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dAllineate.html>`_
Examples
--------
>>> from nipype.interfaces import afni
>>> allineate = afni.Allineate()
>>> allineate.inputs.in_file = 'functional.nii'
>>> allineate.inputs.out_file = 'functional_allineate.nii'
>>> allineate.inputs.in_matrix = 'cmatrix.mat'
>>> allineate.cmdline
'3dAllineate -source functional.nii -prefix functional_allineate.nii -1Dmatrix_apply cmatrix.mat'
>>> res = allineate.run() # doctest: +SKIP
>>> allineate = afni.Allineate()
>>> allineate.inputs.in_file = 'functional.nii'
>>> allineate.inputs.reference = 'structural.nii'
>>> allineate.inputs.allcostx = 'out.allcostX.txt'
>>> allineate.cmdline
'3dAllineate -source functional.nii -base structural.nii -allcostx |& tee out.allcostX.txt'
>>> res = allineate.run() # doctest: +SKIP
>>> allineate = afni.Allineate()
>>> allineate.inputs.in_file = 'functional.nii'
>>> allineate.inputs.reference = 'structural.nii'
>>> allineate.inputs.nwarp_fixmot = ['X', 'Y']
>>> allineate.cmdline
'3dAllineate -source functional.nii -nwarp_fixmotX -nwarp_fixmotY -prefix functional_allineate -base structural.nii'
>>> res = allineate.run() # doctest: +SKIP
"""
_cmd = "3dAllineate"
input_spec = AllineateInputSpec
output_spec = AllineateOutputSpec
def _list_outputs(self):
outputs = super(Allineate, self)._list_outputs()
if self.inputs.out_weight_file:
outputs["out_weight_file"] = op.abspath(self.inputs.out_weight_file)
if self.inputs.out_matrix:
ext = split_filename(self.inputs.out_matrix)[-1]
if ext.lower() not in [".1d", ".1D"]:
outputs["out_matrix"] = self._gen_fname(
self.inputs.out_matrix, suffix=".aff12.1D"
)
else:
outputs["out_matrix"] = op.abspath(self.inputs.out_matrix)
if self.inputs.out_param_file:
ext = split_filename(self.inputs.out_param_file)[-1]
if ext.lower() not in [".1d", ".1D"]:
outputs["out_param_file"] = self._gen_fname(
self.inputs.out_param_file, suffix=".param.1D"
)
else:
outputs["out_param_file"] = op.abspath(self.inputs.out_param_file)
if self.inputs.allcostx:
outputs["allcostX"] = os.path.abspath(self.inputs.allcostx)
return outputs
class AutoTcorrelateInputSpec(AFNICommandInputSpec):
in_file = File(
desc="timeseries x space (volume or surface) file",
argstr="%s",
position=-1,
mandatory=True,
exists=True,
copyfile=False,
)
polort = traits.Int(
desc="Remove polynomical trend of order m or -1 for no detrending",
argstr="-polort %d",
)
eta2 = traits.Bool(desc="eta^2 similarity", argstr="-eta2")
mask = File(exists=True, desc="mask of voxels", argstr="-mask %s")
mask_only_targets = traits.Bool(
desc="use mask only on targets voxels",
argstr="-mask_only_targets",
xor=["mask_source"],
)
mask_source = File(
exists=True,
desc="mask for source voxels",
argstr="-mask_source %s",
xor=["mask_only_targets"],
)
out_file = File(
name_template="%s_similarity_matrix.1D",
desc="output image file name",
argstr="-prefix %s",
name_source="in_file",
)
class AutoTcorrelate(AFNICommand):
"""Computes the correlation coefficient between the time series of each
pair of voxels in the input dataset, and stores the output into a
new anatomical bucket dataset [scaled to shorts to save memory space].
For complete details, see the `3dAutoTcorrelate Documentation.
<https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dAutoTcorrelate.html>`_
Examples
--------
>>> from nipype.interfaces import afni
>>> corr = afni.AutoTcorrelate()
>>> corr.inputs.in_file = 'functional.nii'
>>> corr.inputs.polort = -1
>>> corr.inputs.eta2 = True
>>> corr.inputs.mask = 'mask.nii'
>>> corr.inputs.mask_only_targets = True
>>> corr.cmdline # doctest: +ELLIPSIS
'3dAutoTcorrelate -eta2 -mask mask.nii -mask_only_targets -prefix functional_similarity_matrix.1D -polort -1 functional.nii'
>>> res = corr.run() # doctest: +SKIP
"""
input_spec = AutoTcorrelateInputSpec
output_spec = AFNICommandOutputSpec
_cmd = "3dAutoTcorrelate"
def _overload_extension(self, value, name=None):
path, base, ext = split_filename(value)
if ext.lower() not in [".1d", ".1D", ".nii.gz", ".nii"]:
ext = ext + ".1D"
return os.path.join(path, base + ext)
class AutomaskInputSpec(AFNICommandInputSpec):
in_file = File(
desc="input file to 3dAutomask",
argstr="%s",
position=-1,
mandatory=True,
exists=True,
copyfile=False,
)
out_file = File(
name_template="%s_mask",
desc="output image file name",
argstr="-prefix %s",
name_source="in_file",
)
brain_file = File(
name_template="%s_masked",
desc="output file from 3dAutomask",
argstr="-apply_prefix %s",
name_source="in_file",
)
clfrac = traits.Float(
desc="sets the clip level fraction (must be 0.1-0.9). A small value "
"will tend to make the mask larger [default = 0.5].",
argstr="-clfrac %s",
)
dilate = traits.Int(desc="dilate the mask outwards", argstr="-dilate %s")
erode = traits.Int(desc="erode the mask inwards", argstr="-erode %s")
class AutomaskOutputSpec(TraitedSpec):
out_file = File(desc="mask file", exists=True)
brain_file = File(desc="brain file (skull stripped)", exists=True)
class Automask(AFNICommand):
"""Create a brain-only mask of the image using AFNI 3dAutomask command
For complete details, see the `3dAutomask Documentation.
<https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dAutomask.html>`_
Examples
--------
>>> from nipype.interfaces import afni
>>> automask = afni.Automask()
>>> automask.inputs.in_file = 'functional.nii'
>>> automask.inputs.dilate = 1
>>> automask.inputs.outputtype = 'NIFTI'
>>> automask.cmdline # doctest: +ELLIPSIS
'3dAutomask -apply_prefix functional_masked.nii -dilate 1 -prefix functional_mask.nii functional.nii'
>>> res = automask.run() # doctest: +SKIP
"""
_cmd = "3dAutomask"
input_spec = AutomaskInputSpec
output_spec = AutomaskOutputSpec
class AutoTLRCInputSpec(CommandLineInputSpec):
outputtype = traits.Enum(
"AFNI", list(Info.ftypes.keys()), desc="AFNI output filetype"
)
in_file = File(
desc="Original anatomical volume (+orig)."
"The skull is removed by this script"
"unless instructed otherwise (-no_ss).",
argstr="-input %s",
mandatory=True,
exists=True,
copyfile=False,
)
base = traits.Str(
desc="""\
Reference anatomical volume.
Usually this volume is in some standard space like
TLRC or MNI space and with afni dataset view of
(+tlrc).
Preferably, this reference volume should have had
the skull removed but that is not mandatory.
AFNI's distribution contains several templates.
For a longer list, use "whereami -show_templates"
TT_N27+tlrc --> Single subject, skull stripped volume.
This volume is also known as
N27_SurfVol_NoSkull+tlrc elsewhere in
AFNI and SUMA land.
(www.loni.ucla.edu, www.bic.mni.mcgill.ca)
This template has a full set of FreeSurfer
(surfer.nmr.mgh.harvard.edu)
surface models that can be used in SUMA.
For details, see Talairach-related link:
https://afni.nimh.nih.gov/afni/suma
TT_icbm452+tlrc --> Average volume of 452 normal brains.
Skull Stripped. (www.loni.ucla.edu)
TT_avg152T1+tlrc --> Average volume of 152 normal brains.
Skull Stripped.(www.bic.mni.mcgill.ca)
TT_EPI+tlrc --> EPI template from spm2, masked as TT_avg152T1
TT_avg152 and TT_EPI volume sources are from
SPM's distribution. (www.fil.ion.ucl.ac.uk/spm/)
If you do not specify a path for the template, the script
will attempt to locate the template AFNI's binaries directory.
NOTE: These datasets have been slightly modified from
their original size to match the standard TLRC
dimensions (Jean Talairach and Pierre Tournoux
Co-Planar Stereotaxic Atlas of the Human Brain
Thieme Medical Publishers, New York, 1988).
That was done for internal consistency in AFNI.
You may use the original form of these
volumes if you choose but your TLRC coordinates
will not be consistent with AFNI's TLRC database
(San Antonio Talairach Daemon database), for example.""",
mandatory=True,
argstr="-base %s",
)
no_ss = traits.Bool(
desc="""\
Do not strip skull of input data set
(because skull has already been removed
or because template still has the skull)
NOTE: The ``-no_ss`` option is not all that optional.
Here is a table of when you should and should not use ``-no_ss``
+------------------+------------+---------------+
| Dataset | Template |
+==================+============+===============+
| | w/ skull | wo/ skull |
+------------------+------------+---------------+
| WITH skull | ``-no_ss`` | xxx |
+------------------+------------+---------------+
| WITHOUT skull | No Cigar | ``-no_ss`` |
+------------------+------------+---------------+
Template means: Your template of choice
Dset. means: Your anatomical dataset
``-no_ss`` means: Skull stripping should not be attempted on Dset
xxx means: Don't put anything, the script will strip Dset
No Cigar means: Don't try that combination, it makes no sense.""",
argstr="-no_ss",
)
class AutoTLRC(AFNICommand):
"""A minmal wrapper for the AutoTLRC script
The only option currently supported is no_ss.
For complete details, see the `3dQwarp Documentation.
<https://afni.nimh.nih.gov/pub/dist/doc/program_help/@auto_tlrc.html>`_
Examples
--------
>>> from nipype.interfaces import afni
>>> autoTLRC = afni.AutoTLRC()
>>> autoTLRC.inputs.in_file = 'structural.nii'
>>> autoTLRC.inputs.no_ss = True
>>> autoTLRC.inputs.base = "TT_N27+tlrc"
>>> autoTLRC.cmdline
'@auto_tlrc -base TT_N27+tlrc -input structural.nii -no_ss'
>>> res = autoTLRC.run() # doctest: +SKIP
"""
_cmd = "@auto_tlrc"
input_spec = AutoTLRCInputSpec
output_spec = AFNICommandOutputSpec
def _list_outputs(self):
outputs = self.output_spec().get()
ext = ".HEAD"
outputs["out_file"] = os.path.abspath(
self._gen_fname(self.inputs.in_file, suffix="+tlrc") + ext
)
return outputs
class BandpassInputSpec(AFNICommandInputSpec):
in_file = File(
desc="input file to 3dBandpass",
argstr="%s",
position=-1,
mandatory=True,
exists=True,
copyfile=False,
)
out_file = File(
name_template="%s_bp",
desc="output file from 3dBandpass",
argstr="-prefix %s",
position=1,
name_source="in_file",
)
lowpass = traits.Float(desc="lowpass", argstr="%f", position=-2, mandatory=True)
highpass = traits.Float(desc="highpass", argstr="%f", position=-3, mandatory=True)
mask = File(desc="mask file", position=2, argstr="-mask %s", exists=True)
despike = traits.Bool(
argstr="-despike",
desc="Despike each time series before other processing. Hopefully, "
"you don't actually need to do this, which is why it is "
"optional.",
)
orthogonalize_file = InputMultiPath(
File(exists=True),
argstr="-ort %s",
desc="Also orthogonalize input to columns in f.1D. Multiple '-ort' "
"options are allowed.",
)
orthogonalize_dset = File(
exists=True,
argstr="-dsort %s",
desc="Orthogonalize each voxel to the corresponding voxel time series "
"in dataset 'fset', which must have the same spatial and "
"temporal grid structure as the main input dataset. At present, "
"only one '-dsort' option is allowed.",
)
no_detrend = traits.Bool(
argstr="-nodetrend",
desc="Skip the quadratic detrending of the input that occurs before "
"the FFT-based bandpassing. You would only want to do this if "
"the dataset had been detrended already in some other program.",
)
tr = traits.Float(
argstr="-dt %f", desc="Set time step (TR) in sec [default=from dataset header]."
)
nfft = traits.Int(
argstr="-nfft %d", desc="Set the FFT length [must be a legal value]."
)
normalize = traits.Bool(
argstr="-norm",
desc="Make all output time series have L2 norm = 1 (i.e., sum of "
"squares = 1).",
)
automask = traits.Bool(
argstr="-automask", desc="Create a mask from the input dataset."
)
blur = traits.Float(
argstr="-blur %f",
desc="Blur (inside the mask only) with a filter width (FWHM) of "
"'fff' millimeters.",
)
localPV = traits.Float(
argstr="-localPV %f",
desc="Replace each vector by the local Principal Vector (AKA first "
"singular vector) from a neighborhood of radius 'rrr' "
"millimeters. Note that the PV time series is L2 normalized. "
"This option is mostly for Bob Cox to have fun with.",
)
notrans = traits.Bool(
argstr="-notrans",
desc="Don't check for initial positive transients in the data. "
"The test is a little slow, so skipping it is OK, if you KNOW "
"the data time series are transient-free.",
)
class Bandpass(AFNICommand):
"""Program to lowpass and/or highpass each voxel time series in a
dataset, offering more/different options than Fourier
For complete details, see the `3dBandpass Documentation.
<https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dBandpass.html>`_
Examples
--------
>>> from nipype.interfaces import afni
>>> from nipype.testing import example_data
>>> bandpass = afni.Bandpass()
>>> bandpass.inputs.in_file = 'functional.nii'
>>> bandpass.inputs.highpass = 0.005
>>> bandpass.inputs.lowpass = 0.1
>>> bandpass.cmdline
'3dBandpass -prefix functional_bp 0.005000 0.100000 functional.nii'
>>> res = bandpass.run() # doctest: +SKIP
"""
_cmd = "3dBandpass"
input_spec = BandpassInputSpec
output_spec = AFNICommandOutputSpec
class BlurInMaskInputSpec(AFNICommandInputSpec):
in_file = File(
desc="input file to 3dSkullStrip",
argstr="-input %s",
position=1,
mandatory=True,
exists=True,
copyfile=False,
)
out_file = File(
name_template="%s_blur",
desc="output to the file",
argstr="-prefix %s",
name_source="in_file",
position=-1,
)
mask = File(
desc="Mask dataset, if desired. Blurring will occur only within the "
"mask. Voxels NOT in the mask will be set to zero in the output.",
argstr="-mask %s",
)
multimask = File(
desc="Multi-mask dataset -- each distinct nonzero value in dataset "
"will be treated as a separate mask for blurring purposes.",
argstr="-Mmask %s",
)
automask = traits.Bool(
desc="Create an automask from the input dataset.", argstr="-automask"
)
fwhm = traits.Float(desc="fwhm kernel size", argstr="-FWHM %f", mandatory=True)
preserve = traits.Bool(
desc="Normally, voxels not in the mask will be set to zero in the "
"output. If you want the original values in the dataset to be "
"preserved in the output, use this option.",
argstr="-preserve",
)
float_out = traits.Bool(
desc="Save dataset as floats, no matter what the input data type is.",
argstr="-float",
)
options = Str(desc="options", argstr="%s", position=2)