-
Notifications
You must be signed in to change notification settings - Fork 523
/
dti.py
1583 lines (1406 loc) · 51.7 KB
/
dti.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 warnings
from ...utils.filemanip import fname_presuffix, split_filename, copyfile
from ..base import (
TraitedSpec,
isdefined,
File,
Directory,
InputMultiPath,
OutputMultiPath,
traits,
)
from .base import FSLCommand, FSLCommandInputSpec, Info
class DTIFitInputSpec(FSLCommandInputSpec):
dwi = File(
exists=True,
desc="diffusion weighted image data file",
argstr="-k %s",
position=0,
mandatory=True,
)
base_name = traits.Str(
"dtifit_",
desc=("base_name that all output files " "will start with"),
argstr="-o %s",
position=1,
usedefault=True,
)
mask = File(
exists=True,
desc="bet binary mask file",
argstr="-m %s",
position=2,
mandatory=True,
)
bvecs = File(
exists=True, desc="b vectors file", argstr="-r %s", position=3, mandatory=True
)
bvals = File(
exists=True, desc="b values file", argstr="-b %s", position=4, mandatory=True
)
min_z = traits.Int(argstr="-z %d", desc="min z")
max_z = traits.Int(argstr="-Z %d", desc="max z")
min_y = traits.Int(argstr="-y %d", desc="min y")
max_y = traits.Int(argstr="-Y %d", desc="max y")
min_x = traits.Int(argstr="-x %d", desc="min x")
max_x = traits.Int(argstr="-X %d", desc="max x")
save_tensor = traits.Bool(
desc="save the elements of the tensor", argstr="--save_tensor"
)
sse = traits.Bool(desc="output sum of squared errors", argstr="--sse")
cni = File(exists=True, desc="input counfound regressors", argstr="--cni=%s")
little_bit = traits.Bool(
desc="only process small area of brain", argstr="--littlebit"
)
gradnonlin = File(
exists=True, argstr="--gradnonlin=%s", desc="gradient non linearities"
)
class DTIFitOutputSpec(TraitedSpec):
V1 = File(exists=True, desc="path/name of file with the 1st eigenvector")
V2 = File(exists=True, desc="path/name of file with the 2nd eigenvector")
V3 = File(exists=True, desc="path/name of file with the 3rd eigenvector")
L1 = File(exists=True, desc="path/name of file with the 1st eigenvalue")
L2 = File(exists=True, desc="path/name of file with the 2nd eigenvalue")
L3 = File(exists=True, desc="path/name of file with the 3rd eigenvalue")
MD = File(exists=True, desc="path/name of file with the mean diffusivity")
FA = File(exists=True, desc="path/name of file with the fractional anisotropy")
MO = File(exists=True, desc="path/name of file with the mode of anisotropy")
S0 = File(
exists=True,
desc=(
"path/name of file with the raw T2 signal with no " "diffusion weighting"
),
)
tensor = File(exists=True, desc="path/name of file with the 4D tensor volume")
sse = File(exists=True, desc="path/name of file with the summed squared error")
class DTIFit(FSLCommand):
"""Use FSL dtifit command for fitting a diffusion tensor model at each
voxel
Example
-------
>>> from nipype.interfaces import fsl
>>> dti = fsl.DTIFit()
>>> dti.inputs.dwi = 'diffusion.nii'
>>> dti.inputs.bvecs = 'bvecs'
>>> dti.inputs.bvals = 'bvals'
>>> dti.inputs.base_name = 'TP'
>>> dti.inputs.mask = 'mask.nii'
>>> dti.cmdline
'dtifit -k diffusion.nii -o TP -m mask.nii -r bvecs -b bvals'
"""
_cmd = "dtifit"
input_spec = DTIFitInputSpec
output_spec = DTIFitOutputSpec
def _list_outputs(self):
keys_to_ignore = {"outputtype", "environ", "args"}
# Optional output: Map output name to input flag
opt_output = {"tensor": self.inputs.save_tensor, "sse": self.inputs.sse}
# Ignore optional output, whose corresponding input-flag is not defined
# or set to False
for output, input_flag in opt_output.items():
if isdefined(input_flag) and input_flag:
# this is wanted output, do not ignore
continue
keys_to_ignore.add(output)
outputs = self.output_spec().get()
for k in set(outputs.keys()) - keys_to_ignore:
outputs[k] = self._gen_fname(self.inputs.base_name, suffix="_" + k)
return outputs
class FSLXCommandInputSpec(FSLCommandInputSpec):
dwi = File(
exists=True,
argstr="--data=%s",
mandatory=True,
desc="diffusion weighted image data file",
)
mask = File(
exists=True,
argstr="--mask=%s",
mandatory=True,
desc="brain binary mask file (i.e. from BET)",
)
bvecs = File(
exists=True, argstr="--bvecs=%s", mandatory=True, desc="b vectors file"
)
bvals = File(exists=True, argstr="--bvals=%s", mandatory=True, desc="b values file")
logdir = Directory(".", argstr="--logdir=%s", usedefault=True)
n_fibres = traits.Range(
usedefault=True,
low=1,
value=2,
argstr="--nfibres=%d",
desc=("Maximum number of fibres to fit in each voxel"),
mandatory=True,
)
model = traits.Enum(
1,
2,
3,
argstr="--model=%d",
desc=(
"use monoexponential (1, default, required for "
"single-shell) or multiexponential (2, multi-"
"shell) model"
),
)
fudge = traits.Int(argstr="--fudge=%d", desc="ARD fudge factor")
n_jumps = traits.Int(
5000,
usedefault=True,
argstr="--njumps=%d",
desc="Num of jumps to be made by MCMC",
)
burn_in = traits.Range(
low=0,
value=0,
usedefault=True,
argstr="--burnin=%d",
desc=("Total num of jumps at start of MCMC to be " "discarded"),
)
burn_in_no_ard = traits.Range(
low=0,
value=0,
usedefault=True,
argstr="--burnin_noard=%d",
desc=("num of burnin jumps before the ard is" " imposed"),
)
sample_every = traits.Range(
low=0,
value=1,
usedefault=True,
argstr="--sampleevery=%d",
desc="Num of jumps for each sample (MCMC)",
)
update_proposal_every = traits.Range(
low=1,
value=40,
usedefault=True,
argstr="--updateproposalevery=%d",
desc=("Num of jumps for each update " "to the proposal density std " "(MCMC)"),
)
seed = traits.Int(
argstr="--seed=%d", desc="seed for pseudo random number generator"
)
_xor_inputs1 = ("no_ard", "all_ard")
no_ard = traits.Bool(
argstr="--noard", xor=_xor_inputs1, desc="Turn ARD off on all fibres"
)
all_ard = traits.Bool(
argstr="--allard", xor=_xor_inputs1, desc="Turn ARD on on all fibres"
)
_xor_inputs2 = ("no_spat", "non_linear", "cnlinear")
no_spat = traits.Bool(
argstr="--nospat",
xor=_xor_inputs2,
desc="Initialise with tensor, not spatially",
)
non_linear = traits.Bool(
argstr="--nonlinear", xor=_xor_inputs2, desc="Initialise with nonlinear fitting"
)
cnlinear = traits.Bool(
argstr="--cnonlinear",
xor=_xor_inputs2,
desc=("Initialise with constrained nonlinear " "fitting"),
)
rician = traits.Bool(argstr="--rician", desc=("use Rician noise modeling"))
_xor_inputs3 = ["f0_noard", "f0_ard"]
f0_noard = traits.Bool(
argstr="--f0",
xor=_xor_inputs3,
desc=(
"Noise floor model: add to the model an "
"unattenuated signal compartment f0"
),
)
f0_ard = traits.Bool(
argstr="--f0 --ardf0",
xor=_xor_inputs3 + ["all_ard"],
desc=(
"Noise floor model: add to the model an "
"unattenuated signal compartment f0"
),
)
force_dir = traits.Bool(
True,
argstr="--forcedir",
usedefault=True,
desc=(
"use the actual directory name given "
"(do not add + to make a new directory)"
),
)
class FSLXCommandOutputSpec(TraitedSpec):
dyads = OutputMultiPath(
File(exists=True), desc=("Mean of PDD distribution" " in vector form.")
)
fsamples = OutputMultiPath(
File(exists=True), desc=("Samples from the " "distribution on f " "anisotropy")
)
mean_dsamples = File(exists=True, desc="Mean of distribution on diffusivity d")
mean_fsamples = OutputMultiPath(
File(exists=True), desc=("Mean of distribution on f " "anisotropy")
)
mean_S0samples = File(
exists=True, desc=("Mean of distribution on T2w" "baseline signal intensity S0")
)
mean_tausamples = File(
exists=True,
desc=("Mean of distribution on " "tau samples (only with rician " "noise)"),
)
phsamples = OutputMultiPath(File(exists=True), desc=("phi samples, per fiber"))
thsamples = OutputMultiPath(File(exists=True), desc=("theta samples, per fiber"))
class FSLXCommand(FSLCommand):
"""
Base support for ``xfibres`` and ``bedpostx``
"""
input_spec = FSLXCommandInputSpec
output_spec = FSLXCommandOutputSpec
def _run_interface(self, runtime):
self._out_dir = os.getcwd()
runtime = super(FSLXCommand, self)._run_interface(runtime)
if runtime.stderr:
self.raise_exception(runtime)
return runtime
def _list_outputs(self, out_dir=None):
outputs = self.output_spec().get()
n_fibres = self.inputs.n_fibres
if not out_dir:
if isdefined(self.inputs.logdir):
out_dir = os.path.abspath(self.inputs.logdir)
else:
out_dir = os.path.abspath("logdir")
multi_out = ["dyads", "fsamples", "mean_fsamples", "phsamples", "thsamples"]
single_out = ["mean_dsamples", "mean_S0samples"]
for k in single_out:
outputs[k] = self._gen_fname(k, cwd=out_dir)
if isdefined(self.inputs.rician) and self.inputs.rician:
outputs["mean_tausamples"] = self._gen_fname("mean_tausamples", cwd=out_dir)
for k in multi_out:
outputs[k] = []
for i in range(1, n_fibres + 1):
outputs["fsamples"].append(self._gen_fname("f%dsamples" % i, cwd=out_dir))
outputs["mean_fsamples"].append(
self._gen_fname("mean_f%dsamples" % i, cwd=out_dir)
)
for i in range(1, n_fibres + 1):
outputs["dyads"].append(self._gen_fname("dyads%d" % i, cwd=out_dir))
outputs["phsamples"].append(self._gen_fname("ph%dsamples" % i, cwd=out_dir))
outputs["thsamples"].append(self._gen_fname("th%dsamples" % i, cwd=out_dir))
return outputs
class BEDPOSTX5InputSpec(FSLXCommandInputSpec):
dwi = File(exists=True, desc="diffusion weighted image data file", mandatory=True)
mask = File(exists=True, desc="bet binary mask file", mandatory=True)
bvecs = File(exists=True, desc="b vectors file", mandatory=True)
bvals = File(exists=True, desc="b values file", mandatory=True)
logdir = Directory(argstr="--logdir=%s")
n_fibres = traits.Range(
usedefault=True,
low=1,
value=2,
argstr="-n %d",
desc=("Maximum number of fibres to fit in each voxel"),
mandatory=True,
)
model = traits.Enum(
1,
2,
3,
argstr="-model %d",
desc=(
"use monoexponential (1, default, required for "
"single-shell) or multiexponential (2, multi-"
"shell) model"
),
)
fudge = traits.Int(argstr="-w %d", desc="ARD fudge factor")
n_jumps = traits.Int(
5000, usedefault=True, argstr="-j %d", desc="Num of jumps to be made by MCMC"
)
burn_in = traits.Range(
low=0,
value=0,
usedefault=True,
argstr="-b %d",
desc=("Total num of jumps at start of MCMC to be " "discarded"),
)
sample_every = traits.Range(
low=0,
value=1,
usedefault=True,
argstr="-s %d",
desc="Num of jumps for each sample (MCMC)",
)
out_dir = Directory(
"bedpostx",
mandatory=True,
desc="output directory",
usedefault=True,
position=1,
argstr="%s",
)
gradnonlin = traits.Bool(
False, argstr="-g", desc=("consider gradient nonlinearities, " "default off")
)
grad_dev = File(exists=True, desc="grad_dev file, if gradnonlin, -g is True")
use_gpu = traits.Bool(False, desc="Use the GPU version of bedpostx")
class BEDPOSTX5OutputSpec(TraitedSpec):
mean_dsamples = File(exists=True, desc="Mean of distribution on diffusivity d")
mean_fsamples = OutputMultiPath(
File(exists=True), desc=("Mean of distribution on f " "anisotropy")
)
mean_S0samples = File(
exists=True, desc=("Mean of distribution on T2w" "baseline signal intensity S0")
)
mean_phsamples = OutputMultiPath(
File(exists=True), desc="Mean of distribution on phi"
)
mean_thsamples = OutputMultiPath(
File(exists=True), desc="Mean of distribution on theta"
)
merged_thsamples = OutputMultiPath(
File(exists=True), desc=("Samples from the distribution " "on theta")
)
merged_phsamples = OutputMultiPath(
File(exists=True), desc=("Samples from the distribution " "on phi")
)
merged_fsamples = OutputMultiPath(
File(exists=True),
desc=("Samples from the distribution on " "anisotropic volume fraction"),
)
dyads = OutputMultiPath(
File(exists=True), desc="Mean of PDD distribution in vector form."
)
dyads_dispersion = OutputMultiPath(File(exists=True), desc=("Dispersion"))
class BEDPOSTX5(FSLXCommand):
"""
BEDPOSTX stands for Bayesian Estimation of Diffusion Parameters Obtained
using Sampling Techniques. The X stands for modelling Crossing Fibres.
bedpostx runs Markov Chain Monte Carlo sampling to build up distributions
on diffusion parameters at each voxel. It creates all the files necessary
for running probabilistic tractography. For an overview of the modelling
carried out within bedpostx see this `technical report
<http://www.fmrib.ox.ac.uk/analysis/techrep/tr03tb1/tr03tb1/index.html>`_.
.. note:: Consider using
:func:`niflow.nipype1.workflows.fsl.dmri.create_bedpostx_pipeline` instead.
Example
-------
>>> from nipype.interfaces import fsl
>>> bedp = fsl.BEDPOSTX5(bvecs='bvecs', bvals='bvals', dwi='diffusion.nii',
... mask='mask.nii', n_fibres=1)
>>> bedp.cmdline
'bedpostx bedpostx -b 0 --burnin_noard=0 --forcedir -n 1 -j 5000 \
-s 1 --updateproposalevery=40'
"""
_cmd = "bedpostx"
_default_cmd = _cmd
input_spec = BEDPOSTX5InputSpec
output_spec = BEDPOSTX5OutputSpec
_can_resume = True
def __init__(self, **inputs):
super(BEDPOSTX5, self).__init__(**inputs)
self.inputs.on_trait_change(self._cuda_update, "use_gpu")
def _cuda_update(self):
if isdefined(self.inputs.use_gpu) and self.inputs.use_gpu:
self._cmd = "bedpostx_gpu"
else:
self._cmd = self._default_cmd
def _run_interface(self, runtime):
subjectdir = os.path.abspath(self.inputs.out_dir)
if not os.path.exists(subjectdir):
os.makedirs(subjectdir)
_, _, ext = split_filename(self.inputs.mask)
copyfile(self.inputs.mask, os.path.join(subjectdir, "nodif_brain_mask" + ext))
_, _, ext = split_filename(self.inputs.dwi)
copyfile(self.inputs.dwi, os.path.join(subjectdir, "data" + ext))
copyfile(self.inputs.bvals, os.path.join(subjectdir, "bvals"))
copyfile(self.inputs.bvecs, os.path.join(subjectdir, "bvecs"))
if isdefined(self.inputs.grad_dev):
_, _, ext = split_filename(self.inputs.grad_dev)
copyfile(self.inputs.grad_dev, os.path.join(subjectdir, "grad_dev" + ext))
retval = super(BEDPOSTX5, self)._run_interface(runtime)
self._out_dir = subjectdir + ".bedpostX"
return retval
def _list_outputs(self):
outputs = self.output_spec().get()
n_fibres = self.inputs.n_fibres
multi_out = [
"merged_thsamples",
"merged_fsamples",
"merged_phsamples",
"mean_phsamples",
"mean_thsamples",
"mean_fsamples",
"dyads_dispersion",
"dyads",
]
single_out = ["mean_dsamples", "mean_S0samples"]
for k in single_out:
outputs[k] = self._gen_fname(k, cwd=self._out_dir)
for k in multi_out:
outputs[k] = []
for i in range(1, n_fibres + 1):
outputs["merged_thsamples"].append(
self._gen_fname("merged_th%dsamples" % i, cwd=self._out_dir)
)
outputs["merged_fsamples"].append(
self._gen_fname("merged_f%dsamples" % i, cwd=self._out_dir)
)
outputs["merged_phsamples"].append(
self._gen_fname("merged_ph%dsamples" % i, cwd=self._out_dir)
)
outputs["mean_thsamples"].append(
self._gen_fname("mean_th%dsamples" % i, cwd=self._out_dir)
)
outputs["mean_phsamples"].append(
self._gen_fname("mean_ph%dsamples" % i, cwd=self._out_dir)
)
outputs["mean_fsamples"].append(
self._gen_fname("mean_f%dsamples" % i, cwd=self._out_dir)
)
outputs["dyads"].append(self._gen_fname("dyads%d" % i, cwd=self._out_dir))
outputs["dyads_dispersion"].append(
self._gen_fname("dyads%d_dispersion" % i, cwd=self._out_dir)
)
return outputs
class XFibres5InputSpec(FSLXCommandInputSpec):
gradnonlin = File(
exists=True,
argstr="--gradnonlin=%s",
desc="gradient file corresponding to slice",
)
class XFibres5(FSLXCommand):
"""
Perform model parameters estimation for local (voxelwise) diffusion
parameters
"""
_cmd = "xfibres"
input_spec = XFibres5InputSpec
output_spec = FSLXCommandOutputSpec
XFibres = XFibres5
BEDPOSTX = BEDPOSTX5
class ProbTrackXBaseInputSpec(FSLCommandInputSpec):
thsamples = InputMultiPath(File(exists=True), mandatory=True)
phsamples = InputMultiPath(File(exists=True), mandatory=True)
fsamples = InputMultiPath(File(exists=True), mandatory=True)
samples_base_name = traits.Str(
"merged",
desc=("the rootname/base_name for samples " "files"),
argstr="--samples=%s",
usedefault=True,
)
mask = File(
exists=True,
desc="bet binary mask file in diffusion space",
argstr="-m %s",
mandatory=True,
)
seed = traits.Either(
File(exists=True),
traits.List(File(exists=True)),
traits.List(traits.List(traits.Int(), minlen=3, maxlen=3)),
desc=("seed volume(s), or voxel(s) or freesurfer " "label file"),
argstr="--seed=%s",
mandatory=True,
)
target_masks = InputMultiPath(
File(exits=True),
desc=("list of target masks - required for " "seeds_to_targets classification"),
argstr="--targetmasks=%s",
)
waypoints = File(
exists=True,
desc=(
"waypoint mask or ascii list of waypoint masks - "
"only keep paths going through ALL the masks"
),
argstr="--waypoints=%s",
)
network = traits.Bool(
desc=(
"activate network mode - only keep paths "
"going through at least one seed mask "
"(required if multiple seed masks)"
),
argstr="--network",
)
seed_ref = File(
exists=True,
desc=(
"reference vol to define seed space in simple mode "
"- diffusion space assumed if absent"
),
argstr="--seedref=%s",
)
out_dir = Directory(
exists=True,
argstr="--dir=%s",
desc="directory to put the final volumes in",
genfile=True,
)
force_dir = traits.Bool(
True,
desc=(
"use the actual directory name given - i.e. "
"do not add + to make a new directory"
),
argstr="--forcedir",
usedefault=True,
)
opd = traits.Bool(
True, desc="outputs path distributions", argstr="--opd", usedefault=True
)
correct_path_distribution = traits.Bool(
desc=("correct path distribution " "for the length of the " "pathways"),
argstr="--pd",
)
os2t = traits.Bool(desc="Outputs seeds to targets", argstr="--os2t")
# paths_file = File('nipype_fdtpaths', usedefault=True, argstr='--out=%s',
# desc='produces an output file (default is fdt_paths)')
avoid_mp = File(
exists=True,
desc=("reject pathways passing through locations given by " "this mask"),
argstr="--avoid=%s",
)
stop_mask = File(
exists=True,
argstr="--stop=%s",
desc="stop tracking at locations given by this mask file",
)
xfm = File(
exists=True,
argstr="--xfm=%s",
desc=(
"transformation matrix taking seed space to DTI space "
"(either FLIRT matrix or FNIRT warp_field) - default is "
"identity"
),
)
inv_xfm = File(
argstr="--invxfm=%s",
desc=(
"transformation matrix taking DTI space to seed "
"space (compulsory when using a warp_field for "
"seeds_to_dti)"
),
)
n_samples = traits.Int(
5000,
argstr="--nsamples=%d",
desc="number of samples - default=5000",
usedefault=True,
)
n_steps = traits.Int(
argstr="--nsteps=%d", desc="number of steps per sample - default=2000"
)
dist_thresh = traits.Float(
argstr="--distthresh=%.3f",
desc=("discards samples shorter than this " "threshold (in mm - default=0)"),
)
c_thresh = traits.Float(
argstr="--cthr=%.3f", desc="curvature threshold - default=0.2"
)
sample_random_points = traits.Bool(
argstr="--sampvox", desc=("sample random points within " "seed voxels")
)
step_length = traits.Float(
argstr="--steplength=%.3f", desc="step_length in mm - default=0.5"
)
loop_check = traits.Bool(
argstr="--loopcheck",
desc=(
"perform loop_checks on paths - slower, "
"but allows lower curvature threshold"
),
)
use_anisotropy = traits.Bool(
argstr="--usef", desc="use anisotropy to constrain tracking"
)
rand_fib = traits.Enum(
0,
1,
2,
3,
argstr="--randfib=%d",
desc=(
"options: 0 - default, 1 - to randomly "
"sample initial fibres (with f > fibthresh), "
"2 - to sample in proportion fibres (with "
"f>fibthresh) to f, 3 - to sample ALL "
"populations at random (even if "
"f<fibthresh)"
),
)
fibst = traits.Int(
argstr="--fibst=%d",
desc=(
"force a starting fibre for tracking - "
"default=1, i.e. first fibre orientation. Only "
"works if randfib==0"
),
)
mod_euler = traits.Bool(argstr="--modeuler", desc="use modified euler streamlining")
random_seed = traits.Bool(argstr="--rseed", desc="random seed")
s2tastext = traits.Bool(
argstr="--s2tastext",
desc=(
"output seed-to-target counts as a text "
"file (useful when seeding from a mesh)"
),
)
verbose = traits.Enum(
0,
1,
2,
desc=("Verbose level, [0-2]. Level 2 is required to " "output particle files."),
argstr="--verbose=%d",
)
class ProbTrackXInputSpec(ProbTrackXBaseInputSpec):
mode = traits.Enum(
"simple",
"two_mask_symm",
"seedmask",
desc=(
"options: simple (single seed voxel), seedmask "
"(mask of seed voxels), twomask_symm (two bet "
"binary masks)"
),
argstr="--mode=%s",
genfile=True,
)
mask2 = File(
exists=True,
desc=("second bet binary mask (in diffusion space) in " "twomask_symm mode"),
argstr="--mask2=%s",
)
mesh = File(
exists=True,
desc="Freesurfer-type surface descriptor (in ascii format)",
argstr="--mesh=%s",
)
class ProbTrackXOutputSpec(TraitedSpec):
log = File(
exists=True, desc="path/name of a text record of the command that was run"
)
fdt_paths = OutputMultiPath(
File(exists=True),
desc=(
"path/name of a 3D image file "
"containing the output connectivity "
"distribution to the seed mask"
),
)
way_total = File(
exists=True,
desc=(
"path/name of a text file containing a single "
"number corresponding to the total number of "
"generated tracts that have not been rejected by "
"inclusion/exclusion mask criteria"
),
)
targets = traits.List(
File(exists=True), desc=("a list with all generated seeds_to_target " "files")
)
particle_files = traits.List(
File(exists=True),
desc=(
"Files describing all of the tract "
"samples. Generated only if verbose is "
"set to 2"
),
)
class ProbTrackX(FSLCommand):
""" Use FSL probtrackx for tractography on bedpostx results
Examples
--------
>>> from nipype.interfaces import fsl
>>> pbx = fsl.ProbTrackX(samples_base_name='merged', mask='mask.nii', \
seed='MASK_average_thal_right.nii', mode='seedmask', \
xfm='trans.mat', n_samples=3, n_steps=10, force_dir=True, opd=True, \
os2t=True, target_masks = ['targets_MASK1.nii', 'targets_MASK2.nii'], \
thsamples='merged_thsamples.nii', fsamples='merged_fsamples.nii', \
phsamples='merged_phsamples.nii', out_dir='.')
>>> pbx.cmdline
'probtrackx --forcedir -m mask.nii --mode=seedmask --nsamples=3 --nsteps=10 --opd --os2t --dir=. --samples=merged --seed=MASK_average_thal_right.nii --targetmasks=targets.txt --xfm=trans.mat'
"""
_cmd = "probtrackx"
input_spec = ProbTrackXInputSpec
output_spec = ProbTrackXOutputSpec
def __init__(self, **inputs):
warnings.warn(
("Deprecated: Please use create_bedpostx_pipeline " "instead"),
DeprecationWarning,
)
return super(ProbTrackX, self).__init__(**inputs)
def _run_interface(self, runtime):
for i in range(1, len(self.inputs.thsamples) + 1):
_, _, ext = split_filename(self.inputs.thsamples[i - 1])
copyfile(
self.inputs.thsamples[i - 1],
self.inputs.samples_base_name + "_th%dsamples" % i + ext,
copy=False,
)
_, _, ext = split_filename(self.inputs.thsamples[i - 1])
copyfile(
self.inputs.phsamples[i - 1],
self.inputs.samples_base_name + "_ph%dsamples" % i + ext,
copy=False,
)
_, _, ext = split_filename(self.inputs.thsamples[i - 1])
copyfile(
self.inputs.fsamples[i - 1],
self.inputs.samples_base_name + "_f%dsamples" % i + ext,
copy=False,
)
if isdefined(self.inputs.target_masks):
f = open("targets.txt", "w")
for target in self.inputs.target_masks:
f.write("%s\n" % target)
f.close()
if isinstance(self.inputs.seed, list):
f = open("seeds.txt", "w")
for seed in self.inputs.seed:
if isinstance(seed, list):
f.write("%s\n" % (" ".join([str(s) for s in seed])))
else:
f.write("%s\n" % seed)
f.close()
runtime = super(ProbTrackX, self)._run_interface(runtime)
if runtime.stderr:
self.raise_exception(runtime)
return runtime
def _format_arg(self, name, spec, value):
if name == "target_masks" and isdefined(value):
fname = "targets.txt"
return super(ProbTrackX, self)._format_arg(name, spec, [fname])
elif name == "seed" and isinstance(value, list):
fname = "seeds.txt"
return super(ProbTrackX, self)._format_arg(name, spec, fname)
else:
return super(ProbTrackX, self)._format_arg(name, spec, value)
def _list_outputs(self):
outputs = self.output_spec().get()
if not isdefined(self.inputs.out_dir):
out_dir = self._gen_filename("out_dir")
else:
out_dir = self.inputs.out_dir
outputs["log"] = os.path.abspath(os.path.join(out_dir, "probtrackx.log"))
# utputs['way_total'] = os.path.abspath(os.path.join(out_dir,
# 'waytotal'))
if isdefined(self.inputs.opd is True):
if isinstance(self.inputs.seed, list) and isinstance(
self.inputs.seed[0], list
):
outputs["fdt_paths"] = []
for seed in self.inputs.seed:
outputs["fdt_paths"].append(
os.path.abspath(
self._gen_fname(
("fdt_paths_%s" % ("_".join([str(s) for s in seed]))),
cwd=out_dir,
suffix="",
)
)
)
else:
outputs["fdt_paths"] = os.path.abspath(
self._gen_fname("fdt_paths", cwd=out_dir, suffix="")
)
# handle seeds-to-target output files
if isdefined(self.inputs.target_masks):
outputs["targets"] = []
for target in self.inputs.target_masks:
outputs["targets"].append(
os.path.abspath(
self._gen_fname(
"seeds_to_" + os.path.split(target)[1],
cwd=out_dir,
suffix="",
)
)
)
if isdefined(self.inputs.verbose) and self.inputs.verbose == 2:
outputs["particle_files"] = [
os.path.abspath(os.path.join(out_dir, "particle%d" % i))
for i in range(self.inputs.n_samples)
]
return outputs
def _gen_filename(self, name):
if name == "out_dir":
return os.getcwd()
elif name == "mode":
if isinstance(self.inputs.seed, list) and isinstance(
self.inputs.seed[0], list
):
return "simple"
else:
return "seedmask"
class ProbTrackX2InputSpec(ProbTrackXBaseInputSpec):
simple = traits.Bool(
desc=(
"rack from a list of voxels (seed must be a " "ASCII list of coordinates)"
),
argstr="--simple",
)
fopd = File(
exists=True,
desc="Other mask for binning tract distribution",
argstr="--fopd=%s",
)
waycond = traits.Enum(
"OR",
"AND",
argstr="--waycond=%s",
desc=('Waypoint condition. Either "AND" (default) ' 'or "OR"'),
)
wayorder = traits.Bool(
desc=(
"Reject streamlines that do not hit "
"waypoints in given order. Only valid if "
"waycond=AND"
),
argstr="--wayorder",
)
onewaycondition = traits.Bool(
desc=("Apply waypoint conditions to each " "half tract separately"),
argstr="--onewaycondition",
)
omatrix1 = traits.Bool(
desc="Output matrix1 - SeedToSeed Connectivity", argstr="--omatrix1"
)
distthresh1 = traits.Float(
argstr="--distthresh1=%.3f",
desc=(
"Discards samples (in matrix1) shorter "
"than this threshold (in mm - "
"default=0)"
),
)
omatrix2 = traits.Bool(
desc="Output matrix2 - SeedToLowResMask",
argstr="--omatrix2",
requires=["target2"],
)
target2 = File(
exists=True,
desc=(
"Low resolution binary brain mask for storing "
"connectivity distribution in matrix2 mode"
),
argstr="--target2=%s",
)
omatrix3 = traits.Bool(
desc="Output matrix3 (NxN connectivity matrix)",
argstr="--omatrix3",
requires=["target3", "lrtarget3"],
)
target3 = File(
exists=True,
desc=("Mask used for NxN connectivity matrix (or Nxn if " "lrtarget3 is set)"),
argstr="--target3=%s",
)
lrtarget3 = File(
exists=True,
desc="Column-space mask used for Nxn connectivity matrix",