/
utils.py
3509 lines (3067 loc) · 115 KB
/
utils.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 utility interfaces."""
import os
import os.path as op
import re
import numpy as np
from ...utils.filemanip import load_json, save_json, split_filename
from ..base import (
CommandLineInputSpec,
CommandLine,
Directory,
TraitedSpec,
traits,
isdefined,
File,
InputMultiObject,
InputMultiPath,
Undefined,
Str,
)
from ...external.due import BibTeX
from .base import (
AFNICommandBase,
AFNICommand,
AFNICommandInputSpec,
AFNICommandOutputSpec,
AFNIPythonCommandInputSpec,
AFNIPythonCommand,
)
class ABoverlapInputSpec(AFNICommandInputSpec):
in_file_a = File(
desc="input file A",
argstr="%s",
position=-3,
mandatory=True,
exists=True,
copyfile=False,
)
in_file_b = File(
desc="input file B",
argstr="%s",
position=-2,
mandatory=True,
exists=True,
copyfile=False,
)
out_file = File(desc="collect output to a file", argstr=" |& tee %s", position=-1)
no_automask = traits.Bool(
desc="consider input datasets as masks", argstr="-no_automask"
)
quiet = traits.Bool(
desc="be as quiet as possible (without being entirely mute)", argstr="-quiet"
)
verb = traits.Bool(
desc="print out some progress reports (to stderr)", argstr="-verb"
)
class ABoverlap(AFNICommand):
"""Output (to screen) is a count of various things about how
the automasks of datasets A and B overlap or don't overlap.
For complete details, see the `3dABoverlap Documentation.
<https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dABoverlap.html>`_
Examples
--------
>>> from nipype.interfaces import afni
>>> aboverlap = afni.ABoverlap()
>>> aboverlap.inputs.in_file_a = 'functional.nii'
>>> aboverlap.inputs.in_file_b = 'structural.nii'
>>> aboverlap.inputs.out_file = 'out.mask_ae_overlap.txt'
>>> aboverlap.cmdline
'3dABoverlap functional.nii structural.nii |& tee out.mask_ae_overlap.txt'
>>> res = aboverlap.run() # doctest: +SKIP
"""
_cmd = "3dABoverlap"
input_spec = ABoverlapInputSpec
output_spec = AFNICommandOutputSpec
class AFNItoNIFTIInputSpec(AFNICommandInputSpec):
in_file = File(
desc="input file to 3dAFNItoNIFTI",
argstr="%s",
position=-1,
mandatory=True,
exists=True,
copyfile=False,
)
out_file = File(
name_template="%s.nii",
desc="output image file name",
argstr="-prefix %s",
name_source="in_file",
hash_files=False,
)
float_ = traits.Bool(
desc="Force the output dataset to be 32-bit floats. This option "
"should be used when the input AFNI dataset has different float "
"scale factors for different sub-bricks, an option that "
"NIfTI-1.1 does not support.",
argstr="-float",
)
pure = traits.Bool(
desc="Do NOT write an AFNI extension field into the output file. Only "
"use this option if needed. You can also use the 'nifti_tool' "
"program to strip extensions from a file.",
argstr="-pure",
)
denote = traits.Bool(
desc="When writing the AFNI extension field, remove text notes that "
"might contain subject identifying information.",
argstr="-denote",
)
oldid = traits.Bool(
desc="Give the new dataset the input dataset" "s AFNI ID code.",
argstr="-oldid",
xor=["newid"],
)
newid = traits.Bool(
desc="Give the new dataset a new AFNI ID code, to distinguish it from "
"the input dataset.",
argstr="-newid",
xor=["oldid"],
)
class AFNItoNIFTI(AFNICommand):
"""Converts AFNI format files to NIFTI format. This can also convert 2D or
1D data, which you can numpy.squeeze() to remove extra dimensions.
For complete details, see the `3dAFNItoNIFTI Documentation.
<https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dAFNItoNIFTI.html>`_
Examples
--------
>>> from nipype.interfaces import afni
>>> a2n = afni.AFNItoNIFTI()
>>> a2n.inputs.in_file = 'afni_output.3D'
>>> a2n.inputs.out_file = 'afni_output.nii'
>>> a2n.cmdline
'3dAFNItoNIFTI -prefix afni_output.nii afni_output.3D'
>>> res = a2n.run() # doctest: +SKIP
"""
_cmd = "3dAFNItoNIFTI"
input_spec = AFNItoNIFTIInputSpec
output_spec = AFNICommandOutputSpec
def _overload_extension(self, value, name=None):
path, base, ext = split_filename(value)
if ext.lower() not in [".nii", ".nii.gz", ".1d", ".1D"]:
ext += ".nii"
return os.path.join(path, base + ext)
def _gen_filename(self, name):
return os.path.abspath(super(AFNItoNIFTI, self)._gen_filename(name))
class AutoboxInputSpec(AFNICommandInputSpec):
in_file = File(
exists=True,
mandatory=True,
argstr="-input %s",
desc="input file",
copyfile=False,
)
padding = traits.Int(
argstr="-npad %d", desc="Number of extra voxels to pad on each side of box"
)
out_file = File(
argstr="-prefix %s", name_source="in_file", name_template="%s_autobox"
)
no_clustering = traits.Bool(
argstr="-noclust",
desc="Don't do any clustering to find box. Any non-zero voxel will "
"be preserved in the cropped volume. The default method uses "
"some clustering to find the cropping box, and will clip off "
"small isolated blobs.",
)
class AutoboxOutputSpec(TraitedSpec): # out_file not mandatory
x_min = traits.Int()
x_max = traits.Int()
y_min = traits.Int()
y_max = traits.Int()
z_min = traits.Int()
z_max = traits.Int()
out_file = File(desc="output file")
class Autobox(AFNICommand):
"""Computes size of a box that fits around the volume.
Also can be used to crop the volume to that box.
For complete details, see the `3dAutobox Documentation.
<https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dAutobox.html>`_
Examples
--------
>>> from nipype.interfaces import afni
>>> abox = afni.Autobox()
>>> abox.inputs.in_file = 'structural.nii'
>>> abox.inputs.padding = 5
>>> abox.cmdline
'3dAutobox -input structural.nii -prefix structural_autobox -npad 5'
>>> res = abox.run() # doctest: +SKIP
"""
_cmd = "3dAutobox"
input_spec = AutoboxInputSpec
output_spec = AutoboxOutputSpec
def aggregate_outputs(self, runtime=None, needed_outputs=None):
outputs = super(Autobox, self).aggregate_outputs(runtime, needed_outputs)
pattern = (
r"x=(?P<x_min>-?\d+)\.\.(?P<x_max>-?\d+) "
r"y=(?P<y_min>-?\d+)\.\.(?P<y_max>-?\d+) "
r"z=(?P<z_min>-?\d+)\.\.(?P<z_max>-?\d+)"
)
for line in runtime.stderr.split("\n"):
m = re.search(pattern, line)
if m:
d = m.groupdict()
outputs.trait_set(**{k: int(d[k]) for k in d.keys()})
return outputs
class BrickStatInputSpec(CommandLineInputSpec):
in_file = File(
desc="input file to 3dmaskave",
argstr="%s",
position=-1,
mandatory=True,
exists=True,
)
mask = File(
desc="-mask dset = use dset as mask to include/exclude voxels",
argstr="-mask %s",
position=2,
exists=True,
)
min = traits.Bool(
desc="print the minimum value in dataset", argstr="-min", position=1
)
slow = traits.Bool(
desc="read the whole dataset to find the min and max values", argstr="-slow"
)
max = traits.Bool(desc="print the maximum value in the dataset", argstr="-max")
mean = traits.Bool(desc="print the mean value in the dataset", argstr="-mean")
sum = traits.Bool(desc="print the sum of values in the dataset", argstr="-sum")
var = traits.Bool(desc="print the variance in the dataset", argstr="-var")
percentile = traits.Tuple(
traits.Float,
traits.Float,
traits.Float,
desc="p0 ps p1 write the percentile values starting "
"at p0% and ending at p1% at a step of ps%. "
"only one sub-brick is accepted.",
argstr="-percentile %.3f %.3f %.3f",
)
class BrickStatOutputSpec(TraitedSpec):
min_val = traits.Float(desc="output")
class BrickStat(AFNICommandBase):
"""Computes maximum and/or minimum voxel values of an input dataset.
TODO Add optional arguments.
For complete details, see the `3dBrickStat Documentation.
<https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dBrickStat.html>`_
Examples
--------
>>> from nipype.interfaces import afni
>>> brickstat = afni.BrickStat()
>>> brickstat.inputs.in_file = 'functional.nii'
>>> brickstat.inputs.mask = 'skeleton_mask.nii.gz'
>>> brickstat.inputs.min = True
>>> brickstat.cmdline
'3dBrickStat -min -mask skeleton_mask.nii.gz functional.nii'
>>> res = brickstat.run() # doctest: +SKIP
"""
_cmd = "3dBrickStat"
input_spec = BrickStatInputSpec
output_spec = BrickStatOutputSpec
def aggregate_outputs(self, runtime=None, needed_outputs=None):
outputs = self._outputs()
outfile = os.path.join(os.getcwd(), "stat_result.json")
if runtime is None:
try:
min_val = load_json(outfile)["stat"]
except IOError:
return self.run().outputs
else:
min_val = []
for line in runtime.stdout.split("\n"):
if line:
values = line.split()
if len(values) > 1:
min_val.append([float(val) for val in values])
else:
min_val.extend([float(val) for val in values])
if len(min_val) == 1:
min_val = min_val[0]
save_json(outfile, dict(stat=min_val))
outputs.min_val = min_val
return outputs
class BucketInputSpec(AFNICommandInputSpec):
in_file = traits.List(
traits.Tuple(
(File(exists=True, copyfile=False), traits.Str(argstr="'%s'")),
artstr="%s%s",
),
position=-1,
mandatory=True,
argstr="%s",
desc="""\
List of tuples of input datasets and subbrick selection strings
as described in more detail in the following afni help string
Input dataset specified using one of these forms:
``prefix+view``, ``prefix+view.HEAD``, or ``prefix+view.BRIK``.
You can also add a sub-brick selection list after the end of the
dataset name. This allows only a subset of the sub-bricks to be
included into the output (by default, all of the input dataset
is copied into the output). A sub-brick selection list looks like
one of the following forms::
fred+orig[5] ==> use only sub-brick #5
fred+orig[5,9,17] ==> use #5, #9, and #17
fred+orig[5..8] or [5-8] ==> use #5, #6, #7, and #8
fred+orig[5..13(2)] or [5-13(2)] ==> use #5, #7, #9, #11, and #13
Sub-brick indexes start at 0. You can use the character '$'
to indicate the last sub-brick in a dataset; for example, you
can select every third sub-brick by using the selection list
``fred+orig[0..$(3)]``
N.B.: The sub-bricks are output in the order specified, which may
not be the order in the original datasets. For example, using
``fred+orig[0..$(2),1..$(2)]``
will cause the sub-bricks in fred+orig to be output into the
new dataset in an interleaved fashion. Using ``fred+orig[$..0]``
will reverse the order of the sub-bricks in the output.
N.B.: Bucket datasets have multiple sub-bricks, but do NOT have
a time dimension. You can input sub-bricks from a 3D+time dataset
into a bucket dataset. You can use the '3dinfo' program to see
how many sub-bricks a 3D+time or a bucket dataset contains.
N.B.: In non-bucket functional datasets (like the 'fico' datasets
output by FIM, or the 'fitt' datasets output by 3dttest), sub-brick
``[0]`` is the 'intensity' and sub-brick [1] is the statistical parameter
used as a threshold. Thus, to create a bucket dataset using the
intensity from dataset A and the threshold from dataset B, and
calling the output dataset C, you would type::
3dbucket -prefix C -fbuc 'A+orig[0]' -fbuc 'B+orig[1]
""",
)
out_file = File(argstr="-prefix %s", name_template="buck")
class Bucket(AFNICommand):
"""Concatenate sub-bricks from input datasets into one big
'bucket' dataset.
.. danger::
Using this program, it is possible to create a dataset that
has different basic datum types for different sub-bricks
(e.g., shorts for brick 0, floats for brick 1).
Do NOT do this! Very few AFNI programs will work correctly
with such datasets!
Examples
--------
>>> from nipype.interfaces import afni
>>> bucket = afni.Bucket()
>>> bucket.inputs.in_file = [('functional.nii',"{2..$}"), ('functional.nii',"{1}")]
>>> bucket.inputs.out_file = 'vr_base'
>>> bucket.cmdline
"3dbucket -prefix vr_base functional.nii'{2..$}' functional.nii'{1}'"
>>> res = bucket.run() # doctest: +SKIP
See Also
--------
For complete details, see the `3dbucket Documentation.
<https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dbucket.html>`__.
"""
_cmd = "3dbucket"
input_spec = BucketInputSpec
output_spec = AFNICommandOutputSpec
def _format_arg(self, name, spec, value):
if name == "in_file":
return spec.argstr % (" ".join([i[0] + "'" + i[1] + "'" for i in value]))
return super(Bucket, self)._format_arg(name, spec, value)
class CalcInputSpec(AFNICommandInputSpec):
in_file_a = File(
desc="input file to 3dcalc",
argstr="-a %s",
position=0,
mandatory=True,
exists=True,
)
in_file_b = File(
desc="operand file to 3dcalc", argstr="-b %s", position=1, exists=True
)
in_file_c = File(
desc="operand file to 3dcalc", argstr="-c %s", position=2, exists=True
)
out_file = File(
name_template="%s_calc",
desc="output image file name",
argstr="-prefix %s",
name_source="in_file_a",
)
expr = Str(desc="expr", argstr='-expr "%s"', position=3, mandatory=True)
start_idx = traits.Int(desc="start index for in_file_a", requires=["stop_idx"])
stop_idx = traits.Int(desc="stop index for in_file_a", requires=["start_idx"])
single_idx = traits.Int(desc="volume index for in_file_a")
overwrite = traits.Bool(desc="overwrite output", argstr="-overwrite")
other = File(desc="other options", argstr="")
class Calc(AFNICommand):
"""This program does voxel-by-voxel arithmetic on 3D datasets.
For complete details, see the `3dcalc Documentation.
<https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dcalc.html>`_
Examples
--------
>>> from nipype.interfaces import afni
>>> calc = afni.Calc()
>>> calc.inputs.in_file_a = 'functional.nii'
>>> calc.inputs.in_file_b = 'functional2.nii'
>>> calc.inputs.expr='a*b'
>>> calc.inputs.out_file = 'functional_calc.nii.gz'
>>> calc.inputs.outputtype = 'NIFTI'
>>> calc.cmdline # doctest: +ELLIPSIS
'3dcalc -a functional.nii -b functional2.nii -expr "a*b" -prefix functional_calc.nii.gz'
>>> res = calc.run() # doctest: +SKIP
>>> from nipype.interfaces import afni
>>> calc = afni.Calc()
>>> calc.inputs.in_file_a = 'functional.nii'
>>> calc.inputs.expr = '1'
>>> calc.inputs.out_file = 'rm.epi.all1'
>>> calc.inputs.overwrite = True
>>> calc.cmdline
'3dcalc -a functional.nii -expr "1" -prefix rm.epi.all1 -overwrite'
>>> res = calc.run() # doctest: +SKIP
"""
_cmd = "3dcalc"
input_spec = CalcInputSpec
output_spec = AFNICommandOutputSpec
def _format_arg(self, name, trait_spec, value):
if name == "in_file_a":
arg = trait_spec.argstr % value
if isdefined(self.inputs.start_idx):
arg += "[%d..%d]" % (self.inputs.start_idx, self.inputs.stop_idx)
if isdefined(self.inputs.single_idx):
arg += "[%d]" % (self.inputs.single_idx)
return arg
return super(Calc, self)._format_arg(name, trait_spec, value)
def _parse_inputs(self, skip=None):
"""Skip the arguments without argstr metadata
"""
return super(Calc, self)._parse_inputs(skip=("start_idx", "stop_idx", "other"))
class CatInputSpec(AFNICommandInputSpec):
in_files = traits.List(File(exists=True), argstr="%s", mandatory=True, position=-2)
out_file = File(
argstr="> %s",
value="catout.1d",
usedefault=True,
desc="output (concatenated) file name",
position=-1,
mandatory=True,
)
omitconst = traits.Bool(
desc="Omit columns that are identically constant from output.",
argstr="-nonconst",
)
keepfree = traits.Bool(
desc="Keep only columns that are marked as 'free' in the "
"3dAllineate header from '-1Dparam_save'. "
"If there is no such header, all columns are kept.",
argstr="-nonfixed",
)
out_format = traits.Enum(
"int",
"nice",
"double",
"fint",
"cint",
argstr="-form %s",
desc="specify data type for output.",
xor=["out_int", "out_nice", "out_double", "out_fint", "out_cint"],
)
stack = traits.Bool(
desc="Stack the columns of the resultant matrix in the output.", argstr="-stack"
)
sel = traits.Str(
desc="Apply the same column/row selection string to all filenames "
"on the command line.",
argstr="-sel %s",
)
out_int = traits.Bool(
desc="specifiy int data type for output",
argstr="-i",
xor=["out_format", "out_nice", "out_double", "out_fint", "out_cint"],
)
out_nice = traits.Bool(
desc="specifiy nice data type for output",
argstr="-n",
xor=["out_format", "out_int", "out_double", "out_fint", "out_cint"],
)
out_double = traits.Bool(
desc="specifiy double data type for output",
argstr="-d",
xor=["out_format", "out_nice", "out_int", "out_fint", "out_cint"],
)
out_fint = traits.Bool(
desc="specifiy int, rounded down, data type for output",
argstr="-f",
xor=["out_format", "out_nice", "out_double", "out_int", "out_cint"],
)
out_cint = traits.Bool(
desc="specifiy int, rounded up, data type for output",
xor=["out_format", "out_nice", "out_double", "out_fint", "out_int"],
)
class Cat(AFNICommand):
"""1dcat takes as input one or more 1D files, and writes out a 1D file
containing the side-by-side concatenation of all or a subset of the
columns from the input files.
For complete details, see the `1dcat Documentation.
<https://afni.nimh.nih.gov/pub/dist/doc/program_help/1dcat.html>`_
Examples
--------
>>> from nipype.interfaces import afni
>>> cat1d = afni.Cat()
>>> cat1d.inputs.sel = "'[0,2]'"
>>> cat1d.inputs.in_files = ['f1.1D', 'f2.1D']
>>> cat1d.inputs.out_file = 'catout.1d'
>>> cat1d.cmdline
"1dcat -sel '[0,2]' f1.1D f2.1D > catout.1d"
>>> res = cat1d.run() # doctest: +SKIP
"""
_cmd = "1dcat"
input_spec = CatInputSpec
output_spec = AFNICommandOutputSpec
class CatMatvecInputSpec(AFNICommandInputSpec):
in_file = traits.List(
traits.Tuple(traits.Str(), traits.Str()),
desc="list of tuples of mfiles and associated opkeys",
mandatory=True,
argstr="%s",
position=-2,
)
out_file = File(
argstr=" > %s",
name_template="%s_cat.aff12.1D",
name_source="in_file",
keep_extension=False,
desc="File to write concattenated matvecs to",
position=-1,
mandatory=True,
)
matrix = traits.Bool(
desc="indicates that the resulting matrix will"
"be written to outfile in the 'MATRIX(...)' format (FORM 3)."
"This feature could be used, with clever scripting, to input"
"a matrix directly on the command line to program 3dWarp.",
argstr="-MATRIX",
xor=["oneline", "fourxfour"],
)
oneline = traits.Bool(
desc="indicates that the resulting matrix"
"will simply be written as 12 numbers on one line.",
argstr="-ONELINE",
xor=["matrix", "fourxfour"],
)
fourxfour = traits.Bool(
desc="Output matrix in augmented form (last row is 0 0 0 1)"
"This option does not work with -MATRIX or -ONELINE",
argstr="-4x4",
xor=["matrix", "oneline"],
)
class CatMatvec(AFNICommand):
"""Catenates 3D rotation+shift matrix+vector transformations.
For complete details, see the `cat_matvec Documentation.
<https://afni.nimh.nih.gov/pub/dist/doc/program_help/cat_matvec.html>`_
Examples
--------
>>> from nipype.interfaces import afni
>>> cmv = afni.CatMatvec()
>>> cmv.inputs.in_file = [('structural.BRIK::WARP_DATA','I')]
>>> cmv.inputs.out_file = 'warp.anat.Xat.1D'
>>> cmv.cmdline
'cat_matvec structural.BRIK::WARP_DATA -I > warp.anat.Xat.1D'
>>> res = cmv.run() # doctest: +SKIP
"""
_cmd = "cat_matvec"
input_spec = CatMatvecInputSpec
output_spec = AFNICommandOutputSpec
def _format_arg(self, name, spec, value):
if name == "in_file":
# Concatenate a series of filenames, with optional opkeys
return " ".join(
"%s -%s" % (mfile, opkey) if opkey else mfile for mfile, opkey in value
)
return super(CatMatvec, self)._format_arg(name, spec, value)
class CenterMassInputSpec(CommandLineInputSpec):
in_file = File(
desc="input file to 3dCM",
argstr="%s",
position=-2,
mandatory=True,
exists=True,
copyfile=True,
)
cm_file = File(
name_source="in_file",
name_template="%s_cm.out",
hash_files=False,
keep_extension=False,
desc="File to write center of mass to",
argstr="> %s",
position=-1,
)
mask_file = File(
desc="Only voxels with nonzero values in the provided mask will be "
"averaged.",
argstr="-mask %s",
exists=True,
)
automask = traits.Bool(desc="Generate the mask automatically", argstr="-automask")
set_cm = traits.Tuple(
(traits.Float(), traits.Float(), traits.Float()),
desc="After computing the center of mass, set the origin fields in "
"the header so that the center of mass will be at (x,y,z) in "
"DICOM coords.",
argstr="-set %f %f %f",
)
local_ijk = traits.Bool(
desc="Output values as (i,j,k) in local orienation", argstr="-local_ijk"
)
roi_vals = traits.List(
traits.Int,
desc="Compute center of mass for each blob with voxel value of v0, "
"v1, v2, etc. This option is handy for getting ROI centers of "
"mass.",
argstr="-roi_vals %s",
)
all_rois = traits.Bool(
desc="Don't bother listing the values of ROIs you want: The program "
"will find all of them and produce a full list",
argstr="-all_rois",
)
class CenterMassOutputSpec(TraitedSpec):
out_file = File(exists=True, desc="output file")
cm_file = File(desc="file with the center of mass coordinates")
cm = traits.List(
traits.Tuple(traits.Float(), traits.Float(), traits.Float()),
desc="center of mass",
)
class CenterMass(AFNICommandBase):
"""Computes center of mass using 3dCM command
.. note::
By default, the output is (x,y,z) values in DICOM coordinates. But
as of Dec, 2016, there are now command line switches for other options.
For complete details, see the `3dCM Documentation.
<https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dCM.html>`_
Examples
--------
>>> from nipype.interfaces import afni
>>> cm = afni.CenterMass()
>>> cm.inputs.in_file = 'structural.nii'
>>> cm.inputs.cm_file = 'cm.txt'
>>> cm.inputs.roi_vals = [2, 10]
>>> cm.cmdline
'3dCM -roi_vals 2 10 structural.nii > cm.txt'
>>> res = 3dcm.run() # doctest: +SKIP
"""
_cmd = "3dCM"
input_spec = CenterMassInputSpec
output_spec = CenterMassOutputSpec
def _list_outputs(self):
outputs = super(CenterMass, self)._list_outputs()
outputs["out_file"] = os.path.abspath(self.inputs.in_file)
outputs["cm_file"] = os.path.abspath(self.inputs.cm_file)
sout = np.loadtxt(outputs["cm_file"], ndmin=2)
outputs["cm"] = [tuple(s) for s in sout]
return outputs
class ConvertDsetInputSpec(AFNICommandInputSpec):
in_file = File(
desc="input file to ConvertDset",
argstr="-input %s",
position=-2,
mandatory=True,
exists=True,
)
out_file = File(
desc="output file for ConvertDset",
argstr="-prefix %s",
position=-1,
mandatory=True,
)
out_type = traits.Enum(
(
"niml",
"niml_asc",
"niml_bi",
"1D",
"1Dp",
"1Dpt",
"gii",
"gii_asc",
"gii_b64",
"gii_b64gz",
),
desc="output type",
argstr="-o_%s",
mandatory=True,
position=0,
)
class ConvertDset(AFNICommandBase):
"""Converts a surface dataset from one format to another.
For complete details, see the `ConvertDset Documentation.
<https://afni.nimh.nih.gov/pub/dist/doc/program_help/ConvertDset.html>`_
Examples
--------
>>> from nipype.interfaces import afni
>>> convertdset = afni.ConvertDset()
>>> convertdset.inputs.in_file = 'lh.pial_converted.gii'
>>> convertdset.inputs.out_type = 'niml_asc'
>>> convertdset.inputs.out_file = 'lh.pial_converted.niml.dset'
>>> convertdset.cmdline
'ConvertDset -o_niml_asc -input lh.pial_converted.gii -prefix lh.pial_converted.niml.dset'
>>> res = convertdset.run() # doctest: +SKIP
"""
_cmd = "ConvertDset"
input_spec = ConvertDsetInputSpec
output_spec = AFNICommandOutputSpec
def _list_outputs(self):
outputs = self.output_spec().get()
outputs["out_file"] = op.abspath(self.inputs.out_file)
return outputs
class CopyInputSpec(AFNICommandInputSpec):
in_file = File(
desc="input file to 3dcopy",
argstr="%s",
position=-2,
mandatory=True,
exists=True,
copyfile=False,
)
out_file = File(
name_template="%s_copy",
desc="output image file name",
argstr="%s",
position=-1,
name_source="in_file",
)
verbose = traits.Bool(desc="print progress reports", argstr="-verb")
class Copy(AFNICommand):
"""Copies an image of one type to an image of the same
or different type using 3dcopy command
For complete details, see the `3dcopy Documentation.
<https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dcopy.html>`__
Examples
--------
>>> from nipype.interfaces import afni
>>> copy3d = afni.Copy()
>>> copy3d.inputs.in_file = 'functional.nii'
>>> copy3d.cmdline
'3dcopy functional.nii functional_copy'
>>> res = copy3d.run() # doctest: +SKIP
>>> from copy import deepcopy
>>> copy3d_2 = deepcopy(copy3d)
>>> copy3d_2.inputs.outputtype = 'NIFTI'
>>> copy3d_2.cmdline
'3dcopy functional.nii functional_copy.nii'
>>> res = copy3d_2.run() # doctest: +SKIP
>>> copy3d_3 = deepcopy(copy3d)
>>> copy3d_3.inputs.outputtype = 'NIFTI_GZ'
>>> copy3d_3.cmdline
'3dcopy functional.nii functional_copy.nii.gz'
>>> res = copy3d_3.run() # doctest: +SKIP
>>> copy3d_4 = deepcopy(copy3d)
>>> copy3d_4.inputs.out_file = 'new_func.nii'
>>> copy3d_4.cmdline
'3dcopy functional.nii new_func.nii'
>>> res = copy3d_4.run() # doctest: +SKIP
"""
_cmd = "3dcopy"
input_spec = CopyInputSpec
output_spec = AFNICommandOutputSpec
class DotInputSpec(AFNICommandInputSpec):
in_files = traits.List(
(File()),
desc="list of input files, possibly with subbrick selectors",
argstr="%s ...",
position=-2,
)
out_file = File(desc="collect output to a file", argstr=" |& tee %s", position=-1)
mask = File(desc="Use this dataset as a mask", argstr="-mask %s")
mrange = traits.Tuple(
(traits.Float(), traits.Float()),
desc="Means to further restrict the voxels from 'mset' so that"
"only those mask values within this range (inclusive) willbe used.",
argstr="-mrange %s %s",
)
demean = traits.Bool(
desc="Remove the mean from each volume prior to computing the correlation",
argstr="-demean",
)
docor = traits.Bool(
desc="Return the correlation coefficient (default).", argstr="-docor"
)
dodot = traits.Bool(desc="Return the dot product (unscaled).", argstr="-dodot")
docoef = traits.Bool(
desc="Return the least square fit coefficients {{a,b}} so that dset2 is approximately a + b\\*dset1",
argstr="-docoef",
)
dosums = traits.Bool(
desc="Return the 6 numbers xbar=<x> ybar=<y> <(x-xbar)^2> <(y-ybar)^2> <(x-xbar)(y-ybar)> and the correlation coefficient.",
argstr="-dosums",
)
dodice = traits.Bool(
desc="Return the Dice coefficient (the Sorensen-Dice index).", argstr="-dodice"
)
doeta2 = traits.Bool(
desc="Return eta-squared (Cohen, NeuroImage 2008).", argstr="-doeta2"
)
full = traits.Bool(
desc="Compute the whole matrix. A waste of time, but handy for parsing.",
argstr="-full",
)
show_labels = traits.Bool(
desc="Print sub-brick labels to help identify what is being correlated. This option is useful when"
"you have more than 2 sub-bricks at input.",
argstr="-show_labels",
)
upper = traits.Bool(desc="Compute upper triangular matrix", argstr="-upper")
class Dot(AFNICommand):
"""Correlation coefficient between sub-brick pairs.
All datasets in in_files list will be concatenated.
You can use sub-brick selectors in the file specification.
.. warning::
This program is not efficient when more than two subbricks are input.
For complete details, see the `3ddot Documentation.
<https://afni.nimh.nih.gov/pub/dist/doc/program_help/3ddot.html>`_
>>> from nipype.interfaces import afni
>>> dot = afni.Dot()
>>> dot.inputs.in_files = ['functional.nii[0]', 'structural.nii']
>>> dot.inputs.dodice = True
>>> dot.inputs.out_file = 'out.mask_ae_dice.txt'
>>> dot.cmdline
'3dDot -dodice functional.nii[0] structural.nii |& tee out.mask_ae_dice.txt'
>>> res = copy3d.run() # doctest: +SKIP
"""
_cmd = "3dDot"
input_spec = DotInputSpec
output_spec = AFNICommandOutputSpec
class Edge3InputSpec(AFNICommandInputSpec):
in_file = File(
desc="input file to 3dedge3",
argstr="-input %s",
position=0,
mandatory=True,
exists=True,
copyfile=False,
)
out_file = File(desc="output image file name", position=-1, argstr="-prefix %s")
datum = traits.Enum(
"byte",
"short",
"float",
argstr="-datum %s",
desc="specify data type for output. Valid types are 'byte', "
"'short' and 'float'.",
)
fscale = traits.Bool(
desc="Force scaling of the output to the maximum integer range.",
argstr="-fscale",
xor=["gscale", "nscale", "scale_floats"],
)
gscale = traits.Bool(
desc="Same as '-fscale', but also forces each output sub-brick to "
"to get the same scaling factor.",
argstr="-gscale",
xor=["fscale", "nscale", "scale_floats"],
)
nscale = traits.Bool(
desc="Don't do any scaling on output to byte or short datasets.",
argstr="-nscale",
xor=["fscale", "gscale", "scale_floats"],
)
scale_floats = traits.Float(
desc="Multiply input by VAL, but only if the input datum is "
"float. This is needed when the input dataset "
"has a small range, like 0 to 2.0 for instance. "