/
tensors.py
608 lines (517 loc) · 21.6 KB
/
tensors.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
# -*- 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:
import os.path as op
import numpy as np
from ... import logging
from ...utils.filemanip import split_filename
from ..base import (
CommandLineInputSpec,
CommandLine,
BaseInterface,
traits,
File,
TraitedSpec,
isdefined,
)
iflogger = logging.getLogger("nipype.interface")
class DWI2SphericalHarmonicsImageInputSpec(CommandLineInputSpec):
in_file = File(
exists=True,
argstr="%s",
mandatory=True,
position=-2,
desc="Diffusion-weighted images",
)
out_filename = File(genfile=True, argstr="%s", position=-1, desc="Output filename")
encoding_file = File(
exists=True,
argstr="-grad %s",
mandatory=True,
position=1,
desc="Gradient encoding, supplied as a 4xN text file with each line is in the format [ X Y Z b ], where [ X Y Z ] describe the direction of the applied gradient, and b gives the b-value in units (1000 s/mm^2). See FSL2MRTrix",
)
maximum_harmonic_order = traits.Float(
argstr="-lmax %s",
desc="set the maximum harmonic order for the output series. By default, the program will use the highest possible lmax given the number of diffusion-weighted images.",
)
normalise = traits.Bool(
argstr="-normalise", position=3, desc="normalise the DW signal to the b=0 image"
)
class DWI2SphericalHarmonicsImageOutputSpec(TraitedSpec):
spherical_harmonics_image = File(exists=True, desc="Spherical harmonics image")
class DWI2SphericalHarmonicsImage(CommandLine):
"""
Convert base diffusion-weighted images to their spherical harmonic representation.
This program outputs the spherical harmonic decomposition for the set measured signal attenuations.
The signal attenuations are calculated by identifying the b-zero images from the diffusion encoding supplied
(i.e. those with zero as the b-value), and dividing the remaining signals by the mean b-zero signal intensity.
The spherical harmonic decomposition is then calculated by least-squares linear fitting.
Note that this program makes use of implied symmetries in the diffusion profile.
First, the fact the signal attenuation profile is real implies that it has conjugate symmetry,
i.e. Y(l,-m) = Y(l,m)* (where * denotes the complex conjugate). Second, the diffusion profile should be
antipodally symmetric (i.e. S(x) = S(-x)), implying that all odd l components should be zero. Therefore,
this program only computes the even elements.
Note that the spherical harmonics equations used here differ slightly from those conventionally used,
in that the (-1)^m factor has been omitted. This should be taken into account in all subsequent calculations.
Each volume in the output image corresponds to a different spherical harmonic component, according to the following convention:
* [0] Y(0,0)
* [1] Im {Y(2,2)}
* [2] Im {Y(2,1)}
* [3] Y(2,0)
* [4] Re {Y(2,1)}
* [5] Re {Y(2,2)}
* [6] Im {Y(4,4)}
* [7] Im {Y(4,3)}
Example
-------
>>> import nipype.interfaces.mrtrix as mrt
>>> dwi2SH = mrt.DWI2SphericalHarmonicsImage()
>>> dwi2SH.inputs.in_file = 'diffusion.nii'
>>> dwi2SH.inputs.encoding_file = 'encoding.txt'
>>> dwi2SH.run() # doctest: +SKIP
"""
_cmd = "dwi2SH"
input_spec = DWI2SphericalHarmonicsImageInputSpec
output_spec = DWI2SphericalHarmonicsImageOutputSpec
def _list_outputs(self):
outputs = self.output_spec().get()
outputs["spherical_harmonics_image"] = self.inputs.out_filename
if not isdefined(outputs["spherical_harmonics_image"]):
outputs["spherical_harmonics_image"] = op.abspath(self._gen_outfilename())
else:
outputs["spherical_harmonics_image"] = op.abspath(
outputs["spherical_harmonics_image"]
)
return outputs
def _gen_filename(self, name):
if name == "out_filename":
return self._gen_outfilename()
else:
return None
def _gen_outfilename(self):
_, name, _ = split_filename(self.inputs.in_file)
return name + "_SH.mif"
class ConstrainedSphericalDeconvolutionInputSpec(CommandLineInputSpec):
in_file = File(
exists=True,
argstr="%s",
mandatory=True,
position=-3,
desc="diffusion-weighted image",
)
response_file = File(
exists=True,
argstr="%s",
mandatory=True,
position=-2,
desc="the diffusion-weighted signal response function for a single fibre population (see EstimateResponse)",
)
out_filename = File(genfile=True, argstr="%s", position=-1, desc="Output filename")
mask_image = File(
exists=True,
argstr="-mask %s",
position=2,
desc="only perform computation within the specified binary brain mask image",
)
encoding_file = File(
exists=True,
argstr="-grad %s",
position=1,
desc="Gradient encoding, supplied as a 4xN text file with each line is in the format [ X Y Z b ], where [ X Y Z ] describe the direction of the applied gradient, and b gives the b-value in units (1000 s/mm^2). See FSL2MRTrix",
)
filter_file = File(
exists=True,
argstr="-filter %s",
position=-2,
desc="a text file containing the filtering coefficients for each even harmonic order."
"the linear frequency filtering parameters used for the initial linear spherical deconvolution step (default = [ 1 1 1 0 0 ]).",
)
lambda_value = traits.Float(
argstr="-lambda %s",
desc="the regularisation parameter lambda that controls the strength of the constraint (default = 1.0).",
)
maximum_harmonic_order = traits.Int(
argstr="-lmax %s",
desc="set the maximum harmonic order for the output series. By default, the program will use the highest possible lmax given the number of diffusion-weighted images.",
)
threshold_value = traits.Float(
argstr="-threshold %s",
desc="the threshold below which the amplitude of the FOD is assumed to be zero, expressed as a fraction of the mean value of the initial FOD (default = 0.1)",
)
iterations = traits.Int(
argstr="-niter %s",
desc="the maximum number of iterations to perform for each voxel (default = 50)",
)
debug = traits.Bool(argstr="-debug", desc="Display debugging messages.")
directions_file = File(
exists=True,
argstr="-directions %s",
position=-2,
desc="a text file containing the [ el az ] pairs for the directions: Specify the directions over which to apply the non-negativity constraint (by default, the built-in 300 direction set is used)",
)
normalise = traits.Bool(
argstr="-normalise", position=3, desc="normalise the DW signal to the b=0 image"
)
class ConstrainedSphericalDeconvolutionOutputSpec(TraitedSpec):
spherical_harmonics_image = File(exists=True, desc="Spherical harmonics image")
class ConstrainedSphericalDeconvolution(CommandLine):
"""
Perform non-negativity constrained spherical deconvolution.
Note that this program makes use of implied symmetries in the diffusion profile.
First, the fact the signal attenuation profile is real implies that it has conjugate symmetry,
i.e. Y(l,-m) = Y(l,m)* (where * denotes the complex conjugate). Second, the diffusion profile should be
antipodally symmetric (i.e. S(x) = S(-x)), implying that all odd l components should be zero.
Therefore, this program only computes the even elements. Note that the spherical harmonics equations used here
differ slightly from those conventionally used, in that the (-1)^m factor has been omitted. This should be taken
into account in all subsequent calculations. Each volume in the output image corresponds to a different spherical
harmonic component, according to the following convention:
* [0] Y(0,0)
* [1] Im {Y(2,2)}
* [2] Im {Y(2,1)}
* [3] Y(2,0)
* [4] Re {Y(2,1)}
* [5] Re {Y(2,2)}
* [6] Im {Y(4,4)}
* [7] Im {Y(4,3)}
Example
-------
>>> import nipype.interfaces.mrtrix as mrt
>>> csdeconv = mrt.ConstrainedSphericalDeconvolution()
>>> csdeconv.inputs.in_file = 'dwi.mif'
>>> csdeconv.inputs.encoding_file = 'encoding.txt'
>>> csdeconv.run() # doctest: +SKIP
"""
_cmd = "csdeconv"
input_spec = ConstrainedSphericalDeconvolutionInputSpec
output_spec = ConstrainedSphericalDeconvolutionOutputSpec
def _list_outputs(self):
outputs = self.output_spec().get()
outputs["spherical_harmonics_image"] = self.inputs.out_filename
if not isdefined(outputs["spherical_harmonics_image"]):
outputs["spherical_harmonics_image"] = op.abspath(self._gen_outfilename())
else:
outputs["spherical_harmonics_image"] = op.abspath(
outputs["spherical_harmonics_image"]
)
return outputs
def _gen_filename(self, name):
if name == "out_filename":
return self._gen_outfilename()
else:
return None
def _gen_outfilename(self):
_, name, _ = split_filename(self.inputs.in_file)
return name + "_CSD.mif"
class EstimateResponseForSHInputSpec(CommandLineInputSpec):
in_file = File(
exists=True,
argstr="%s",
mandatory=True,
position=-3,
desc="Diffusion-weighted images",
)
mask_image = File(
exists=True,
mandatory=True,
argstr="%s",
position=-2,
desc="only perform computation within the specified binary brain mask image",
)
out_filename = File(genfile=True, argstr="%s", position=-1, desc="Output filename")
encoding_file = File(
exists=True,
argstr="-grad %s",
mandatory=True,
position=1,
desc="Gradient encoding, supplied as a 4xN text file with each line is in the format [ X Y Z b ], where [ X Y Z ] describe the direction of the applied gradient, and b gives the b-value in units (1000 s/mm^2). See FSL2MRTrix",
)
maximum_harmonic_order = traits.Int(
argstr="-lmax %s",
desc="set the maximum harmonic order for the output series. By default, the program will use the highest possible lmax given the number of diffusion-weighted images.",
)
normalise = traits.Bool(
argstr="-normalise", desc="normalise the DW signal to the b=0 image"
)
quiet = traits.Bool(
argstr="-quiet", desc="Do not display information messages or progress status."
)
debug = traits.Bool(argstr="-debug", desc="Display debugging messages.")
class EstimateResponseForSHOutputSpec(TraitedSpec):
response = File(exists=True, desc="Spherical harmonics image")
class EstimateResponseForSH(CommandLine):
"""
Estimates the fibre response function for use in spherical deconvolution.
Example
-------
>>> import nipype.interfaces.mrtrix as mrt
>>> estresp = mrt.EstimateResponseForSH()
>>> estresp.inputs.in_file = 'dwi.mif'
>>> estresp.inputs.mask_image = 'dwi_WMProb.mif'
>>> estresp.inputs.encoding_file = 'encoding.txt'
>>> estresp.run() # doctest: +SKIP
"""
_cmd = "estimate_response"
input_spec = EstimateResponseForSHInputSpec
output_spec = EstimateResponseForSHOutputSpec
def _list_outputs(self):
outputs = self.output_spec().get()
outputs["response"] = self.inputs.out_filename
if not isdefined(outputs["response"]):
outputs["response"] = op.abspath(self._gen_outfilename())
else:
outputs["response"] = op.abspath(outputs["response"])
return outputs
def _gen_filename(self, name):
if name == "out_filename":
return self._gen_outfilename()
else:
return None
def _gen_outfilename(self):
_, name, _ = split_filename(self.inputs.in_file)
return name + "_ER.txt"
def concat_files(bvec_file, bval_file, invert_x, invert_y, invert_z):
bvecs = np.loadtxt(bvec_file)
bvals = np.loadtxt(bval_file)
if np.shape(bvecs)[0] > np.shape(bvecs)[1]:
bvecs = np.transpose(bvecs)
if invert_x:
bvecs[0, :] = -bvecs[0, :]
iflogger.info("Inverting b-vectors in the x direction")
if invert_y:
bvecs[1, :] = -bvecs[1, :]
iflogger.info("Inverting b-vectors in the y direction")
if invert_z:
bvecs[2, :] = -bvecs[2, :]
iflogger.info("Inverting b-vectors in the z direction")
iflogger.info(np.shape(bvecs))
iflogger.info(np.shape(bvals))
encoding = np.transpose(np.vstack((bvecs, bvals)))
_, bvec, _ = split_filename(bvec_file)
_, bval, _ = split_filename(bval_file)
out_encoding_file = bvec + "_" + bval + ".txt"
np.savetxt(out_encoding_file, encoding)
return out_encoding_file
class FSL2MRTrixInputSpec(TraitedSpec):
bvec_file = File(
exists=True, mandatory=True, desc="FSL b-vectors file (3xN text file)"
)
bval_file = File(
exists=True, mandatory=True, desc="FSL b-values file (1xN text file)"
)
invert_x = traits.Bool(
False, usedefault=True, desc="Inverts the b-vectors along the x-axis"
)
invert_y = traits.Bool(
False, usedefault=True, desc="Inverts the b-vectors along the y-axis"
)
invert_z = traits.Bool(
False, usedefault=True, desc="Inverts the b-vectors along the z-axis"
)
out_encoding_file = File(genfile=True, desc="Output encoding filename")
class FSL2MRTrixOutputSpec(TraitedSpec):
encoding_file = File(
desc="The gradient encoding, supplied as a 4xN text file with each line is in the format [ X Y Z b ], where [ X Y Z ] describe the direction of the applied gradient"
"and b gives the b-value in units (1000 s/mm^2)."
)
class FSL2MRTrix(BaseInterface):
"""
Converts separate b-values and b-vectors from text files (FSL style) into a
4xN text file in which each line is in the format [ X Y Z b ], where [ X Y Z ]
describe the direction of the applied gradient, and b gives the
b-value in units (1000 s/mm^2).
Example
-------
>>> import nipype.interfaces.mrtrix as mrt
>>> fsl2mrtrix = mrt.FSL2MRTrix()
>>> fsl2mrtrix.inputs.bvec_file = 'bvecs'
>>> fsl2mrtrix.inputs.bval_file = 'bvals'
>>> fsl2mrtrix.inputs.invert_y = True
>>> fsl2mrtrix.run() # doctest: +SKIP
"""
input_spec = FSL2MRTrixInputSpec
output_spec = FSL2MRTrixOutputSpec
def _run_interface(self, runtime):
encoding = concat_files(
self.inputs.bvec_file,
self.inputs.bval_file,
self.inputs.invert_x,
self.inputs.invert_y,
self.inputs.invert_z,
)
return runtime
def _list_outputs(self):
outputs = self.output_spec().get()
outputs["encoding_file"] = op.abspath(self._gen_filename("out_encoding_file"))
return outputs
def _gen_filename(self, name):
if name == "out_encoding_file":
return self._gen_outfilename()
else:
return None
def _gen_outfilename(self):
_, bvec, _ = split_filename(self.inputs.bvec_file)
_, bval, _ = split_filename(self.inputs.bval_file)
return bvec + "_" + bval + ".txt"
class GenerateDirectionsInputSpec(CommandLineInputSpec):
num_dirs = traits.Int(
mandatory=True,
argstr="%s",
position=-2,
desc="the number of directions to generate.",
)
power = traits.Float(
argstr="-power %s", desc="specify exponent to use for repulsion power law."
)
niter = traits.Int(
argstr="-niter %s", desc="specify the maximum number of iterations to perform."
)
display_info = traits.Bool(argstr="-info", desc="Display information messages.")
quiet_display = traits.Bool(
argstr="-quiet", desc="do not display information messages or progress status."
)
display_debug = traits.Bool(argstr="-debug", desc="Display debugging messages.")
out_file = File(
name_source=["num_dirs"],
name_template="directions_%d.txt",
argstr="%s",
hash_files=False,
position=-1,
desc="the text file to write the directions to, as [ az el ] pairs.",
)
class GenerateDirectionsOutputSpec(TraitedSpec):
out_file = File(exists=True, desc="directions file")
class GenerateDirections(CommandLine):
"""
generate a set of directions evenly distributed over a hemisphere.
Example
-------
>>> import nipype.interfaces.mrtrix as mrt
>>> gendir = mrt.GenerateDirections()
>>> gendir.inputs.num_dirs = 300
>>> gendir.run() # doctest: +SKIP
"""
_cmd = "gendir"
input_spec = GenerateDirectionsInputSpec
output_spec = GenerateDirectionsOutputSpec
class FindShPeaksInputSpec(CommandLineInputSpec):
in_file = File(
exists=True,
argstr="%s",
mandatory=True,
position=-3,
desc="the input image of SH coefficients.",
)
directions_file = File(
exists=True,
argstr="%s",
mandatory=True,
position=-2,
desc="the set of directions to use as seeds for the peak finding",
)
peaks_image = File(
exists=True,
argstr="-peaks %s",
desc="the program will try to find the peaks that most closely match those in the image provided",
)
num_peaks = traits.Int(
argstr="-num %s", desc="the number of peaks to extract (default is 3)"
)
peak_directions = traits.List(
traits.Float,
argstr="-direction %s",
sep=" ",
minlen=2,
maxlen=2,
desc="phi theta. the direction of a peak to estimate. The algorithm will attempt to find the same number of peaks as have been specified using this option "
" phi: the azimuthal angle of the direction (in degrees). theta: the elevation angle of the direction (in degrees, from the vertical z-axis)",
)
peak_threshold = traits.Float(
argstr="-threshold %s",
desc="only peak amplitudes greater than the threshold will be considered",
)
display_info = traits.Bool(argstr="-info", desc="Display information messages.")
quiet_display = traits.Bool(
argstr="-quiet", desc="do not display information messages or progress status."
)
display_debug = traits.Bool(argstr="-debug", desc="Display debugging messages.")
out_file = File(
name_template="%s_peak_dirs.mif",
keep_extension=False,
argstr="%s",
hash_files=False,
position=-1,
desc="the output image. Each volume corresponds to the x, y & z component of each peak direction vector in turn",
name_source=["in_file"],
)
class FindShPeaksOutputSpec(TraitedSpec):
out_file = File(exists=True, desc="Peak directions image")
class FindShPeaks(CommandLine):
"""
identify the orientations of the N largest peaks of a SH profile
Example
-------
>>> import nipype.interfaces.mrtrix as mrt
>>> shpeaks = mrt.FindShPeaks()
>>> shpeaks.inputs.in_file = 'csd.mif'
>>> shpeaks.inputs.directions_file = 'dirs.txt'
>>> shpeaks.inputs.num_peaks = 2
>>> shpeaks.run() # doctest: +SKIP
"""
_cmd = "find_SH_peaks"
input_spec = FindShPeaksInputSpec
output_spec = FindShPeaksOutputSpec
class Directions2AmplitudeInputSpec(CommandLineInputSpec):
in_file = File(
exists=True,
argstr="%s",
mandatory=True,
position=-2,
desc="the input directions image. Each volume corresponds to the x, y & z component of each direction vector in turn.",
)
peaks_image = File(
exists=True,
argstr="-peaks %s",
desc="the program will try to find the peaks that most closely match those in the image provided",
)
num_peaks = traits.Int(
argstr="-num %s", desc="the number of peaks to extract (default is 3)"
)
peak_directions = traits.List(
traits.Float,
argstr="-direction %s",
sep=" ",
minlen=2,
maxlen=2,
desc="phi theta. the direction of a peak to estimate. The algorithm will attempt to find the same number of peaks as have been specified using this option "
" phi: the azimuthal angle of the direction (in degrees). theta: the elevation angle of the direction (in degrees, from the vertical z-axis)",
)
display_info = traits.Bool(argstr="-info", desc="Display information messages.")
quiet_display = traits.Bool(
argstr="-quiet", desc="do not display information messages or progress status."
)
display_debug = traits.Bool(argstr="-debug", desc="Display debugging messages.")
out_file = File(
name_template="%s_amplitudes.mif",
keep_extension=False,
argstr="%s",
hash_files=False,
position=-1,
desc="the output amplitudes image",
name_source=["in_file"],
)
class Directions2AmplitudeOutputSpec(TraitedSpec):
out_file = File(exists=True, desc="amplitudes image")
class Directions2Amplitude(CommandLine):
"""
convert directions image to amplitudes
Example
-------
>>> import nipype.interfaces.mrtrix as mrt
>>> amplitudes = mrt.Directions2Amplitude()
>>> amplitudes.inputs.in_file = 'peak_directions.mif'
>>> amplitudes.run() # doctest: +SKIP
"""
_cmd = "dir2amp"
input_spec = Directions2AmplitudeInputSpec
output_spec = Directions2AmplitudeOutputSpec