-
Notifications
You must be signed in to change notification settings - Fork 521
/
preprocess.py
2293 lines (2078 loc) · 75.5 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:
"""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.
"""
import os
import os.path as op
from warnings import warn
import numpy as np
from nibabel import load
from ... import LooseVersion
from ...utils.filemanip import split_filename
from ..base import (
TraitedSpec,
File,
InputMultiPath,
OutputMultiPath,
Undefined,
traits,
isdefined,
)
from .base import FSLCommand, FSLCommandInputSpec, Info
class BETInputSpec(FSLCommandInputSpec):
# We use position args here as list indices - so a negative number
# will put something on the end
in_file = File(
exists=True,
desc="input file to skull strip",
argstr="%s",
position=0,
mandatory=True,
copyfile=False,
)
out_file = File(
desc="name of output skull stripped image",
argstr="%s",
position=1,
genfile=True,
hash_files=False,
)
outline = traits.Bool(desc="create surface outline image", argstr="-o")
mask = traits.Bool(desc="create binary mask image", argstr="-m")
skull = traits.Bool(desc="create skull image", argstr="-s")
no_output = traits.Bool(argstr="-n", desc="Don't generate segmented output")
frac = traits.Float(desc="fractional intensity threshold", argstr="-f %.2f")
vertical_gradient = traits.Float(
argstr="-g %.2f",
desc="vertical gradient in fractional intensity threshold (-1, 1)",
)
radius = traits.Int(argstr="-r %d", units="mm", desc="head radius")
center = traits.List(
traits.Int,
desc="center of gravity in voxels",
argstr="-c %s",
minlen=0,
maxlen=3,
units="voxels",
)
threshold = traits.Bool(
argstr="-t", desc="apply thresholding to segmented brain image and mask"
)
mesh = traits.Bool(argstr="-e", desc="generate a vtk mesh brain surface")
# the remaining 'options' are more like modes (mutually exclusive) that
# FSL actually implements in a shell script wrapper around the bet binary.
# for some combinations of them in specific order a call would not fail,
# but in general using more than one of the following is clearly not
# supported
_xor_inputs = (
"functional",
"reduce_bias",
"robust",
"padding",
"remove_eyes",
"surfaces",
"t2_guided",
)
robust = traits.Bool(
desc="robust brain centre estimation (iterates BET several times)",
argstr="-R",
xor=_xor_inputs,
)
padding = traits.Bool(
desc=(
"improve BET if FOV is very small in Z (by temporarily padding "
"end slices)"
),
argstr="-Z",
xor=_xor_inputs,
)
remove_eyes = traits.Bool(
desc="eye & optic nerve cleanup (can be useful in SIENA)",
argstr="-S",
xor=_xor_inputs,
)
surfaces = traits.Bool(
desc=(
"run bet2 and then betsurf to get additional skull and scalp "
"surfaces (includes registrations)"
),
argstr="-A",
xor=_xor_inputs,
)
t2_guided = File(
desc="as with creating surfaces, when also feeding in "
"non-brain-extracted T2 (includes registrations)",
argstr="-A2 %s",
xor=_xor_inputs,
)
functional = traits.Bool(argstr="-F", xor=_xor_inputs, desc="apply to 4D fMRI data")
reduce_bias = traits.Bool(
argstr="-B", xor=_xor_inputs, desc="bias field and neck cleanup"
)
class BETOutputSpec(TraitedSpec):
out_file = File(desc="path/name of skullstripped file (if generated)")
mask_file = File(desc="path/name of binary brain mask (if generated)")
outline_file = File(desc="path/name of outline file (if generated)")
meshfile = File(desc="path/name of vtk mesh file (if generated)")
inskull_mask_file = File(desc="path/name of inskull mask (if generated)")
inskull_mesh_file = File(desc="path/name of inskull mesh outline (if generated)")
outskull_mask_file = File(desc="path/name of outskull mask (if generated)")
outskull_mesh_file = File(desc="path/name of outskull mesh outline (if generated)")
outskin_mask_file = File(desc="path/name of outskin mask (if generated)")
outskin_mesh_file = File(desc="path/name of outskin mesh outline (if generated)")
skull_mask_file = File(desc="path/name of skull mask (if generated)")
skull_file = File(desc="path/name of skull file (if generated)")
class BET(FSLCommand):
"""FSL BET wrapper for skull stripping
For complete details, see the `BET Documentation.
<https://fsl.fmrib.ox.ac.uk/fsl/fslwiki/BET/UserGuide>`_
Examples
--------
>>> from nipype.interfaces import fsl
>>> btr = fsl.BET()
>>> btr.inputs.in_file = 'structural.nii'
>>> btr.inputs.frac = 0.7
>>> btr.inputs.out_file = 'brain_anat.nii'
>>> btr.cmdline
'bet structural.nii brain_anat.nii -f 0.70'
>>> res = btr.run() # doctest: +SKIP
"""
_cmd = "bet"
input_spec = BETInputSpec
output_spec = BETOutputSpec
def _run_interface(self, runtime):
# The returncode is meaningless in BET. So check the output
# in stderr and if it's set, then update the returncode
# accordingly.
runtime = super(BET, self)._run_interface(runtime)
if runtime.stderr:
self.raise_exception(runtime)
return runtime
def _format_arg(self, name, spec, value):
formatted = super(BET, self)._format_arg(name, spec, value)
if name == "in_file":
# Convert to relative path to prevent BET failure
# with long paths.
return op.relpath(formatted, start=os.getcwd())
return formatted
def _gen_outfilename(self):
out_file = self.inputs.out_file
# Generate default output filename if non specified.
if not isdefined(out_file) and isdefined(self.inputs.in_file):
out_file = self._gen_fname(self.inputs.in_file, suffix="_brain")
# Convert to relative path to prevent BET failure
# with long paths.
return op.relpath(out_file, start=os.getcwd())
return out_file
def _list_outputs(self):
outputs = self.output_spec().get()
outputs["out_file"] = os.path.abspath(self._gen_outfilename())
basename = os.path.basename(outputs["out_file"])
cwd = os.path.dirname(outputs["out_file"])
kwargs = {"basename": basename, "cwd": cwd}
if (isdefined(self.inputs.mesh) and self.inputs.mesh) or (
isdefined(self.inputs.surfaces) and self.inputs.surfaces
):
outputs["meshfile"] = self._gen_fname(
suffix="_mesh.vtk", change_ext=False, **kwargs
)
if (isdefined(self.inputs.mask) and self.inputs.mask) or (
isdefined(self.inputs.reduce_bias) and self.inputs.reduce_bias
):
outputs["mask_file"] = self._gen_fname(suffix="_mask", **kwargs)
if isdefined(self.inputs.outline) and self.inputs.outline:
outputs["outline_file"] = self._gen_fname(suffix="_overlay", **kwargs)
if isdefined(self.inputs.surfaces) and self.inputs.surfaces:
outputs["inskull_mask_file"] = self._gen_fname(
suffix="_inskull_mask", **kwargs
)
outputs["inskull_mesh_file"] = self._gen_fname(
suffix="_inskull_mesh", **kwargs
)
outputs["outskull_mask_file"] = self._gen_fname(
suffix="_outskull_mask", **kwargs
)
outputs["outskull_mesh_file"] = self._gen_fname(
suffix="_outskull_mesh", **kwargs
)
outputs["outskin_mask_file"] = self._gen_fname(
suffix="_outskin_mask", **kwargs
)
outputs["outskin_mesh_file"] = self._gen_fname(
suffix="_outskin_mesh", **kwargs
)
outputs["skull_mask_file"] = self._gen_fname(suffix="_skull_mask", **kwargs)
if isdefined(self.inputs.skull) and self.inputs.skull:
outputs["skull_file"] = self._gen_fname(suffix="_skull", **kwargs)
if isdefined(self.inputs.no_output) and self.inputs.no_output:
outputs["out_file"] = Undefined
return outputs
def _gen_filename(self, name):
if name == "out_file":
return self._gen_outfilename()
return None
class FASTInputSpec(FSLCommandInputSpec):
"""Defines inputs (trait classes) for FAST"""
in_files = InputMultiPath(
File(exists=True),
copyfile=False,
desc="image, or multi-channel set of images, " "to be segmented",
argstr="%s",
position=-1,
mandatory=True,
)
out_basename = File(desc="base name of output files", argstr="-o %s")
# ^^ uses in_file name as basename if none given
number_classes = traits.Range(
low=1, high=10, argstr="-n %d", desc="number of tissue-type classes"
)
output_biasfield = traits.Bool(desc="output estimated bias field", argstr="-b")
output_biascorrected = traits.Bool(
desc="output restored image (bias-corrected image)", argstr="-B"
)
img_type = traits.Enum(
(1, 2, 3),
desc="int specifying type of image: (1 = T1, 2 = T2, 3 = PD)",
argstr="-t %d",
)
bias_iters = traits.Range(
low=1,
high=10,
argstr="-I %d",
desc="number of main-loop iterations during " "bias-field removal",
)
bias_lowpass = traits.Range(
low=4,
high=40,
desc="bias field smoothing extent (FWHM) " "in mm",
argstr="-l %d",
units="mm",
)
init_seg_smooth = traits.Range(
low=0.0001,
high=0.1,
desc="initial segmentation spatial "
"smoothness (during bias field "
"estimation)",
argstr="-f %.3f",
)
segments = traits.Bool(
desc="outputs a separate binary image for each " "tissue type", argstr="-g"
)
init_transform = File(
exists=True,
desc="<standard2input.mat> initialise" " using priors",
argstr="-a %s",
)
other_priors = InputMultiPath(
File(exist=True),
desc="alternative prior images",
argstr="-A %s",
minlen=3,
maxlen=3,
)
no_pve = traits.Bool(
desc="turn off PVE (partial volume estimation)", argstr="--nopve"
)
no_bias = traits.Bool(desc="do not remove bias field", argstr="-N")
use_priors = traits.Bool(desc="use priors throughout", argstr="-P")
# ^^ Must also set -a!, mutually inclusive?? No, conditional mandatory... need to figure out how to handle with traits.
segment_iters = traits.Range(
low=1,
high=50,
desc="number of segmentation-initialisation" " iterations",
argstr="-W %d",
)
mixel_smooth = traits.Range(
low=0.0, high=1.0, desc="spatial smoothness for mixeltype", argstr="-R %.2f"
)
iters_afterbias = traits.Range(
low=1,
high=20,
desc="number of main-loop iterations " "after bias-field removal",
argstr="-O %d",
)
hyper = traits.Range(
low=0.0, high=1.0, desc="segmentation spatial smoothness", argstr="-H %.2f"
)
verbose = traits.Bool(desc="switch on diagnostic messages", argstr="-v")
manual_seg = File(
exists=True, desc="Filename containing intensities", argstr="-s %s"
)
probability_maps = traits.Bool(
desc="outputs individual probability maps", argstr="-p"
)
class FASTOutputSpec(TraitedSpec):
"""Specify possible outputs from FAST"""
tissue_class_map = File(
exists=True,
desc="path/name of binary segmented volume file"
" one val for each class _seg",
)
tissue_class_files = OutputMultiPath(
File(
desc=(
"path/name of binary segmented volumes one file for each class "
"_seg_x"
)
)
)
restored_image = OutputMultiPath(
File(
desc=(
"restored images (one for each input image) named according to "
"the input images _restore"
)
)
)
mixeltype = File(desc="path/name of mixeltype volume file _mixeltype")
partial_volume_map = File(desc="path/name of partial volume file _pveseg")
partial_volume_files = OutputMultiPath(
File(desc="path/name of partial volumes files one for each class, _pve_x")
)
bias_field = OutputMultiPath(File(desc="Estimated bias field _bias"))
probability_maps = OutputMultiPath(
File(desc="filenames, one for each class, for each input, prob_x")
)
class FAST(FSLCommand):
"""FSL FAST wrapper for segmentation and bias correction
For complete details, see the `FAST Documentation.
<https://fsl.fmrib.ox.ac.uk/fsl/fslwiki/FAST>`_
Examples
--------
>>> from nipype.interfaces import fsl
>>> fastr = fsl.FAST()
>>> fastr.inputs.in_files = 'structural.nii'
>>> fastr.inputs.out_basename = 'fast_'
>>> fastr.cmdline
'fast -o fast_ -S 1 structural.nii'
>>> out = fastr.run() # doctest: +SKIP
"""
_cmd = "fast"
input_spec = FASTInputSpec
output_spec = FASTOutputSpec
def _format_arg(self, name, spec, value):
# first do what should be done in general
formatted = super(FAST, self)._format_arg(name, spec, value)
if name == "in_files":
# FAST needs the -S parameter value to correspond to the number
# of input images, otherwise it will ignore all but the first
formatted = "-S %d %s" % (len(value), formatted)
return formatted
def _list_outputs(self):
outputs = self.output_spec().get()
if not isdefined(self.inputs.number_classes):
nclasses = 3
else:
nclasses = self.inputs.number_classes
# when using multichannel, results basename is based on last
# input filename
_gen_fname_opts = {}
if isdefined(self.inputs.out_basename):
_gen_fname_opts["basename"] = self.inputs.out_basename
_gen_fname_opts["cwd"] = os.getcwd()
else:
_gen_fname_opts["basename"] = self.inputs.in_files[-1]
_gen_fname_opts["cwd"], _, _ = split_filename(_gen_fname_opts["basename"])
outputs["tissue_class_map"] = self._gen_fname(suffix="_seg", **_gen_fname_opts)
if self.inputs.segments:
outputs["tissue_class_files"] = []
for i in range(nclasses):
outputs["tissue_class_files"].append(
self._gen_fname(suffix="_seg_%d" % i, **_gen_fname_opts)
)
if isdefined(self.inputs.output_biascorrected):
outputs["restored_image"] = []
if len(self.inputs.in_files) > 1:
# for multi-image segmentation there is one corrected image
# per input
for val, f in enumerate(self.inputs.in_files):
# image numbering is 1-based
outputs["restored_image"].append(
self._gen_fname(
suffix="_restore_%d" % (val + 1), **_gen_fname_opts
)
)
else:
# single image segmentation has unnumbered output image
outputs["restored_image"].append(
self._gen_fname(suffix="_restore", **_gen_fname_opts)
)
outputs["mixeltype"] = self._gen_fname(suffix="_mixeltype", **_gen_fname_opts)
if not self.inputs.no_pve:
outputs["partial_volume_map"] = self._gen_fname(
suffix="_pveseg", **_gen_fname_opts
)
outputs["partial_volume_files"] = []
for i in range(nclasses):
outputs["partial_volume_files"].append(
self._gen_fname(suffix="_pve_%d" % i, **_gen_fname_opts)
)
if self.inputs.output_biasfield:
outputs["bias_field"] = []
if len(self.inputs.in_files) > 1:
# for multi-image segmentation there is one bias field image
# per input
for val, f in enumerate(self.inputs.in_files):
# image numbering is 1-based
outputs["bias_field"].append(
self._gen_fname(
suffix="_bias_%d" % (val + 1), **_gen_fname_opts
)
)
else:
# single image segmentation has unnumbered output image
outputs["bias_field"].append(
self._gen_fname(suffix="_bias", **_gen_fname_opts)
)
if self.inputs.probability_maps:
outputs["probability_maps"] = []
for i in range(nclasses):
outputs["probability_maps"].append(
self._gen_fname(suffix="_prob_%d" % i, **_gen_fname_opts)
)
return outputs
class FLIRTInputSpec(FSLCommandInputSpec):
in_file = File(
exists=True, argstr="-in %s", mandatory=True, position=0, desc="input file"
)
reference = File(
exists=True, argstr="-ref %s", mandatory=True, position=1, desc="reference file"
)
out_file = File(
argstr="-out %s",
desc="registered output file",
name_source=["in_file"],
name_template="%s_flirt",
position=2,
hash_files=False,
)
out_matrix_file = File(
argstr="-omat %s",
name_source=["in_file"],
keep_extension=True,
name_template="%s_flirt.mat",
desc="output affine matrix in 4x4 asciii format",
position=3,
hash_files=False,
)
out_log = File(
name_source=["in_file"],
keep_extension=True,
requires=["save_log"],
name_template="%s_flirt.log",
desc="output log",
)
in_matrix_file = File(argstr="-init %s", desc="input 4x4 affine matrix")
apply_xfm = traits.Bool(
argstr="-applyxfm",
desc=(
"apply transformation supplied by in_matrix_file or uses_qform to"
" use the affine matrix stored in the reference header"
),
)
apply_isoxfm = traits.Float(
argstr="-applyisoxfm %f",
xor=["apply_xfm"],
desc="as applyxfm but forces isotropic resampling",
)
datatype = traits.Enum(
"char",
"short",
"int",
"float",
"double",
argstr="-datatype %s",
desc="force output data type",
)
cost = traits.Enum(
"mutualinfo",
"corratio",
"normcorr",
"normmi",
"leastsq",
"labeldiff",
"bbr",
argstr="-cost %s",
desc="cost function",
)
# XXX What is the difference between 'cost' and 'searchcost'? Are
# these both necessary or do they map to the same variable.
cost_func = traits.Enum(
"mutualinfo",
"corratio",
"normcorr",
"normmi",
"leastsq",
"labeldiff",
"bbr",
argstr="-searchcost %s",
desc="cost function",
)
uses_qform = traits.Bool(
argstr="-usesqform", desc="initialize using sform or qform"
)
display_init = traits.Bool(argstr="-displayinit", desc="display initial matrix")
angle_rep = traits.Enum(
"quaternion",
"euler",
argstr="-anglerep %s",
desc="representation of rotation angles",
)
interp = traits.Enum(
"trilinear",
"nearestneighbour",
"sinc",
"spline",
argstr="-interp %s",
desc="final interpolation method used in reslicing",
)
sinc_width = traits.Int(
argstr="-sincwidth %d", units="voxels", desc="full-width in voxels"
)
sinc_window = traits.Enum(
"rectangular",
"hanning",
"blackman",
argstr="-sincwindow %s",
desc="sinc window",
) # XXX better doc
bins = traits.Int(argstr="-bins %d", desc="number of histogram bins")
dof = traits.Int(argstr="-dof %d", desc="number of transform degrees of freedom")
no_resample = traits.Bool(argstr="-noresample", desc="do not change input sampling")
force_scaling = traits.Bool(
argstr="-forcescaling", desc="force rescaling even for low-res images"
)
min_sampling = traits.Float(
argstr="-minsampling %f",
units="mm",
desc="set minimum voxel dimension for sampling",
)
padding_size = traits.Int(
argstr="-paddingsize %d",
units="voxels",
desc="for applyxfm: interpolates outside image " "by size",
)
searchr_x = traits.List(
traits.Int,
minlen=2,
maxlen=2,
units="degrees",
argstr="-searchrx %s",
desc="search angles along x-axis, in degrees",
)
searchr_y = traits.List(
traits.Int,
minlen=2,
maxlen=2,
units="degrees",
argstr="-searchry %s",
desc="search angles along y-axis, in degrees",
)
searchr_z = traits.List(
traits.Int,
minlen=2,
maxlen=2,
units="degrees",
argstr="-searchrz %s",
desc="search angles along z-axis, in degrees",
)
no_search = traits.Bool(
argstr="-nosearch", desc="set all angular searches to ranges 0 to 0"
)
coarse_search = traits.Int(
argstr="-coarsesearch %d", units="degrees", desc="coarse search delta angle"
)
fine_search = traits.Int(
argstr="-finesearch %d", units="degrees", desc="fine search delta angle"
)
schedule = File(
exists=True, argstr="-schedule %s", desc="replaces default schedule"
)
ref_weight = File(
exists=True, argstr="-refweight %s", desc="File for reference weighting volume"
)
in_weight = File(
exists=True, argstr="-inweight %s", desc="File for input weighting volume"
)
no_clamp = traits.Bool(argstr="-noclamp", desc="do not use intensity clamping")
no_resample_blur = traits.Bool(
argstr="-noresampblur", desc="do not use blurring on downsampling"
)
rigid2D = traits.Bool(argstr="-2D", desc="use 2D rigid body mode - ignores dof")
save_log = traits.Bool(desc="save to log file")
verbose = traits.Int(argstr="-verbose %d", desc="verbose mode, 0 is least")
bgvalue = traits.Float(
0,
argstr="-setbackground %f",
desc=("use specified background value for points " "outside FOV"),
)
# BBR options
wm_seg = File(
argstr="-wmseg %s",
min_ver="5.0.0",
desc="white matter segmentation volume needed by BBR cost function",
)
wmcoords = File(
argstr="-wmcoords %s",
min_ver="5.0.0",
desc="white matter boundary coordinates for BBR cost function",
)
wmnorms = File(
argstr="-wmnorms %s",
min_ver="5.0.0",
desc="white matter boundary normals for BBR cost function",
)
fieldmap = File(
argstr="-fieldmap %s",
min_ver="5.0.0",
desc=(
"fieldmap image in rads/s - must be already registered to the "
"reference image"
),
)
fieldmapmask = File(
argstr="-fieldmapmask %s", min_ver="5.0.0", desc="mask for fieldmap image"
)
pedir = traits.Int(
argstr="-pedir %d",
min_ver="5.0.0",
desc="phase encode direction of EPI - 1/2/3=x/y/z & -1/-2/-3=-x/-y/-z",
)
echospacing = traits.Float(
argstr="-echospacing %f",
min_ver="5.0.0",
desc="value of EPI echo spacing - units of seconds",
)
bbrtype = traits.Enum(
"signed",
"global_abs",
"local_abs",
argstr="-bbrtype %s",
min_ver="5.0.0",
desc=("type of bbr cost function: signed [default], global_abs, " "local_abs"),
)
bbrslope = traits.Float(
argstr="-bbrslope %f", min_ver="5.0.0", desc="value of bbr slope"
)
class FLIRTOutputSpec(TraitedSpec):
out_file = File(exists=True, desc="path/name of registered file (if generated)")
out_matrix_file = File(
exists=True, desc="path/name of calculated affine transform " "(if generated)"
)
out_log = File(desc="path/name of output log (if generated)")
class FLIRT(FSLCommand):
"""FSL FLIRT wrapper for coregistration
For complete details, see the `FLIRT Documentation.
<https://fsl.fmrib.ox.ac.uk/fsl/fslwiki/FLIRT>`_
To print out the command line help, use:
fsl.FLIRT().inputs_help()
Examples
--------
>>> from nipype.interfaces import fsl
>>> from nipype.testing import example_data
>>> flt = fsl.FLIRT(bins=640, cost_func='mutualinfo')
>>> flt.inputs.in_file = 'structural.nii'
>>> flt.inputs.reference = 'mni.nii'
>>> flt.inputs.output_type = "NIFTI_GZ"
>>> flt.cmdline # doctest: +ELLIPSIS
'flirt -in structural.nii -ref mni.nii -out structural_flirt.nii.gz -omat structural_flirt.mat -bins 640 -searchcost mutualinfo'
>>> res = flt.run() #doctest: +SKIP
"""
_cmd = "flirt"
input_spec = FLIRTInputSpec
output_spec = FLIRTOutputSpec
_log_written = False
def aggregate_outputs(self, runtime=None, needed_outputs=None):
outputs = super(FLIRT, self).aggregate_outputs(
runtime=runtime, needed_outputs=needed_outputs
)
if self.inputs.save_log and not self._log_written:
with open(outputs.out_log, "a") as text_file:
text_file.write(runtime.stdout + "\n")
self._log_written = True
return outputs
def _parse_inputs(self, skip=None):
if skip is None:
skip = []
if self.inputs.save_log and not self.inputs.verbose:
self.inputs.verbose = 1
if self.inputs.apply_xfm and not (
self.inputs.in_matrix_file or self.inputs.uses_qform
):
raise RuntimeError(
"Argument apply_xfm requires in_matrix_file or "
"uses_qform arguments to run"
)
skip.append("save_log")
return super(FLIRT, self)._parse_inputs(skip=skip)
class ApplyXFMInputSpec(FLIRTInputSpec):
apply_xfm = traits.Bool(
True,
argstr="-applyxfm",
desc=(
"apply transformation supplied by in_matrix_file or uses_qform to"
" use the affine matrix stored in the reference header"
),
usedefault=True,
)
class ApplyXFM(FLIRT):
"""Currently just a light wrapper around FLIRT,
with no modifications
ApplyXFM is used to apply an existing tranform to an image
Examples
--------
>>> import nipype.interfaces.fsl as fsl
>>> from nipype.testing import example_data
>>> applyxfm = fsl.preprocess.ApplyXFM()
>>> applyxfm.inputs.in_file = example_data('structural.nii')
>>> applyxfm.inputs.in_matrix_file = example_data('trans.mat')
>>> applyxfm.inputs.out_file = 'newfile.nii'
>>> applyxfm.inputs.reference = example_data('mni.nii')
>>> applyxfm.inputs.apply_xfm = True
>>> result = applyxfm.run() # doctest: +SKIP
"""
input_spec = ApplyXFMInputSpec
class MCFLIRTInputSpec(FSLCommandInputSpec):
in_file = File(
exists=True,
position=0,
argstr="-in %s",
mandatory=True,
desc="timeseries to motion-correct",
)
out_file = File(
argstr="-out %s", genfile=True, desc="file to write", hash_files=False
)
cost = traits.Enum(
"mutualinfo",
"woods",
"corratio",
"normcorr",
"normmi",
"leastsquares",
argstr="-cost %s",
desc="cost function to optimize",
)
bins = traits.Int(argstr="-bins %d", desc="number of histogram bins")
dof = traits.Int(argstr="-dof %d", desc="degrees of freedom for the transformation")
ref_vol = traits.Int(argstr="-refvol %d", desc="volume to align frames to")
scaling = traits.Float(argstr="-scaling %.2f", desc="scaling factor to use")
smooth = traits.Float(
argstr="-smooth %.2f", desc="smoothing factor for the cost function"
)
rotation = traits.Int(
argstr="-rotation %d", desc="scaling factor for rotation tolerances"
)
stages = traits.Int(
argstr="-stages %d",
desc="stages (if 4, perform final search with sinc interpolation",
)
init = File(exists=True, argstr="-init %s", desc="inital transformation matrix")
interpolation = traits.Enum(
"spline",
"nn",
"sinc",
argstr="-%s_final",
desc="interpolation method for transformation",
)
use_gradient = traits.Bool(argstr="-gdt", desc="run search on gradient images")
use_contour = traits.Bool(argstr="-edge", desc="run search on contour images")
mean_vol = traits.Bool(argstr="-meanvol", desc="register to mean volume")
stats_imgs = traits.Bool(
argstr="-stats", desc="produce variance and std. dev. images"
)
save_mats = traits.Bool(argstr="-mats", desc="save transformation matrices")
save_plots = traits.Bool(argstr="-plots", desc="save transformation parameters")
save_rms = traits.Bool(
argstr="-rmsabs -rmsrel", desc="save rms displacement parameters"
)
ref_file = File(
exists=True, argstr="-reffile %s", desc="target image for motion correction"
)
class MCFLIRTOutputSpec(TraitedSpec):
out_file = File(exists=True, desc="motion-corrected timeseries")
variance_img = File(exists=True, desc="variance image")
std_img = File(exists=True, desc="standard deviation image")
mean_img = File(exists=True, desc="mean timeseries image (if mean_vol=True)")
par_file = File(exists=True, desc="text-file with motion parameters")
mat_file = OutputMultiPath(File(exists=True), desc="transformation matrices")
rms_files = OutputMultiPath(
File(exists=True), desc="absolute and relative displacement parameters"
)
class MCFLIRT(FSLCommand):
"""FSL MCFLIRT wrapper for within-modality motion correction
For complete details, see the `MCFLIRT Documentation.
<https://fsl.fmrib.ox.ac.uk/fsl/fslwiki/MCFLIRT>`_
Examples
--------
>>> from nipype.interfaces import fsl
>>> mcflt = fsl.MCFLIRT()
>>> mcflt.inputs.in_file = 'functional.nii'
>>> mcflt.inputs.cost = 'mutualinfo'
>>> mcflt.inputs.out_file = 'moco.nii'
>>> mcflt.cmdline
'mcflirt -in functional.nii -cost mutualinfo -out moco.nii'
>>> res = mcflt.run() # doctest: +SKIP
"""
_cmd = "mcflirt"
input_spec = MCFLIRTInputSpec
output_spec = MCFLIRTOutputSpec
def _format_arg(self, name, spec, value):
if name == "interpolation":
if value == "trilinear":
return ""
else:
return spec.argstr % value
return super(MCFLIRT, self)._format_arg(name, spec, value)
def _list_outputs(self):
outputs = self._outputs().get()
outputs["out_file"] = self._gen_outfilename()
output_dir = os.path.dirname(outputs["out_file"])
if isdefined(self.inputs.stats_imgs) and self.inputs.stats_imgs:
if LooseVersion(Info.version()) < LooseVersion("6.0.0"):
# FSL <6.0 outputs have .nii.gz_variance.nii.gz as extension
outputs["variance_img"] = self._gen_fname(
outputs["out_file"] + "_variance.ext", cwd=output_dir
)
outputs["std_img"] = self._gen_fname(
outputs["out_file"] + "_sigma.ext", cwd=output_dir
)
else:
outputs["variance_img"] = self._gen_fname(
outputs["out_file"], suffix="_variance", cwd=output_dir
)
outputs["std_img"] = self._gen_fname(
outputs["out_file"], suffix="_sigma", cwd=output_dir
)
# The mean image created if -stats option is specified ('meanvol')
# is missing the top and bottom slices. Therefore we only expose the
# mean image created by -meanvol option ('mean_reg') which isn't
# corrupted.
# Note that the same problem holds for the std and variance image.
if isdefined(self.inputs.mean_vol) and self.inputs.mean_vol:
if LooseVersion(Info.version()) < LooseVersion("6.0.0"):
# FSL <6.0 outputs have .nii.gz_mean_img.nii.gz as extension
outputs["mean_img"] = self._gen_fname(
outputs["out_file"] + "_mean_reg.ext", cwd=output_dir
)
else:
outputs["mean_img"] = self._gen_fname(
outputs["out_file"], suffix="_mean_reg", cwd=output_dir
)
if isdefined(self.inputs.save_mats) and self.inputs.save_mats:
_, filename = os.path.split(outputs["out_file"])
matpathname = os.path.join(output_dir, filename + ".mat")
_, _, _, timepoints = load(self.inputs.in_file).shape
outputs["mat_file"] = []
for t in range(timepoints):
outputs["mat_file"].append(os.path.join(matpathname, "MAT_%04d" % t))
if isdefined(self.inputs.save_plots) and self.inputs.save_plots:
# Note - if e.g. out_file has .nii.gz, you get .nii.gz.par,
# which is what mcflirt does!
outputs["par_file"] = outputs["out_file"] + ".par"
if isdefined(self.inputs.save_rms) and self.inputs.save_rms:
outfile = outputs["out_file"]
outputs["rms_files"] = [outfile + "_abs.rms", outfile + "_rel.rms"]
return outputs
def _gen_filename(self, name):
if name == "out_file":
return self._gen_outfilename()
return None
def _gen_outfilename(self):
out_file = self.inputs.out_file
if isdefined(out_file):
out_file = os.path.realpath(out_file)
if not isdefined(out_file) and isdefined(self.inputs.in_file):
out_file = self._gen_fname(self.inputs.in_file, suffix="_mcf")
return os.path.abspath(out_file)
class FNIRTInputSpec(FSLCommandInputSpec):
ref_file = File(
exists=True, argstr="--ref=%s", mandatory=True, desc="name of reference image"
)
in_file = File(
exists=True, argstr="--in=%s", mandatory=True, desc="name of input image"
)
affine_file = File(
exists=True, argstr="--aff=%s", desc="name of file containing affine transform"
)
inwarp_file = File(
exists=True,
argstr="--inwarp=%s",
desc="name of file containing initial non-linear warps",
)
in_intensitymap_file = traits.List(
File(exists=True),
argstr="--intin=%s",
copyfile=False,
minlen=1,
maxlen=2,
desc=(
"name of file/files containing "
"initial intensity mapping "
"usually generated by previous "