-
Notifications
You must be signed in to change notification settings - Fork 520
/
preprocess.py
3374 lines (3040 loc) · 109 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:
"""Provides interfaces to various commands provided by FreeSurfer
"""
import os
import os.path as op
from glob import glob
import shutil
import numpy as np
from nibabel import load
from ... import logging, LooseVersion
from ...utils.filemanip import fname_presuffix, check_depends
from ..io import FreeSurferSource
from ..base import (
TraitedSpec,
File,
traits,
Directory,
InputMultiPath,
OutputMultiPath,
CommandLine,
CommandLineInputSpec,
isdefined,
)
from .base import FSCommand, FSTraitedSpec, FSTraitedSpecOpenMP, FSCommandOpenMP, Info
from .utils import copy2subjdir
__docformat__ = "restructuredtext"
iflogger = logging.getLogger("nipype.interface")
# Keeping this to avoid breaking external programs that depend on it, but
# this should not be used internally
FSVersion = Info.looseversion().vstring
class ParseDICOMDirInputSpec(FSTraitedSpec):
dicom_dir = Directory(
exists=True,
argstr="--d %s",
mandatory=True,
desc="path to siemens dicom directory",
)
dicom_info_file = File(
"dicominfo.txt",
argstr="--o %s",
usedefault=True,
desc="file to which results are written",
)
sortbyrun = traits.Bool(argstr="--sortbyrun", desc="assign run numbers")
summarize = traits.Bool(
argstr="--summarize", desc="only print out info for run leaders"
)
class ParseDICOMDirOutputSpec(TraitedSpec):
dicom_info_file = File(exists=True, desc="text file containing dicom information")
class ParseDICOMDir(FSCommand):
"""Uses mri_parse_sdcmdir to get information from dicom directories
Examples
--------
>>> from nipype.interfaces.freesurfer import ParseDICOMDir
>>> dcminfo = ParseDICOMDir()
>>> dcminfo.inputs.dicom_dir = '.'
>>> dcminfo.inputs.sortbyrun = True
>>> dcminfo.inputs.summarize = True
>>> dcminfo.cmdline
'mri_parse_sdcmdir --d . --o dicominfo.txt --sortbyrun --summarize'
"""
_cmd = "mri_parse_sdcmdir"
input_spec = ParseDICOMDirInputSpec
output_spec = ParseDICOMDirOutputSpec
def _list_outputs(self):
outputs = self.output_spec().get()
if isdefined(self.inputs.dicom_info_file):
outputs["dicom_info_file"] = os.path.join(
os.getcwd(), self.inputs.dicom_info_file
)
return outputs
class UnpackSDICOMDirInputSpec(FSTraitedSpec):
source_dir = Directory(
exists=True,
argstr="-src %s",
mandatory=True,
desc="directory with the DICOM files",
)
output_dir = Directory(
argstr="-targ %s", desc="top directory into which the files will be unpacked"
)
run_info = traits.Tuple(
traits.Int,
traits.Str,
traits.Str,
traits.Str,
mandatory=True,
argstr="-run %d %s %s %s",
xor=("run_info", "config", "seq_config"),
desc="runno subdir format name : spec unpacking rules on cmdline",
)
config = File(
exists=True,
argstr="-cfg %s",
mandatory=True,
xor=("run_info", "config", "seq_config"),
desc="specify unpacking rules in file",
)
seq_config = File(
exists=True,
argstr="-seqcfg %s",
mandatory=True,
xor=("run_info", "config", "seq_config"),
desc="specify unpacking rules based on sequence",
)
dir_structure = traits.Enum(
"fsfast",
"generic",
argstr="-%s",
desc="unpack to specified directory structures",
)
no_info_dump = traits.Bool(argstr="-noinfodump", desc="do not create infodump file")
scan_only = File(
exists=True,
argstr="-scanonly %s",
desc="only scan the directory and put result in file",
)
log_file = File(exists=True, argstr="-log %s", desc="explicilty set log file")
spm_zeropad = traits.Int(
argstr="-nspmzeropad %d", desc="set frame number zero padding width for SPM"
)
no_unpack_err = traits.Bool(
argstr="-no-unpackerr", desc="do not try to unpack runs with errors"
)
class UnpackSDICOMDir(FSCommand):
"""Use unpacksdcmdir to convert dicom files
Call unpacksdcmdir -help from the command line to see more information on
using this command.
Examples
--------
>>> from nipype.interfaces.freesurfer import UnpackSDICOMDir
>>> unpack = UnpackSDICOMDir()
>>> unpack.inputs.source_dir = '.'
>>> unpack.inputs.output_dir = '.'
>>> unpack.inputs.run_info = (5, 'mprage', 'nii', 'struct')
>>> unpack.inputs.dir_structure = 'generic'
>>> unpack.cmdline
'unpacksdcmdir -generic -targ . -run 5 mprage nii struct -src .'
"""
_cmd = "unpacksdcmdir"
input_spec = UnpackSDICOMDirInputSpec
class MRIConvertInputSpec(FSTraitedSpec):
read_only = traits.Bool(argstr="--read_only", desc="read the input volume")
no_write = traits.Bool(argstr="--no_write", desc="do not write output")
in_info = traits.Bool(argstr="--in_info", desc="display input info")
out_info = traits.Bool(argstr="--out_info", desc="display output info")
in_stats = traits.Bool(argstr="--in_stats", desc="display input stats")
out_stats = traits.Bool(argstr="--out_stats", desc="display output stats")
in_matrix = traits.Bool(argstr="--in_matrix", desc="display input matrix")
out_matrix = traits.Bool(argstr="--out_matrix", desc="display output matrix")
in_i_size = traits.Int(argstr="--in_i_size %d", desc="input i size")
in_j_size = traits.Int(argstr="--in_j_size %d", desc="input j size")
in_k_size = traits.Int(argstr="--in_k_size %d", desc="input k size")
force_ras = traits.Bool(
argstr="--force_ras_good", desc="use default when orientation info absent"
)
in_i_dir = traits.Tuple(
traits.Float,
traits.Float,
traits.Float,
argstr="--in_i_direction %f %f %f",
desc="<R direction> <A direction> <S direction>",
)
in_j_dir = traits.Tuple(
traits.Float,
traits.Float,
traits.Float,
argstr="--in_j_direction %f %f %f",
desc="<R direction> <A direction> <S direction>",
)
in_k_dir = traits.Tuple(
traits.Float,
traits.Float,
traits.Float,
argstr="--in_k_direction %f %f %f",
desc="<R direction> <A direction> <S direction>",
)
_orientations = [
"LAI",
"LIA",
"ALI",
"AIL",
"ILA",
"IAL",
"LAS",
"LSA",
"ALS",
"ASL",
"SLA",
"SAL",
"LPI",
"LIP",
"PLI",
"PIL",
"ILP",
"IPL",
"LPS",
"LSP",
"PLS",
"PSL",
"SLP",
"SPL",
"RAI",
"RIA",
"ARI",
"AIR",
"IRA",
"IAR",
"RAS",
"RSA",
"ARS",
"ASR",
"SRA",
"SAR",
"RPI",
"RIP",
"PRI",
"PIR",
"IRP",
"IPR",
"RPS",
"RSP",
"PRS",
"PSR",
"SRP",
"SPR",
]
# _orientations = [comb for comb in itertools.chain(*[[''.join(c) for c in itertools.permutations(s)] for s in [a+b+c for a in 'LR' for b in 'AP' for c in 'IS']])]
in_orientation = traits.Enum(
_orientations,
argstr="--in_orientation %s",
desc="specify the input orientation",
)
in_center = traits.List(
traits.Float,
maxlen=3,
argstr="--in_center %s",
desc="<R coordinate> <A coordinate> <S coordinate>",
)
sphinx = traits.Bool(argstr="--sphinx", desc="change orientation info to sphinx")
out_i_count = traits.Int(
argstr="--out_i_count %d", desc="some count ?? in i direction"
)
out_j_count = traits.Int(
argstr="--out_j_count %d", desc="some count ?? in j direction"
)
out_k_count = traits.Int(
argstr="--out_k_count %d", desc="some count ?? in k direction"
)
vox_size = traits.Tuple(
traits.Float,
traits.Float,
traits.Float,
argstr="-voxsize %f %f %f",
desc="<size_x> <size_y> <size_z> specify the size (mm) - useful for upsampling or downsampling",
)
out_i_size = traits.Int(argstr="--out_i_size %d", desc="output i size")
out_j_size = traits.Int(argstr="--out_j_size %d", desc="output j size")
out_k_size = traits.Int(argstr="--out_k_size %d", desc="output k size")
out_i_dir = traits.Tuple(
traits.Float,
traits.Float,
traits.Float,
argstr="--out_i_direction %f %f %f",
desc="<R direction> <A direction> <S direction>",
)
out_j_dir = traits.Tuple(
traits.Float,
traits.Float,
traits.Float,
argstr="--out_j_direction %f %f %f",
desc="<R direction> <A direction> <S direction>",
)
out_k_dir = traits.Tuple(
traits.Float,
traits.Float,
traits.Float,
argstr="--out_k_direction %f %f %f",
desc="<R direction> <A direction> <S direction>",
)
out_orientation = traits.Enum(
_orientations,
argstr="--out_orientation %s",
desc="specify the output orientation",
)
out_center = traits.Tuple(
traits.Float,
traits.Float,
traits.Float,
argstr="--out_center %f %f %f",
desc="<R coordinate> <A coordinate> <S coordinate>",
)
out_datatype = traits.Enum(
"uchar",
"short",
"int",
"float",
argstr="--out_data_type %s",
desc="output data type <uchar|short|int|float>",
)
resample_type = traits.Enum(
"interpolate",
"weighted",
"nearest",
"sinc",
"cubic",
argstr="--resample_type %s",
desc="<interpolate|weighted|nearest|sinc|cubic> (default is interpolate)",
)
no_scale = traits.Bool(argstr="--no_scale 1", desc="dont rescale values for COR")
no_change = traits.Bool(
argstr="--nochange", desc="don't change type of input to that of template"
)
tr = traits.Int(argstr="-tr %d", desc="TR in msec")
te = traits.Int(argstr="-te %d", desc="TE in msec")
ti = traits.Int(argstr="-ti %d", desc="TI in msec (note upper case flag)")
autoalign_matrix = File(
exists=True, argstr="--autoalign %s", desc="text file with autoalign matrix"
)
unwarp_gradient = traits.Bool(
argstr="--unwarp_gradient_nonlinearity", desc="unwarp gradient nonlinearity"
)
apply_transform = File(
exists=True, argstr="--apply_transform %s", desc="apply xfm file"
)
apply_inv_transform = File(
exists=True,
argstr="--apply_inverse_transform %s",
desc="apply inverse transformation xfm file",
)
devolve_transform = traits.Str(argstr="--devolvexfm %s", desc="subject id")
crop_center = traits.Tuple(
traits.Int,
traits.Int,
traits.Int,
argstr="--crop %d %d %d",
desc="<x> <y> <z> crop to 256 around center (x, y, z)",
)
crop_size = traits.Tuple(
traits.Int,
traits.Int,
traits.Int,
argstr="--cropsize %d %d %d",
desc="<dx> <dy> <dz> crop to size <dx, dy, dz>",
)
cut_ends = traits.Int(
argstr="--cutends %d", desc="remove ncut slices from the ends"
)
slice_crop = traits.Tuple(
traits.Int,
traits.Int,
argstr="--slice-crop %d %d",
desc="s_start s_end : keep slices s_start to s_end",
)
slice_reverse = traits.Bool(
argstr="--slice-reverse", desc="reverse order of slices, update vox2ras"
)
slice_bias = traits.Float(
argstr="--slice-bias %f", desc="apply half-cosine bias field"
)
fwhm = traits.Float(argstr="--fwhm %f", desc="smooth input volume by fwhm mm")
_filetypes = [
"cor",
"mgh",
"mgz",
"minc",
"analyze",
"analyze4d",
"spm",
"afni",
"brik",
"bshort",
"bfloat",
"sdt",
"outline",
"otl",
"gdf",
"nifti1",
"nii",
"niigz",
]
_infiletypes = ["ge", "gelx", "lx", "ximg", "siemens", "dicom", "siemens_dicom"]
in_type = traits.Enum(
_filetypes + _infiletypes, argstr="--in_type %s", desc="input file type"
)
out_type = traits.Enum(_filetypes, argstr="--out_type %s", desc="output file type")
ascii = traits.Bool(
argstr="--ascii", desc="save output as ascii col>row>slice>frame"
)
reorder = traits.Tuple(
traits.Int,
traits.Int,
traits.Int,
argstr="--reorder %d %d %d",
desc="olddim1 olddim2 olddim3",
)
invert_contrast = traits.Float(
argstr="--invert_contrast %f", desc="threshold for inversting contrast"
)
in_file = File(
exists=True,
mandatory=True,
position=-2,
argstr="--input_volume %s",
desc="File to read/convert",
)
out_file = File(
argstr="--output_volume %s",
position=-1,
genfile=True,
desc="output filename or True to generate one",
)
conform = traits.Bool(
argstr="--conform",
desc="conform to 1mm voxel size in coronal slice direction with 256^3 or more",
)
conform_min = traits.Bool(argstr="--conform_min", desc="conform to smallest size")
conform_size = traits.Float(
argstr="--conform_size %s", desc="conform to size_in_mm"
)
cw256 = traits.Bool(argstr="--cw256", desc="confrom to dimensions of 256^3")
parse_only = traits.Bool(argstr="--parse_only", desc="parse input only")
subject_name = traits.Str(argstr="--subject_name %s", desc="subject name ???")
reslice_like = File(
exists=True, argstr="--reslice_like %s", desc="reslice output to match file"
)
template_type = traits.Enum(
_filetypes + _infiletypes,
argstr="--template_type %s",
desc="template file type",
)
split = traits.Bool(
argstr="--split", desc="split output frames into separate output files."
)
frame = traits.Int(argstr="--frame %d", desc="keep only 0-based frame number")
midframe = traits.Bool(argstr="--mid-frame", desc="keep only the middle frame")
skip_n = traits.Int(argstr="--nskip %d", desc="skip the first n frames")
drop_n = traits.Int(argstr="--ndrop %d", desc="drop the last n frames")
frame_subsample = traits.Tuple(
traits.Int,
traits.Int,
traits.Int,
argstr="--fsubsample %d %d %d",
desc="start delta end : frame subsampling (end = -1 for end)",
)
in_scale = traits.Float(argstr="--scale %f", desc="input intensity scale factor")
out_scale = traits.Float(
argstr="--out-scale %d", desc="output intensity scale factor"
)
in_like = File(exists=True, argstr="--in_like %s", desc="input looks like")
fill_parcellation = traits.Bool(
argstr="--fill_parcellation", desc="fill parcellation"
)
smooth_parcellation = traits.Bool(
argstr="--smooth_parcellation", desc="smooth parcellation"
)
zero_outlines = traits.Bool(argstr="--zero_outlines", desc="zero outlines")
color_file = File(exists=True, argstr="--color_file %s", desc="color file")
no_translate = traits.Bool(argstr="--no_translate", desc="???")
status_file = File(argstr="--status %s", desc="status file for DICOM conversion")
sdcm_list = File(
exists=True, argstr="--sdcmlist %s", desc="list of DICOM files for conversion"
)
template_info = traits.Bool(
argstr="--template_info", desc="dump info about template"
)
crop_gdf = traits.Bool(argstr="--crop_gdf", desc="apply GDF cropping")
zero_ge_z_offset = traits.Bool(
argstr="--zero_ge_z_offset", desc="zero ge z offset ???"
)
class MRIConvertOutputSpec(TraitedSpec):
out_file = OutputMultiPath(File(exists=True), desc="converted output file")
class MRIConvert(FSCommand):
"""use fs mri_convert to manipulate files
.. note::
Adds niigz as an output type option
Examples
--------
>>> mc = MRIConvert()
>>> mc.inputs.in_file = 'structural.nii'
>>> mc.inputs.out_file = 'outfile.mgz'
>>> mc.inputs.out_type = 'mgz'
>>> mc.cmdline
'mri_convert --out_type mgz --input_volume structural.nii --output_volume outfile.mgz'
"""
_cmd = "mri_convert"
input_spec = MRIConvertInputSpec
output_spec = MRIConvertOutputSpec
filemap = dict(
cor="cor",
mgh="mgh",
mgz="mgz",
minc="mnc",
afni="brik",
brik="brik",
bshort="bshort",
spm="img",
analyze="img",
analyze4d="img",
bfloat="bfloat",
nifti1="img",
nii="nii",
niigz="nii.gz",
)
def _format_arg(self, name, spec, value):
if name in ["in_type", "out_type", "template_type"]:
if value == "niigz":
return spec.argstr % "nii"
return super(MRIConvert, self)._format_arg(name, spec, value)
def _get_outfilename(self):
outfile = self.inputs.out_file
if not isdefined(outfile):
if isdefined(self.inputs.out_type):
suffix = "_out." + self.filemap[self.inputs.out_type]
else:
suffix = "_out.nii.gz"
outfile = fname_presuffix(
self.inputs.in_file, newpath=os.getcwd(), suffix=suffix, use_ext=False
)
return os.path.abspath(outfile)
def _list_outputs(self):
outputs = self.output_spec().get()
outfile = self._get_outfilename()
if isdefined(self.inputs.split) and self.inputs.split:
size = load(self.inputs.in_file).shape
if len(size) == 3:
tp = 1
else:
tp = size[-1]
if outfile.endswith(".mgz"):
stem = outfile.split(".mgz")[0]
ext = ".mgz"
elif outfile.endswith(".nii.gz"):
stem = outfile.split(".nii.gz")[0]
ext = ".nii.gz"
else:
stem = ".".join(outfile.split(".")[:-1])
ext = "." + outfile.split(".")[-1]
outfile = []
for idx in range(0, tp):
outfile.append(stem + "%04d" % idx + ext)
if isdefined(self.inputs.out_type):
if self.inputs.out_type in ["spm", "analyze"]:
# generate all outputs
size = load(self.inputs.in_file).shape
if len(size) == 3:
tp = 1
else:
tp = size[-1]
# have to take care of all the frame manipulations
raise Exception(
"Not taking frame manipulations into account- please warn the developers"
)
outfiles = []
outfile = self._get_outfilename()
for i in range(tp):
outfiles.append(fname_presuffix(outfile, suffix="%03d" % (i + 1)))
outfile = outfiles
outputs["out_file"] = outfile
return outputs
def _gen_filename(self, name):
if name == "out_file":
return self._get_outfilename()
return None
class DICOMConvertInputSpec(FSTraitedSpec):
dicom_dir = Directory(
exists=True,
mandatory=True,
desc="dicom directory from which to convert dicom files",
)
base_output_dir = Directory(
mandatory=True, desc="directory in which subject directories are created"
)
subject_dir_template = traits.Str(
"S.%04d", usedefault=True, desc="template for subject directory name"
)
subject_id = traits.Any(desc="subject identifier to insert into template")
file_mapping = traits.List(
traits.Tuple(traits.Str, traits.Str),
desc="defines the output fields of interface",
)
out_type = traits.Enum(
"niigz",
MRIConvertInputSpec._filetypes,
usedefault=True,
desc="defines the type of output file produced",
)
dicom_info = File(
exists=True, desc="File containing summary information from mri_parse_sdcmdir"
)
seq_list = traits.List(
traits.Str,
requires=["dicom_info"],
desc="list of pulse sequence names to be converted.",
)
ignore_single_slice = traits.Bool(
requires=["dicom_info"], desc="ignore volumes containing a single slice"
)
class DICOMConvert(FSCommand):
"""use fs mri_convert to convert dicom files
Examples
--------
>>> from nipype.interfaces.freesurfer import DICOMConvert
>>> cvt = DICOMConvert()
>>> cvt.inputs.dicom_dir = 'dicomdir'
>>> cvt.inputs.file_mapping = [('nifti', '*.nii'), ('info', 'dicom*.txt'), ('dti', '*dti.bv*')]
"""
_cmd = "mri_convert"
input_spec = DICOMConvertInputSpec
def _get_dicomfiles(self):
"""validate fsl bet options
if set to None ignore
"""
return glob(os.path.abspath(os.path.join(self.inputs.dicom_dir, "*-1.dcm")))
def _get_outdir(self):
"""returns output directory"""
subjid = self.inputs.subject_id
if not isdefined(subjid):
path, fname = os.path.split(self._get_dicomfiles()[0])
subjid = int(fname.split("-")[0])
if isdefined(self.inputs.subject_dir_template):
subjid = self.inputs.subject_dir_template % subjid
basedir = self.inputs.base_output_dir
if not isdefined(basedir):
basedir = os.path.abspath(".")
outdir = os.path.abspath(os.path.join(basedir, subjid))
return outdir
def _get_runs(self):
"""Returns list of dicom series that should be converted.
Requires a dicom info summary file generated by ``DicomDirInfo``
"""
seq = np.genfromtxt(self.inputs.dicom_info, dtype=object)
runs = []
for s in seq:
if self.inputs.seq_list:
if self.inputs.ignore_single_slice:
if (int(s[8]) > 1) and any(
[s[12].startswith(sn) for sn in self.inputs.seq_list]
):
runs.append(int(s[2]))
else:
if any([s[12].startswith(sn) for sn in self.inputs.seq_list]):
runs.append(int(s[2]))
else:
runs.append(int(s[2]))
return runs
def _get_filelist(self, outdir):
"""Returns list of files to be converted"""
filemap = {}
for f in self._get_dicomfiles():
head, fname = os.path.split(f)
fname, ext = os.path.splitext(fname)
fileparts = fname.split("-")
runno = int(fileparts[1])
out_type = MRIConvert.filemap[self.inputs.out_type]
outfile = os.path.join(
outdir, ".".join(("%s-%02d" % (fileparts[0], runno), out_type))
)
filemap[runno] = (f, outfile)
if self.inputs.dicom_info:
files = [filemap[r] for r in self._get_runs()]
else:
files = [filemap[r] for r in list(filemap.keys())]
return files
@property
def cmdline(self):
""" `command` plus any arguments (args)
validates arguments and generates command line"""
self._check_mandatory_inputs()
outdir = self._get_outdir()
cmd = []
if not os.path.exists(outdir):
cmdstr = "python -c \"import os; os.makedirs('%s')\"" % outdir
cmd.extend([cmdstr])
infofile = os.path.join(outdir, "shortinfo.txt")
if not os.path.exists(infofile):
cmdstr = "dcmdir-info-mgh %s > %s" % (self.inputs.dicom_dir, infofile)
cmd.extend([cmdstr])
files = self._get_filelist(outdir)
for infile, outfile in files:
if not os.path.exists(outfile):
single_cmd = "%s%s %s %s" % (
self._cmd_prefix,
self.cmd,
infile,
os.path.join(outdir, outfile),
)
cmd.extend([single_cmd])
return "; ".join(cmd)
class ResampleInputSpec(FSTraitedSpec):
in_file = File(
exists=True,
argstr="-i %s",
mandatory=True,
desc="file to resample",
position=-2,
)
resampled_file = File(
argstr="-o %s", desc="output filename", genfile=True, position=-1
)
voxel_size = traits.Tuple(
traits.Float,
traits.Float,
traits.Float,
argstr="-vs %.2f %.2f %.2f",
desc="triplet of output voxel sizes",
mandatory=True,
)
class ResampleOutputSpec(TraitedSpec):
resampled_file = File(exists=True, desc="output filename")
class Resample(FSCommand):
"""Use FreeSurfer mri_convert to up or down-sample image files
Examples
--------
>>> from nipype.interfaces import freesurfer
>>> resampler = freesurfer.Resample()
>>> resampler.inputs.in_file = 'structural.nii'
>>> resampler.inputs.resampled_file = 'resampled.nii'
>>> resampler.inputs.voxel_size = (2.1, 2.1, 2.1)
>>> resampler.cmdline
'mri_convert -vs 2.10 2.10 2.10 -i structural.nii -o resampled.nii'
"""
_cmd = "mri_convert"
input_spec = ResampleInputSpec
output_spec = ResampleOutputSpec
def _get_outfilename(self):
if isdefined(self.inputs.resampled_file):
outfile = self.inputs.resampled_file
else:
outfile = fname_presuffix(
self.inputs.in_file, newpath=os.getcwd(), suffix="_resample"
)
return outfile
def _list_outputs(self):
outputs = self.output_spec().get()
outputs["resampled_file"] = self._get_outfilename()
return outputs
def _gen_filename(self, name):
if name == "resampled_file":
return self._get_outfilename()
return None
class ReconAllInputSpec(CommandLineInputSpec):
subject_id = traits.Str(
"recon_all", argstr="-subjid %s", desc="subject name", usedefault=True
)
directive = traits.Enum(
"all",
"autorecon1",
# autorecon2 variants
"autorecon2",
"autorecon2-volonly",
"autorecon2-perhemi",
"autorecon2-inflate1",
"autorecon2-cp",
"autorecon2-wm",
# autorecon3 variants
"autorecon3",
"autorecon3-T2pial",
# Mix of autorecon2 and autorecon3 steps
"autorecon-pial",
"autorecon-hemi",
# Not "multi-stage flags"
"localGI",
"qcache",
argstr="-%s",
desc="process directive",
usedefault=True,
position=0,
)
hemi = traits.Enum("lh", "rh", desc="hemisphere to process", argstr="-hemi %s")
T1_files = InputMultiPath(
File(exists=True), argstr="-i %s...", desc="name of T1 file to process"
)
T2_file = File(
exists=True,
argstr="-T2 %s",
min_ver="5.3.0",
desc="Convert T2 image to orig directory",
)
FLAIR_file = File(
exists=True,
argstr="-FLAIR %s",
min_ver="5.3.0",
desc="Convert FLAIR image to orig directory",
)
use_T2 = traits.Bool(
argstr="-T2pial",
min_ver="5.3.0",
xor=["use_FLAIR"],
desc="Use T2 image to refine the pial surface",
)
use_FLAIR = traits.Bool(
argstr="-FLAIRpial",
min_ver="5.3.0",
xor=["use_T2"],
desc="Use FLAIR image to refine the pial surface",
)
openmp = traits.Int(
argstr="-openmp %d", desc="Number of processors to use in parallel"
)
parallel = traits.Bool(argstr="-parallel", desc="Enable parallel execution")
hires = traits.Bool(
argstr="-hires",
min_ver="6.0.0",
desc="Conform to minimum voxel size (for voxels < 1mm)",
)
mprage = traits.Bool(
argstr="-mprage",
desc=(
"Assume scan parameters are MGH MP-RAGE "
"protocol, which produces darker gray matter"
),
)
big_ventricles = traits.Bool(
argstr="-bigventricles",
desc=("For use in subjects with enlarged " "ventricles"),
)
brainstem = traits.Bool(
argstr="-brainstem-structures", desc="Segment brainstem structures"
)
hippocampal_subfields_T1 = traits.Bool(
argstr="-hippocampal-subfields-T1",
min_ver="6.0.0",
desc="segment hippocampal subfields using input T1 scan",
)
hippocampal_subfields_T2 = traits.Tuple(
File(exists=True),
traits.Str(),
argstr="-hippocampal-subfields-T2 %s %s",
min_ver="6.0.0",
desc=(
"segment hippocampal subfields using T2 scan, identified by "
"ID (may be combined with hippocampal_subfields_T1)"
),
)
expert = File(
exists=True, argstr="-expert %s", desc="Set parameters using expert file"
)
xopts = traits.Enum(
"use",
"clean",
"overwrite",
argstr="-xopts-%s",
desc="Use, delete or overwrite existing expert options file",
)
subjects_dir = Directory(
exists=True,
argstr="-sd %s",
hash_files=False,
desc="path to subjects directory",
genfile=True,
)
flags = InputMultiPath(traits.Str, argstr="%s", desc="additional parameters")
# Expert options
talairach = traits.Str(desc="Flags to pass to talairach commands", xor=["expert"])
mri_normalize = traits.Str(
desc="Flags to pass to mri_normalize commands", xor=["expert"]
)
mri_watershed = traits.Str(
desc="Flags to pass to mri_watershed commands", xor=["expert"]
)
mri_em_register = traits.Str(
desc="Flags to pass to mri_em_register commands", xor=["expert"]
)
mri_ca_normalize = traits.Str(
desc="Flags to pass to mri_ca_normalize commands", xor=["expert"]
)
mri_ca_register = traits.Str(
desc="Flags to pass to mri_ca_register commands", xor=["expert"]
)
mri_remove_neck = traits.Str(
desc="Flags to pass to mri_remove_neck commands", xor=["expert"]
)
mri_ca_label = traits.Str(
desc="Flags to pass to mri_ca_label commands", xor=["expert"]
)
mri_segstats = traits.Str(
desc="Flags to pass to mri_segstats commands", xor=["expert"]
)
mri_mask = traits.Str(desc="Flags to pass to mri_mask commands", xor=["expert"])
mri_segment = traits.Str(
desc="Flags to pass to mri_segment commands", xor=["expert"]
)
mri_edit_wm_with_aseg = traits.Str(
desc="Flags to pass to mri_edit_wm_with_aseg commands", xor=["expert"]
)
mri_pretess = traits.Str(
desc="Flags to pass to mri_pretess commands", xor=["expert"]
)
mri_fill = traits.Str(desc="Flags to pass to mri_fill commands", xor=["expert"])
mri_tessellate = traits.Str(
desc="Flags to pass to mri_tessellate commands", xor=["expert"]
)
mris_smooth = traits.Str(
desc="Flags to pass to mri_smooth commands", xor=["expert"]
)
mris_inflate = traits.Str(
desc="Flags to pass to mri_inflate commands", xor=["expert"]
)
mris_sphere = traits.Str(
desc="Flags to pass to mris_sphere commands", xor=["expert"]
)
mris_fix_topology = traits.Str(
desc="Flags to pass to mris_fix_topology commands", xor=["expert"]
)
mris_make_surfaces = traits.Str(
desc="Flags to pass to mris_make_surfaces commands", xor=["expert"]
)
mris_surf2vol = traits.Str(
desc="Flags to pass to mris_surf2vol commands", xor=["expert"]
)
mris_register = traits.Str(
desc="Flags to pass to mris_register commands", xor=["expert"]
)
mrisp_paint = traits.Str(
desc="Flags to pass to mrisp_paint commands", xor=["expert"]
)
mris_ca_label = traits.Str(
desc="Flags to pass to mris_ca_label commands", xor=["expert"]
)
mris_anatomical_stats = traits.Str(
desc="Flags to pass to mris_anatomical_stats commands", xor=["expert"]
)
mri_aparc2aseg = traits.Str(
desc="Flags to pass to mri_aparc2aseg commands", xor=["expert"]
)