/
utils.py
2836 lines (2365 loc) · 86.2 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:
"""The fsl module provides classes for interfacing with the `FSL
<http://www.fmrib.ox.ac.uk/fsl/index.html>`_ command line tools. This
was written to work with FSL version 4.1.4.
Examples
--------
See the docstrings of the individual classes for examples.
"""
import os
import os.path as op
import re
from glob import glob
import tempfile
import numpy as np
from ...utils.filemanip import load_json, save_json, split_filename, fname_presuffix
from ..base import (
traits,
TraitedSpec,
OutputMultiPath,
File,
CommandLine,
CommandLineInputSpec,
isdefined,
)
from .base import FSLCommand, FSLCommandInputSpec, Info
class CopyGeomInputSpec(FSLCommandInputSpec):
in_file = File(
exists=True, mandatory=True, argstr="%s", position=0, desc="source image"
)
dest_file = File(
exists=True,
mandatory=True,
argstr="%s",
position=1,
desc="destination image",
copyfile=True,
output_name="out_file",
name_source="dest_file",
name_template="%s",
)
ignore_dims = traits.Bool(
desc="Do not copy image dimensions", argstr="-d", position="-1"
)
class CopyGeomOutputSpec(TraitedSpec):
out_file = File(exists=True, desc="image with new geometry header")
class CopyGeom(FSLCommand):
"""Use fslcpgeom to copy the header geometry information to another image.
Copy certain parts of the header information (image dimensions, voxel
dimensions, voxel dimensions units string, image orientation/origin or
qform/sform info) from one image to another. Note that only copies from
Analyze to Analyze or Nifti to Nifti will work properly. Copying from
different files will result in loss of information or potentially incorrect
settings.
"""
_cmd = "fslcpgeom"
input_spec = CopyGeomInputSpec
output_spec = CopyGeomOutputSpec
class RobustFOVInputSpec(FSLCommandInputSpec):
in_file = File(
exists=True, desc="input filename", argstr="-i %s", position=0, mandatory=True
)
out_roi = File(
desc="ROI volume output name",
argstr="-r %s",
name_source=["in_file"],
hash_files=False,
name_template="%s_ROI",
)
brainsize = traits.Int(
desc=("size of brain in z-dimension (default " "170mm/150mm)"), argstr="-b %d"
)
out_transform = File(
desc=("Transformation matrix in_file to out_roi " "output name"),
argstr="-m %s",
name_source=["in_file"],
hash_files=False,
name_template="%s_to_ROI",
)
class RobustFOVOutputSpec(TraitedSpec):
out_roi = File(exists=True, desc="ROI volume output name")
out_transform = File(
exists=True, desc=("Transformation matrix in_file to out_roi " "output name")
)
class RobustFOV(FSLCommand):
"""Automatically crops an image removing lower head and neck.
Interface is stable 5.0.0 to 5.0.9, but default brainsize changed from
150mm to 170mm.
"""
_cmd = "robustfov"
input_spec = RobustFOVInputSpec
output_spec = RobustFOVOutputSpec
class ImageMeantsInputSpec(FSLCommandInputSpec):
in_file = File(
exists=True,
desc="input file for computing the average timeseries",
argstr="-i %s",
position=0,
mandatory=True,
)
out_file = File(
desc="name of output text matrix",
argstr="-o %s",
genfile=True,
hash_files=False,
)
mask = File(exists=True, desc="input 3D mask", argstr="-m %s")
spatial_coord = traits.List(
traits.Int,
desc=("<x y z> requested spatial coordinate " "(instead of mask)"),
argstr="-c %s",
)
use_mm = traits.Bool(
desc=("use mm instead of voxel coordinates (for -c " "option)"),
argstr="--usemm",
)
show_all = traits.Bool(
desc=("show all voxel time series (within mask) " "instead of averaging"),
argstr="--showall",
)
eig = traits.Bool(
desc=("calculate Eigenvariate(s) instead of mean (output will have 0 " "mean)"),
argstr="--eig",
)
order = traits.Int(
1, desc="select number of Eigenvariates", argstr="--order=%d", usedefault=True
)
nobin = traits.Bool(
desc=("do not binarise the mask for calculation of " "Eigenvariates"),
argstr="--no_bin",
)
transpose = traits.Bool(
desc=("output results in transpose format (one row per voxel/mean)"),
argstr="--transpose",
)
class ImageMeantsOutputSpec(TraitedSpec):
out_file = File(exists=True, desc="path/name of output text matrix")
class ImageMeants(FSLCommand):
""" Use fslmeants for printing the average timeseries (intensities) to
the screen (or saves to a file). The average is taken over all voxels
in the mask (or all voxels in the image if no mask is specified)
"""
_cmd = "fslmeants"
input_spec = ImageMeantsInputSpec
output_spec = ImageMeantsOutputSpec
def _list_outputs(self):
outputs = self.output_spec().get()
outputs["out_file"] = self.inputs.out_file
if not isdefined(outputs["out_file"]):
outputs["out_file"] = self._gen_fname(
self.inputs.in_file, suffix="_ts", ext=".txt", change_ext=True
)
outputs["out_file"] = os.path.abspath(outputs["out_file"])
return outputs
def _gen_filename(self, name):
if name == "out_file":
return self._list_outputs()[name]
return None
class SmoothInputSpec(FSLCommandInputSpec):
in_file = File(exists=True, argstr="%s", position=0, mandatory=True)
sigma = traits.Float(
argstr="-kernel gauss %.03f -fmean",
position=1,
xor=["fwhm"],
mandatory=True,
desc="gaussian kernel sigma in mm (not voxels)",
)
fwhm = traits.Float(
argstr="-kernel gauss %.03f -fmean",
position=1,
xor=["sigma"],
mandatory=True,
desc=("gaussian kernel fwhm, will be converted to sigma in mm " "(not voxels)"),
)
smoothed_file = File(
argstr="%s",
position=2,
name_source=["in_file"],
name_template="%s_smooth",
hash_files=False,
)
class SmoothOutputSpec(TraitedSpec):
smoothed_file = File(exists=True)
class Smooth(FSLCommand):
"""
Use fslmaths to smooth the image
Examples
--------
Setting the kernel width using sigma:
>>> sm = Smooth()
>>> sm.inputs.output_type = 'NIFTI_GZ'
>>> sm.inputs.in_file = 'functional2.nii'
>>> sm.inputs.sigma = 8.0
>>> sm.cmdline # doctest: +ELLIPSIS
'fslmaths functional2.nii -kernel gauss 8.000 -fmean functional2_smooth.nii.gz'
Setting the kernel width using fwhm:
>>> sm = Smooth()
>>> sm.inputs.output_type = 'NIFTI_GZ'
>>> sm.inputs.in_file = 'functional2.nii'
>>> sm.inputs.fwhm = 8.0
>>> sm.cmdline # doctest: +ELLIPSIS
'fslmaths functional2.nii -kernel gauss 3.397 -fmean functional2_smooth.nii.gz'
One of sigma or fwhm must be set:
>>> from nipype.interfaces.fsl import Smooth
>>> sm = Smooth()
>>> sm.inputs.output_type = 'NIFTI_GZ'
>>> sm.inputs.in_file = 'functional2.nii'
>>> sm.cmdline #doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Smooth requires a value for one of the inputs ...
"""
input_spec = SmoothInputSpec
output_spec = SmoothOutputSpec
_cmd = "fslmaths"
def _format_arg(self, name, trait_spec, value):
if name == "fwhm":
sigma = float(value) / np.sqrt(8 * np.log(2))
return super(Smooth, self)._format_arg(name, trait_spec, sigma)
return super(Smooth, self)._format_arg(name, trait_spec, value)
class SliceInputSpec(FSLCommandInputSpec):
in_file = File(
exists=True,
argstr="%s",
position=0,
mandatory=True,
desc="input filename",
copyfile=False,
)
out_base_name = traits.Str(argstr="%s", position=1, desc="outputs prefix")
class SliceOutputSpec(TraitedSpec):
out_files = OutputMultiPath(File(exists=True))
class Slice(FSLCommand):
"""Use fslslice to split a 3D file into lots of 2D files (along z-axis).
Examples
--------
>>> from nipype.interfaces.fsl import Slice
>>> slice = Slice()
>>> slice.inputs.in_file = 'functional.nii'
>>> slice.inputs.out_base_name = 'sl'
>>> slice.cmdline
'fslslice functional.nii sl'
"""
_cmd = "fslslice"
input_spec = SliceInputSpec
output_spec = SliceOutputSpec
def _list_outputs(self):
"""Create a Bunch which contains all possible files generated
by running the interface. Some files are always generated, others
depending on which ``inputs`` options are set.
Returns
-------
outputs : Bunch object
Bunch object containing all possible files generated by
interface object.
If None, file was not generated
Else, contains path, filename of generated outputfile
"""
outputs = self._outputs().get()
ext = Info.output_type_to_ext(self.inputs.output_type)
suffix = "_slice_*" + ext
if isdefined(self.inputs.out_base_name):
fname_template = os.path.abspath(self.inputs.out_base_name + suffix)
else:
fname_template = fname_presuffix(
self.inputs.in_file, suffix=suffix, use_ext=False
)
outputs["out_files"] = sorted(glob(fname_template))
return outputs
class MergeInputSpec(FSLCommandInputSpec):
in_files = traits.List(File(exists=True), argstr="%s", position=2, mandatory=True)
dimension = traits.Enum(
"t",
"x",
"y",
"z",
"a",
argstr="-%s",
position=0,
desc=(
"dimension along which to merge, optionally "
"set tr input when dimension is t"
),
mandatory=True,
)
tr = traits.Float(
position=-1,
argstr="%.2f",
desc=(
"use to specify TR in seconds (default is 1.00 "
"sec), overrides dimension and sets it to tr"
),
)
merged_file = File(
argstr="%s",
position=1,
name_source="in_files",
name_template="%s_merged",
hash_files=False,
)
class MergeOutputSpec(TraitedSpec):
merged_file = File(exists=True)
class Merge(FSLCommand):
"""Use fslmerge to concatenate images
Images can be concatenated across time, x, y, or z dimensions. Across the
time (t) dimension the TR is set by default to 1 sec.
Note: to set the TR to a different value, specify 't' for dimension and
specify the TR value in seconds for the tr input. The dimension will be
automatically updated to 'tr'.
Examples
--------
>>> from nipype.interfaces.fsl import Merge
>>> merger = Merge()
>>> merger.inputs.in_files = ['functional2.nii', 'functional3.nii']
>>> merger.inputs.dimension = 't'
>>> merger.inputs.output_type = 'NIFTI_GZ'
>>> merger.cmdline
'fslmerge -t functional2_merged.nii.gz functional2.nii functional3.nii'
>>> merger.inputs.tr = 2.25
>>> merger.cmdline
'fslmerge -tr functional2_merged.nii.gz functional2.nii functional3.nii 2.25'
"""
_cmd = "fslmerge"
input_spec = MergeInputSpec
output_spec = MergeOutputSpec
def _format_arg(self, name, spec, value):
if name == "tr":
if self.inputs.dimension != "t":
raise ValueError("When TR is specified, dimension must be t")
return spec.argstr % value
if name == "dimension":
if isdefined(self.inputs.tr):
return "-tr"
return spec.argstr % value
return super(Merge, self)._format_arg(name, spec, value)
class ExtractROIInputSpec(FSLCommandInputSpec):
in_file = File(
exists=True, argstr="%s", position=0, desc="input file", mandatory=True
)
roi_file = File(
argstr="%s", position=1, desc="output file", genfile=True, hash_files=False
)
x_min = traits.Int(argstr="%d", position=2)
x_size = traits.Int(argstr="%d", position=3)
y_min = traits.Int(argstr="%d", position=4)
y_size = traits.Int(argstr="%d", position=5)
z_min = traits.Int(argstr="%d", position=6)
z_size = traits.Int(argstr="%d", position=7)
t_min = traits.Int(argstr="%d", position=8)
t_size = traits.Int(argstr="%d", position=9)
_crop_xor = [
"x_min",
"x_size",
"y_min",
"y_size",
"z_min",
"z_size",
"t_min",
"t_size",
]
crop_list = traits.List(
traits.Tuple(traits.Int, traits.Int),
argstr="%s",
position=2,
xor=_crop_xor,
desc="list of two tuples specifying crop options",
)
class ExtractROIOutputSpec(TraitedSpec):
roi_file = File(exists=True)
class ExtractROI(FSLCommand):
"""Uses FSL Fslroi command to extract region of interest (ROI)
from an image.
You can a) take a 3D ROI from a 3D data set (or if it is 4D, the
same ROI is taken from each time point and a new 4D data set is
created), b) extract just some time points from a 4D data set, or
c) control time and space limits to the ROI. Note that the
arguments are minimum index and size (not maximum index). So to
extract voxels 10 to 12 inclusive you would specify 10 and 3 (not
10 and 12).
Examples
--------
>>> from nipype.interfaces.fsl import ExtractROI
>>> from nipype.testing import anatfile
>>> fslroi = ExtractROI(in_file=anatfile, roi_file='bar.nii', t_min=0,
... t_size=1)
>>> fslroi.cmdline == 'fslroi %s bar.nii 0 1' % anatfile
True
"""
_cmd = "fslroi"
input_spec = ExtractROIInputSpec
output_spec = ExtractROIOutputSpec
def _format_arg(self, name, spec, value):
if name == "crop_list":
return " ".join(map(str, sum(list(map(list, value)), [])))
return super(ExtractROI, self)._format_arg(name, spec, value)
def _list_outputs(self):
"""Create a Bunch which contains all possible files generated
by running the interface. Some files are always generated, others
depending on which ``inputs`` options are set.
Returns
-------
outputs : Bunch object
Bunch object containing all possible files generated by
interface object.
If None, file was not generated
Else, contains path, filename of generated outputfile
"""
outputs = self._outputs().get()
outputs["roi_file"] = self.inputs.roi_file
if not isdefined(outputs["roi_file"]):
outputs["roi_file"] = self._gen_fname(self.inputs.in_file, suffix="_roi")
outputs["roi_file"] = os.path.abspath(outputs["roi_file"])
return outputs
def _gen_filename(self, name):
if name == "roi_file":
return self._list_outputs()[name]
return None
class SplitInputSpec(FSLCommandInputSpec):
in_file = File(
exists=True, argstr="%s", position=0, mandatory=True, desc="input filename"
)
out_base_name = traits.Str(argstr="%s", position=1, desc="outputs prefix")
dimension = traits.Enum(
"t",
"x",
"y",
"z",
argstr="-%s",
position=2,
mandatory=True,
desc="dimension along which the file will be split",
)
class SplitOutputSpec(TraitedSpec):
out_files = OutputMultiPath(File(exists=True))
class Split(FSLCommand):
"""Uses FSL Fslsplit command to separate a volume into images in
time, x, y or z dimension.
"""
_cmd = "fslsplit"
input_spec = SplitInputSpec
output_spec = SplitOutputSpec
def _list_outputs(self):
"""Create a Bunch which contains all possible files generated
by running the interface. Some files are always generated, others
depending on which ``inputs`` options are set.
Returns
-------
outputs : Bunch object
Bunch object containing all possible files generated by
interface object.
If None, file was not generated
Else, contains path, filename of generated outputfile
"""
outputs = self._outputs().get()
ext = Info.output_type_to_ext(self.inputs.output_type)
outbase = "vol[0-9]*"
if isdefined(self.inputs.out_base_name):
outbase = "%s[0-9]*" % self.inputs.out_base_name
outputs["out_files"] = sorted(glob(os.path.join(os.getcwd(), outbase + ext)))
return outputs
class ImageMathsInputSpec(FSLCommandInputSpec):
in_file = File(exists=True, argstr="%s", mandatory=True, position=1)
in_file2 = File(exists=True, argstr="%s", position=3)
mask_file = File(
exists=True,
argstr="-mas %s",
desc="use (following image>0) to mask current image",
)
out_file = File(argstr="%s", position=-2, genfile=True, hash_files=False)
op_string = traits.Str(
argstr="%s", position=2, desc="string defining the operation, i. e. -add"
)
suffix = traits.Str(desc="out_file suffix")
out_data_type = traits.Enum(
"char",
"short",
"int",
"float",
"double",
"input",
argstr="-odt %s",
position=-1,
desc=("output datatype, one of (char, short, " "int, float, double, input)"),
)
class ImageMathsOutputSpec(TraitedSpec):
out_file = File(exists=True)
class ImageMaths(FSLCommand):
"""Use FSL fslmaths command to allow mathematical manipulation of images
`FSL info <http://www.fmrib.ox.ac.uk/fslcourse/lectures/practicals/intro/index.htm#fslutils>`_
Examples
--------
>>> from nipype.interfaces import fsl
>>> from nipype.testing import anatfile
>>> maths = fsl.ImageMaths(in_file=anatfile, op_string= '-add 5',
... out_file='foo_maths.nii')
>>> maths.cmdline == 'fslmaths %s -add 5 foo_maths.nii' % anatfile
True
"""
input_spec = ImageMathsInputSpec
output_spec = ImageMathsOutputSpec
_cmd = "fslmaths"
def _gen_filename(self, name):
if name == "out_file":
return self._list_outputs()[name]
return None
def _parse_inputs(self, skip=None):
return super(ImageMaths, self)._parse_inputs(skip=["suffix"])
def _list_outputs(self):
suffix = "_maths" # ohinds: build suffix
if isdefined(self.inputs.suffix):
suffix = self.inputs.suffix
outputs = self._outputs().get()
outputs["out_file"] = self.inputs.out_file
if not isdefined(outputs["out_file"]):
outputs["out_file"] = self._gen_fname(self.inputs.in_file, suffix=suffix)
outputs["out_file"] = os.path.abspath(outputs["out_file"])
return outputs
class FilterRegressorInputSpec(FSLCommandInputSpec):
in_file = File(
exists=True,
argstr="-i %s",
desc="input file name (4D image)",
mandatory=True,
position=1,
)
out_file = File(
argstr="-o %s",
desc="output file name for the filtered data",
genfile=True,
position=2,
hash_files=False,
)
design_file = File(
exists=True,
argstr="-d %s",
position=3,
mandatory=True,
desc=(
"name of the matrix with time courses (e.g. GLM "
"design or MELODIC mixing matrix)"
),
)
filter_columns = traits.List(
traits.Int,
argstr="-f '%s'",
xor=["filter_all"],
mandatory=True,
position=4,
desc=("(1-based) column indices to filter out of the data"),
)
filter_all = traits.Bool(
mandatory=True,
argstr="-f '%s'",
xor=["filter_columns"],
position=4,
desc=("use all columns in the design file in " "denoising"),
)
mask = File(exists=True, argstr="-m %s", desc="mask image file name")
var_norm = traits.Bool(argstr="--vn", desc="perform variance-normalization on data")
out_vnscales = traits.Bool(
argstr="--out_vnscales",
desc=("output scaling factors for variance " "normalization"),
)
class FilterRegressorOutputSpec(TraitedSpec):
out_file = File(exists=True, desc="output file name for the filtered data")
class FilterRegressor(FSLCommand):
"""Data de-noising by regressing out part of a design matrix
Uses simple OLS regression on 4D images
"""
input_spec = FilterRegressorInputSpec
output_spec = FilterRegressorOutputSpec
_cmd = "fsl_regfilt"
def _format_arg(self, name, trait_spec, value):
if name == "filter_columns":
return trait_spec.argstr % ",".join(map(str, value))
elif name == "filter_all":
design = np.loadtxt(self.inputs.design_file)
try:
n_cols = design.shape[1]
except IndexError:
n_cols = 1
return trait_spec.argstr % ",".join(map(str, list(range(1, n_cols + 1))))
return super(FilterRegressor, self)._format_arg(name, trait_spec, value)
def _list_outputs(self):
outputs = self.output_spec().get()
outputs["out_file"] = self.inputs.out_file
if not isdefined(outputs["out_file"]):
outputs["out_file"] = self._gen_fname(
self.inputs.in_file, suffix="_regfilt"
)
outputs["out_file"] = os.path.abspath(outputs["out_file"])
return outputs
def _gen_filename(self, name):
if name == "out_file":
return self._list_outputs()[name]
return None
class ImageStatsInputSpec(FSLCommandInputSpec):
split_4d = traits.Bool(
argstr="-t",
position=1,
desc=("give a separate output line for each 3D " "volume of a 4D timeseries"),
)
in_file = File(
exists=True,
argstr="%s",
mandatory=True,
position=3,
desc="input file to generate stats of",
)
op_string = traits.Str(
argstr="%s",
mandatory=True,
position=4,
desc=(
"string defining the operation, options are "
"applied in order, e.g. -M -l 10 -M will "
"report the non-zero mean, apply a threshold "
"and then report the new nonzero mean"
),
)
mask_file = File(exists=True, argstr="", desc="mask file used for option -k %s")
index_mask_file = File(
exists=True,
argstr="-K %s",
position=2,
desc="generate seperate n submasks from indexMask, "
"for indexvalues 1..n where n is the maximum index "
"value in indexMask, and generate statistics for each submask",
)
class ImageStatsOutputSpec(TraitedSpec):
out_stat = traits.Any(desc="stats output")
class ImageStats(FSLCommand):
"""Use FSL fslstats command to calculate stats from images
`FSL info
<http://www.fmrib.ox.ac.uk/fslcourse/lectures/practicals/intro/index.htm#fslutils>`_
Examples
--------
>>> from nipype.interfaces.fsl import ImageStats
>>> from nipype.testing import funcfile
>>> stats = ImageStats(in_file=funcfile, op_string= '-M')
>>> stats.cmdline == 'fslstats %s -M'%funcfile
True
"""
input_spec = ImageStatsInputSpec
output_spec = ImageStatsOutputSpec
_cmd = "fslstats"
def _format_arg(self, name, trait_spec, value):
if name == "mask_file":
return ""
if name == "op_string":
if "-k %s" in self.inputs.op_string:
if isdefined(self.inputs.mask_file):
return self.inputs.op_string % self.inputs.mask_file
else:
raise ValueError("-k %s option in op_string requires mask_file")
return super(ImageStats, self)._format_arg(name, trait_spec, value)
def aggregate_outputs(self, runtime=None, needed_outputs=None):
outputs = self._outputs()
# local caching for backward compatibility
outfile = os.path.join(os.getcwd(), "stat_result.json")
if runtime is None:
try:
out_stat = load_json(outfile)["stat"]
except IOError:
return self.run().outputs
else:
out_stat = []
for line in runtime.stdout.split("\n"):
if line:
values = line.split()
if len(values) > 1:
out_stat.append([float(val) for val in values])
else:
out_stat.extend([float(val) for val in values])
if len(out_stat) == 1:
out_stat = out_stat[0]
save_json(outfile, dict(stat=out_stat))
outputs.out_stat = out_stat
return outputs
class AvScaleInputSpec(CommandLineInputSpec):
all_param = traits.Bool(False, argstr="--allparams")
mat_file = File(exists=True, argstr="%s", desc="mat file to read", position=-2)
ref_file = File(
exists=True,
argstr="%s",
position=-1,
desc="reference file to get center of rotation",
)
class AvScaleOutputSpec(TraitedSpec):
rotation_translation_matrix = traits.List(
traits.List(traits.Float), desc="Rotation and Translation Matrix"
)
scales = traits.List(traits.Float, desc="Scales (x,y,z)")
skews = traits.List(traits.Float, desc="Skews")
average_scaling = traits.Float(desc="Average Scaling")
determinant = traits.Float(desc="Determinant")
forward_half_transform = traits.List(
traits.List(traits.Float), desc="Forward Half Transform"
)
backward_half_transform = traits.List(
traits.List(traits.Float), desc="Backwards Half Transform"
)
left_right_orientation_preserved = traits.Bool(
desc="True if LR orientation preserved"
)
rot_angles = traits.List(traits.Float, desc="rotation angles")
translations = traits.List(traits.Float, desc="translations")
class AvScale(CommandLine):
"""Use FSL avscale command to extract info from mat file output of FLIRT
Examples
--------
>>> avscale = AvScale()
>>> avscale.inputs.mat_file = 'flirt.mat'
>>> res = avscale.run() # doctest: +SKIP
"""
input_spec = AvScaleInputSpec
output_spec = AvScaleOutputSpec
_cmd = "avscale"
def _run_interface(self, runtime):
runtime = super(AvScale, self)._run_interface(runtime)
expr = re.compile(
r"Rotation & Translation Matrix:\n(?P<rot_tran_mat>[0-9\. \n-]+)[\s\n]*"
r"(Rotation Angles \(x,y,z\) \[rads\] = (?P<rot_angles>[0-9\. -]+))?[\s\n]*"
r"(Translations \(x,y,z\) \[mm\] = (?P<translations>[0-9\. -]+))?[\s\n]*"
r"Scales \(x,y,z\) = (?P<scales>[0-9\. -]+)[\s\n]*"
r"Skews \(xy,xz,yz\) = (?P<skews>[0-9\. -]+)[\s\n]*"
r"Average scaling = (?P<avg_scaling>[0-9\.-]+)[\s\n]*"
r"Determinant = (?P<determinant>[0-9\.-]+)[\s\n]*"
r"Left-Right orientation: (?P<lr_orientation>[A-Za-z]+)[\s\n]*"
r"Forward half transform =[\s]*\n"
r"(?P<fwd_half_xfm>[0-9\. \n-]+)[\s\n]*"
r"Backward half transform =[\s]*\n"
r"(?P<bwd_half_xfm>[0-9\. \n-]+)[\s\n]*"
)
out = expr.search(runtime.stdout).groupdict()
outputs = {}
outputs["rotation_translation_matrix"] = [
[float(v) for v in r.strip().split(" ")]
for r in out["rot_tran_mat"].strip().split("\n")
]
outputs["scales"] = [float(s) for s in out["scales"].strip().split(" ")]
outputs["skews"] = [float(s) for s in out["skews"].strip().split(" ")]
outputs["average_scaling"] = float(out["avg_scaling"].strip())
outputs["determinant"] = float(out["determinant"].strip())
outputs["left_right_orientation_preserved"] = (
out["lr_orientation"].strip() == "preserved"
)
outputs["forward_half_transform"] = [
[float(v) for v in r.strip().split(" ")]
for r in out["fwd_half_xfm"].strip().split("\n")
]
outputs["backward_half_transform"] = [
[float(v) for v in r.strip().split(" ")]
for r in out["bwd_half_xfm"].strip().split("\n")
]
if self.inputs.all_param:
outputs["rot_angles"] = [
float(r) for r in out["rot_angles"].strip().split(" ")
]
outputs["translations"] = [
float(r) for r in out["translations"].strip().split(" ")
]
setattr(self, "_results", outputs)
return runtime
def _list_outputs(self):
return self._results
class OverlayInputSpec(FSLCommandInputSpec):
transparency = traits.Bool(
desc="make overlay colors semi-transparent",
position=1,
argstr="%s",
usedefault=True,
default_value=True,
)
out_type = traits.Enum(
"float",
"int",
position=2,
usedefault=True,
argstr="%s",
desc="write output with float or int",
)
use_checkerboard = traits.Bool(
desc="use checkerboard mask for overlay", argstr="-c", position=3
)
background_image = File(
exists=True,
position=4,
mandatory=True,
argstr="%s",
desc="image to use as background",
)
_xor_inputs = ("auto_thresh_bg", "full_bg_range", "bg_thresh")
auto_thresh_bg = traits.Bool(
desc=("automatically threshold the background image"),
argstr="-a",
position=5,
xor=_xor_inputs,
mandatory=True,
)
full_bg_range = traits.Bool(
desc="use full range of background image",
argstr="-A",
position=5,
xor=_xor_inputs,
mandatory=True,
)
bg_thresh = traits.Tuple(
traits.Float,
traits.Float,
argstr="%.3f %.3f",
position=5,
desc="min and max values for background intensity",
xor=_xor_inputs,
mandatory=True,
)
stat_image = File(
exists=True,
position=6,
mandatory=True,
argstr="%s",
desc="statistical image to overlay in color",
)
stat_thresh = traits.Tuple(
traits.Float,
traits.Float,
position=7,