-
Notifications
You must be signed in to change notification settings - Fork 437
/
dti.py
executable file
·2344 lines (1858 loc) · 71.5 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
#!/usr/bin/python
"""
Classes and functions for fitting tensors.
"""
import functools
import warnings
import numpy as np
import scipy.optimize as opt
from dipy.core.geometry import vector_norm
from dipy.core.gradients import gradient_table
from dipy.core.onetime import auto_attr
from dipy.data import get_sphere
from dipy.reconst.base import ReconstModel
from dipy.reconst.vec_val_sum import vec_val_vect
from dipy.testing.decorators import warning_for_keywords
from dipy.utils.volume import adjacency_calc
MIN_POSITIVE_SIGNAL = 0.0001
ols_resort_msg = "Resorted to OLS solution in some voxels"
@warning_for_keywords()
def _roll_evals(evals, *, axis=-1):
"""Check evals shape.
Helper function to check that the evals provided to functions calculating
tensor statistics have the right shape
Parameters
----------
evals : array-like
Eigenvalues of a diffusion tensor. shape should be (...,3).
axis : int, optional
The axis of the array which contains the 3 eigenvals. Default: -1
Returns
-------
evals : array-like
Eigenvalues of a diffusion tensor, rolled so that the 3 eigenvals are
the last axis.
"""
if evals.shape[-1] != 3:
msg = f"Expecting 3 eigenvalues, got {evals.shape[-1]}"
raise ValueError(msg)
evals = np.rollaxis(evals, axis)
return evals
@warning_for_keywords()
def fractional_anisotropy(evals, *, axis=-1):
r"""Return Fractional anisotropy (FA) of a diffusion tensor.
Parameters
----------
evals : array-like
Eigenvalues of a diffusion tensor.
axis : int, optional
Axis of `evals` which contains 3 eigenvalues.
Returns
-------
fa : array
Calculated FA. Range is 0 <= FA <= 1.
Notes
-----
FA is calculated using the following equation:
.. math::
FA = \sqrt{\frac{1}{2}\frac{(\lambda_1-\lambda_2)^2+(\lambda_1-
\lambda_3)^2+(\lambda_2-\lambda_3)^2}{\lambda_1^2+
\lambda_2^2+\lambda_3^2}}
"""
evals = _roll_evals(evals, axis=axis)
# Make sure not to get nans
all_zero = (evals == 0).all(axis=0)
ev1, ev2, ev3 = evals
fa = np.sqrt(
0.5
* ((ev1 - ev2) ** 2 + (ev2 - ev3) ** 2 + (ev3 - ev1) ** 2)
/ ((evals * evals).sum(0) + all_zero)
)
return fa
@warning_for_keywords()
def geodesic_anisotropy(evals, *, axis=-1):
r"""
Geodesic anisotropy (GA) of a diffusion tensor.
Parameters
----------
evals : array-like
Eigenvalues of a diffusion tensor.
axis : int, optional
Axis of `evals` which contains 3 eigenvalues.
Returns
-------
ga : array
Calculated GA. In the range 0 to +infinity
Notes
-----
GA is calculated using the following equation given in
:footcite:p:`Batchelor2005`:
.. math::
GA = \sqrt{\sum_{i=1}^3
\log^2{\left ( \lambda_i/<\mathbf{D}> \right )}},
\quad \textrm{where} \quad <\mathbf{D}> =
(\lambda_1\lambda_2\lambda_3)^{1/3}
Note that the notation, $<D>$, is often used as the mean diffusivity (MD)
of the diffusion tensor and can lead to confusions in the literature
(see :footcite:p:`Batchelor2005` versus :footcite:p:`Correia2011b` versus
:footcite:p:`Lee2008` for example). :footcite:p:`Correia2011b` defines
geodesic anisotropy (GA) with $<D>$ as the MD in the denominator of the
sum. This is wrong. The original paper :footcite:p:`Batchelor2005` defines
GA with $<D> = det(D)^{1/3}$, as the isotropic part of the distance. This
might be an explanation for the confusion. The isotropic part of the
diffusion tensor in Euclidean space is the MD whereas the isotropic part of
the tensor in log-Euclidean space is $det(D)^{1/3}$. The Appendix of
:footcite:p:`Batchelor2005` and log-Euclidean derivations from
:footcite:p:`Lee2008` are clear on this. Hence, all that to say that
$<D> = det(D)^{1/3}$ here for the GA definition and not MD.
See also :footcite:p:`Arsigny2006`.
References
----------
.. footbibliography::
"""
evals = _roll_evals(evals, axis=axis)
ev1, ev2, ev3 = evals
log1 = np.zeros(ev1.shape)
log2 = np.zeros(ev1.shape)
log3 = np.zeros(ev1.shape)
idx = np.nonzero(ev1)
# this is the definition in :footcite:p:`Batchelor2005`
detD = np.power(ev1 * ev2 * ev3, 1 / 3.0)
log1[idx] = np.log(ev1[idx] / detD[idx])
log2[idx] = np.log(ev2[idx] / detD[idx])
log3[idx] = np.log(ev3[idx] / detD[idx])
ga = np.sqrt(log1**2 + log2**2 + log3**2)
return ga
@warning_for_keywords()
def mean_diffusivity(evals, *, axis=-1):
r"""
Mean Diffusivity (MD) of a diffusion tensor.
Parameters
----------
evals : array-like
Eigenvalues of a diffusion tensor.
axis : int, optional
Axis of `evals` which contains 3 eigenvalues.
Returns
-------
md : array
Calculated MD.
Notes
-----
MD is calculated with the following equation:
.. math::
MD = \frac{\lambda_1 + \lambda_2 + \lambda_3}{3}
"""
evals = _roll_evals(evals, axis=axis)
return evals.mean(0)
@warning_for_keywords()
def axial_diffusivity(evals, *, axis=-1):
r"""
Axial Diffusivity (AD) of a diffusion tensor.
Also called parallel diffusivity.
Parameters
----------
evals : array-like
Eigenvalues of a diffusion tensor, must be sorted in descending order
along `axis`.
axis : int, optional
Axis of `evals` which contains 3 eigenvalues.
Returns
-------
ad : array
Calculated AD.
Notes
-----
AD is calculated with the following equation:
.. math::
AD = \lambda_1
"""
evals = _roll_evals(evals, axis=axis)
ev1, ev2, ev3 = evals
return ev1
@warning_for_keywords()
def radial_diffusivity(evals, *, axis=-1):
r"""
Radial Diffusivity (RD) of a diffusion tensor.
Also called perpendicular diffusivity.
Parameters
----------
evals : array-like
Eigenvalues of a diffusion tensor, must be sorted in descending order
along `axis`.
axis : int, optional
Axis of `evals` which contains 3 eigenvalues.
Returns
-------
rd : array
Calculated RD.
Notes
-----
RD is calculated with the following equation:
.. math::
RD = \frac{\lambda_2 + \lambda_3}{2}
"""
evals = _roll_evals(evals, axis=axis)
return evals[1:].mean(0)
@warning_for_keywords()
def trace(evals, *, axis=-1):
r"""
Trace of a diffusion tensor.
Parameters
----------
evals : array-like
Eigenvalues of a diffusion tensor.
axis : int, optional
Axis of `evals` which contains 3 eigenvalues.
Returns
-------
trace : array
Calculated trace of the diffusion tensor.
Notes
-----
Trace is calculated with the following equation:
.. math::
Trace = \lambda_1 + \lambda_2 + \lambda_3
"""
evals = _roll_evals(evals, axis=axis)
return evals.sum(0)
def color_fa(fa, evecs):
r"""Color fractional anisotropy of diffusion tensor
Parameters
----------
fa : array-like
Array of the fractional anisotropy (can be 1D, 2D or 3D)
evecs : array-like
eigen vectors from the tensor model
Returns
-------
rgb : Array with 3 channels for each color as the last dimension.
Colormap of the FA with red for the x value, y for the green
value and z for the blue value.
Notes
-----
It is computed from the clipped FA between 0 and 1 using the following
formula
.. math::
rgb = abs(max(\vec{e})) \times fa
"""
if (fa.shape != evecs[..., 0, 0].shape) or ((3, 3) != evecs.shape[-2:]):
raise ValueError("Wrong number of dimensions for evecs")
return np.abs(evecs[..., 0]) * np.clip(fa, 0, 1)[..., None]
# The following are used to calculate the tensor mode:
def determinant(q_form):
"""
The determinant of a tensor, given in quadratic form
Parameters
----------
q_form : ndarray
The quadratic form of a tensor, or an array with quadratic forms of
tensors. Should be of shape (x, y, z, 3, 3) or (n, 3, 3) or (3, 3).
Returns
-------
det : array
The determinant of the tensor in each spatial coordinate
"""
# Following the conventions used here:
# https://en.wikipedia.org/wiki/Determinant
aei = q_form[..., 0, 0] * q_form[..., 1, 1] * q_form[..., 2, 2]
bfg = q_form[..., 0, 1] * q_form[..., 1, 2] * q_form[..., 2, 0]
cdh = q_form[..., 0, 2] * q_form[..., 1, 0] * q_form[..., 2, 1]
ceg = q_form[..., 0, 2] * q_form[..., 1, 1] * q_form[..., 2, 0]
bdi = q_form[..., 0, 1] * q_form[..., 1, 0] * q_form[..., 2, 2]
afh = q_form[..., 0, 0] * q_form[..., 1, 2] * q_form[..., 2, 1]
return aei + bfg + cdh - ceg - bdi - afh
def isotropic(q_form):
r"""
Calculate the isotropic part of the tensor.
See :footcite:p:`Ennis2006` for further details about the method.
Parameters
----------
q_form : ndarray
The quadratic form of a tensor, or an array with quadratic forms of
tensors. Should be of shape (x,y,z,3,3) or (n, 3, 3) or (3,3).
Returns
-------
A_hat: ndarray
The isotropic part of the tensor in each spatial coordinate
Notes
-----
The isotropic part of a tensor is defined as (equations 3-5 of
:footcite:p:`Ennis2006`):
.. math::
\bar{A} = \frac{1}{2} tr(A) I
References
----------
.. footbibliography::
"""
tr_A = q_form[..., 0, 0] + q_form[..., 1, 1] + q_form[..., 2, 2]
my_I = np.eye(3)
tr_AI = tr_A.reshape(tr_A.shape + (1, 1)) * my_I
return (1 / 3.0) * tr_AI
def deviatoric(q_form):
r"""
Calculate the deviatoric (anisotropic) part of the tensor.
See :footcite:p:`Ennis2006` for further details about the method.
Parameters
----------
q_form : ndarray
The quadratic form of a tensor, or an array with quadratic forms of
tensors. Should be of shape (x,y,z,3,3) or (n, 3, 3) or (3,3).
Returns
-------
A_squiggle : ndarray
The deviatoric part of the tensor in each spatial coordinate.
Notes
-----
The deviatoric part of the tensor is defined as (equations 3-5 in
:footcite:p:`Ennis2006`):
.. math::
\widetilde{A} = A - \bar{A}
Where $A$ is the tensor quadratic form and $\bar{A}$ is the anisotropic
part of the tensor.
References
----------
.. footbibliography::
"""
A_squiggle = q_form - isotropic(q_form)
return A_squiggle
def norm(q_form):
r"""
Calculate the Frobenius norm of a tensor quadratic form
Parameters
----------
q_form: ndarray
The quadratic form of a tensor, or an array with quadratic forms of
tensors. Should be of shape (x,y,z,3,3) or (n, 3, 3) or (3,3).
Returns
-------
norm : ndarray
The Frobenius norm of the 3,3 tensor q_form in each spatial
coordinate.
Notes
-----
The Frobenius norm is defined as:
.. math::
||A||_F = [\sum_{i,j} abs(a_{i,j})^2]^{1/2}
See Also
--------
np.linalg.norm
"""
return np.sqrt(np.sum(np.sum(np.abs(q_form**2), -1), -1))
def mode(q_form):
r"""
Mode (MO) of a diffusion tensor.
See :footcite:p:`Ennis2006` for further details about the method.
Parameters
----------
q_form : ndarray
The quadratic form of a tensor, or an array with quadratic forms of
tensors. Should be of shape (x, y, z, 3, 3) or (n, 3, 3) or (3, 3).
Returns
-------
mode : array
Calculated tensor mode in each spatial coordinate.
Notes
-----
Mode ranges between -1 (planar anisotropy) and +1 (linear anisotropy)
with 0 representing isotropy. Mode is calculated with the following
equation (equation 9 in :footcite:p:`Ennis2006`):
.. math::
Mode = 3*\sqrt{6}*det(\widetilde{A}/norm(\widetilde{A}))
Where $\widetilde{A}$ is the deviatoric part of the tensor quadratic form.
References
----------
.. footbibliography::
"""
A_squiggle = deviatoric(q_form)
A_s_norm = norm(A_squiggle)
mode = np.zeros_like(A_s_norm)
nonzero = A_s_norm != 0
A_squiggle_nonzero = A_squiggle[nonzero]
# Add two dims for the (3,3), so that it can broadcast on A_squiggle
A_s_norm_nonzero = A_s_norm[nonzero].reshape(-1, 1, 1)
mode_nonzero = 3 * np.sqrt(6) * determinant(A_squiggle_nonzero / A_s_norm_nonzero)
mode[nonzero] = mode_nonzero
return mode
@warning_for_keywords()
def linearity(evals, *, axis=-1):
r"""
The linearity of the tensor.
See :footcite:p:`Westin1997` for further details about the method.
Parameters
----------
evals : array-like
Eigenvalues of a diffusion tensor.
axis : int, optional
Axis of `evals` which contains 3 eigenvalues.
Returns
-------
linearity : array
Calculated linearity of the diffusion tensor.
Notes
-----
Linearity is calculated with the following equation:
.. math::
Linearity = \frac{\lambda_1-\lambda_2}{\lambda_1+\lambda_2+\lambda_3}
References
----------
.. footbibliography::
"""
evals = _roll_evals(evals, axis=axis)
ev1, ev2, ev3 = evals
return (ev1 - ev2) / evals.sum(0)
@warning_for_keywords()
def planarity(evals, *, axis=-1):
r"""
The planarity of the tensor.
See :footcite:p:`Westin1997` for further details about the method.
Parameters
----------
evals : array-like
Eigenvalues of a diffusion tensor.
axis : int, optional
Axis of `evals` which contains 3 eigenvalues.
Returns
-------
linearity : array
Calculated linearity of the diffusion tensor.
Notes
-----
Planarity is calculated with the following equation:
.. math::
Planarity =
\frac{2 (\lambda_2-\lambda_3)}{\lambda_1+\lambda_2+\lambda_3}
References
----------
.. footbibliography::
"""
evals = _roll_evals(evals, axis=axis)
ev1, ev2, ev3 = evals
return 2 * (ev2 - ev3) / evals.sum(0)
@warning_for_keywords()
def sphericity(evals, *, axis=-1):
r"""
The sphericity of the tensor.
See :footcite:p:`Westin1997` for further details about the method.
Parameters
----------
evals : array-like
Eigenvalues of a diffusion tensor.
axis : int, optional
Axis of `evals` which contains 3 eigenvalues.
Returns
-------
sphericity : array
Calculated sphericity of the diffusion tensor.
Notes
-----
Sphericity is calculated with the following equation:
.. math::
Sphericity = \frac{3 \lambda_3)}{\lambda_1+\lambda_2+\lambda_3}
References
----------
.. footbibliography::
"""
evals = _roll_evals(evals, axis=axis)
ev1, ev2, ev3 = evals
return (3 * ev3) / evals.sum(0)
def apparent_diffusion_coef(q_form, sphere):
r"""
Calculate the apparent diffusion coefficient (ADC) in each direction of a
sphere.
Parameters
----------
q_form : ndarray
The quadratic form of a tensor, or an array with quadratic forms of
tensors. Should be of shape (..., 3, 3)
sphere : a Sphere class instance
The ADC will be calculated for each of the vertices in the sphere
Notes
-----
The calculation of ADC, relies on the following relationship:
.. math::
ADC = \vec{b} Q \vec{b}^T
Where Q is the quadratic form of the tensor.
"""
bvecs = sphere.vertices
bvals = np.ones(bvecs.shape[0])
gtab = gradient_table(bvals, bvecs=bvecs)
D = design_matrix(gtab)[:, :6]
return -np.dot(lower_triangular(q_form), D.T)
def tensor_prediction(dti_params, gtab, S0):
r"""
Predict a signal given tensor parameters.
Parameters
----------
dti_params : ndarray
Tensor parameters. The last dimension should have 12 tensor
parameters: 3 eigenvalues, followed by the 3 corresponding
eigenvectors.
gtab : a GradientTable class instance
The gradient table for this prediction
S0 : float or ndarray
The non diffusion-weighted signal in every voxel, or across all
voxels. Default: 1
Notes
-----
The predicted signal is given by:
.. math::
S(\theta, b) = S_0 * e^{-b ADC}
where $ADC = \theta Q \theta^T$, $\theta$ is a unit vector pointing at any
direction on the sphere for which a signal is to be predicted, $b$ is the b
value provided in the GradientTable input for that direction, $Q$ is the
quadratic form of the tensor determined by the input parameters.
"""
evals = dti_params[..., :3]
evecs = dti_params[..., 3:].reshape(dti_params.shape[:-1] + (3, 3))
qform = vec_val_vect(evecs, evals)
del evals, evecs
lower_tri = lower_triangular(qform, b0=S0)
del qform
D = design_matrix(gtab)
return np.exp(np.dot(lower_tri, D.T))
class TensorModel(ReconstModel):
"""Diffusion Tensor"""
def __init__(self, gtab, *args, fit_method="WLS", return_S0_hat=False, **kwargs):
"""A Diffusion Tensor Model.
See :footcite:p:`Basser1994b` and :footcite:p:`Basser1996` for further
details about the model.
Parameters
----------
gtab : GradientTable class instance
Gradient table.
fit_method : str or callable, optional
str can be one of the following:
'WLS' for weighted least squares
:func:`dti.wls_fit_tensor`
'LS' or 'OLS' for ordinary least squares
:func:`dti.ols_fit_tensor`
'NLLS' for non-linear least-squares
:func:`dti.nlls_fit_tensor`
'RT' or 'restore' or 'RESTORE' for RESTORE robust tensor
fitting :footcite:p:`Chang2005`
:func:`dti.restore_fit_tensor`
callable has to have the signature:
``fit_method(design_matrix, data, *args, **kwargs)``
return_S0_hat : bool, optional
Boolean to return (True) or not (False) the S0 values for the fit.
args, kwargs : arguments and key-word arguments passed to the
fit_method. See :func:`dti.wls_fit_tensor`,
:func:`dti.ols_fit_tensor` for details
min_signal : float, optional
The minimum signal value. Needs to be a strictly positive
number. Default: minimal signal in the data provided to `fit`.
Notes
-----
In order to increase speed of processing, tensor fitting is done
simultaneously over many voxels. Many fit_methods use the 'step'
parameter to set the number of voxels that will be fit at once in each
iteration. This is the chunk size as a number of voxels. A larger step
value should speed things up, but it will also take up more memory. It
is advisable to keep an eye on memory consumption as this value is
increased.
E.g., in :func:`iter_fit_tensor` we have a default step value of
1e4
References
----------
.. footbibliography::
"""
ReconstModel.__init__(self, gtab)
if not callable(fit_method):
try:
fit_method = common_fit_methods[fit_method]
except KeyError as e:
e_s = '"' + str(fit_method) + '" is not a known fit '
e_s += "method, the fit method should either be a "
e_s += "function or one of the common fit methods"
raise ValueError(e_s) from e
self.fit_method = fit_method
self.return_S0_hat = return_S0_hat
self.design_matrix = design_matrix(self.gtab)
self.args = args
self.kwargs = kwargs
self.min_signal = self.kwargs.pop("min_signal", None)
if self.min_signal is not None and self.min_signal <= 0:
e_s = "The `min_signal` key-word argument needs to be strictly"
e_s += " positive."
raise ValueError(e_s)
self.extra = {}
@warning_for_keywords()
def fit(self, data, *, mask=None, adjacency=False):
"""Fit method of the DTI model class
Parameters
----------
data : array
The measured signal from one voxel.
mask : array, optional
A boolean array used to mark the coordinates in the data that
should be analyzed that has the shape data.shape[:-1]
adjacency : float, optional
Calculate voxel adjacency accounting for mask, using this
value as cutoff distance (measured in voxel coordinates)
"""
S0_params = None
img_shape = data.shape[:-1]
if mask is not None:
# Check for valid shape of the mask
if mask.shape != img_shape:
raise ValueError("Mask is not the same shape as data.")
mask = np.asarray(mask, dtype=bool)
data_in_mask = np.reshape(data[mask], (-1, data.shape[-1]))
if adjacency > 0:
self.kwargs["adjacency"] = adjacency_calc(
img_shape, mask=mask, adjacency=adjacency
)
if "sigma" in self.kwargs:
sigma = self.kwargs["sigma"]
if isinstance(sigma, np.ndarray): # sigma passed as array
if sigma.size == 1: # scalar passed as array
sigma_in_mask = sigma[0] # to scalar
else:
if sigma.ndim > 1: # spatially varying
sigma_in_mask = np.reshape(sigma[mask], (-1, 1))
if sigma_in_mask.size != data_in_mask.shape[0]:
raise ValueError(
"ValueError: sigma size must\
equal number of voxels for\
spatial variation"
)
else: # image varying
sigma_in_mask = sigma
if sigma_in_mask.size != data_in_mask.shape[-1]:
raise ValueError(
"ValueError: sigma size must\
equal number of images for\
image variation"
)
else: # sigma passed as scalar
sigma_in_mask = sigma
self.kwargs["sigma"] = sigma_in_mask
if self.min_signal is None:
min_signal = MIN_POSITIVE_SIGNAL
else:
min_signal = self.min_signal
data_in_mask = np.maximum(data_in_mask, min_signal)
params_in_mask, extra = self.fit_method(
self.design_matrix,
data_in_mask,
*self.args,
return_S0_hat=self.return_S0_hat,
**self.kwargs,
)
if self.return_S0_hat:
params_in_mask, model_S0 = params_in_mask
if mask is None:
out_shape = data.shape[:-1] + (-1,)
dti_params = params_in_mask.reshape(out_shape)
if self.return_S0_hat:
S0_params = model_S0.reshape(out_shape[:-1])
if extra is not None:
for key in extra:
self.extra[key] = extra[key].reshape(data.shape)
else:
dti_params = np.zeros(data.shape[:-1] + (12,))
dti_params[mask, :] = params_in_mask
if self.return_S0_hat:
S0_params = np.zeros(data.shape[:-1])
S0_params[mask] = model_S0.squeeze()
if extra is not None:
for key in extra:
self.extra[key] = np.zeros(data.shape)
self.extra[key][mask, :] = extra[key]
return TensorFit(self, dti_params, model_S0=S0_params)
@warning_for_keywords()
def predict(self, dti_params, *, S0=1.0):
"""
Predict a signal for this TensorModel class instance given parameters.
Parameters
----------
dti_params : ndarray
The last dimension should have 12 tensor parameters: 3
eigenvalues, followed by the 3 eigenvectors
S0 : float or ndarray, optional
The non diffusion-weighted signal in every voxel, or across all
voxels.
"""
return tensor_prediction(dti_params, self.gtab, S0)
class TensorFit:
@warning_for_keywords()
def __init__(self, model, model_params, *, model_S0=None):
"""Initialize a TensorFit class instance."""
self.model = model
self.model_params = model_params
self.model_S0 = model_S0
def __getitem__(self, index):
model_params = self.model_params
model_S0 = self.model_S0
N = model_params.ndim
if type(index) is not tuple:
index = (index,)
elif len(index) >= model_params.ndim:
raise IndexError("IndexError: invalid index")
index = index + (slice(None),) * (N - len(index))
if model_S0 is not None:
model_S0 = model_S0[index[:-1]]
return type(self)(self.model, model_params[index], model_S0=model_S0)
@property
def S0_hat(self):
return self.model_S0
@property
def shape(self):
return self.model_params.shape[:-1]
@property
def directions(self):
"""
For tracking - return the primary direction in each voxel
"""
return self.evecs[..., None, :, 0]
@property
def evals(self):
"""
Returns the eigenvalues of the tensor as an array
"""
return self.model_params[..., :3]
@property
def evecs(self):
"""
Returns the eigenvectors of the tensor as an array, columnwise
"""
evecs = self.model_params[..., 3:12]
return evecs.reshape(self.shape + (3, 3))
@property
def quadratic_form(self):
"""Calculates the 3x3 diffusion tensor for each voxel"""
# do `evecs * evals * evecs.T` where * is matrix multiply
# einsum does this with:
# np.einsum('...ij,...j,...kj->...ik', evecs, evals, evecs)
return vec_val_vect(self.evecs, self.evals)
@warning_for_keywords()
def lower_triangular(self, *, b0=None):
return lower_triangular(self.quadratic_form, b0=b0)
@auto_attr
def fa(self):
"""Fractional anisotropy (FA) calculated from cached eigenvalues."""
return fractional_anisotropy(self.evals)
@auto_attr
def color_fa(self):
"""Color fractional anisotropy of diffusion tensor"""
return color_fa(self.fa, self.evecs)
@auto_attr
def ga(self):
"""Geodesic anisotropy (GA) calculated from cached eigenvalues."""
return geodesic_anisotropy(self.evals)
@auto_attr
def mode(self):
"""
Tensor mode calculated from cached eigenvalues.
"""
return mode(self.quadratic_form)
@auto_attr
def md(self):
r"""
Mean diffusivity (MD) calculated from cached eigenvalues.
Returns
-------
md : array (V, 1)
Calculated MD.
Notes
-----
MD is calculated with the following equation:
.. math::
MD = \frac{\lambda_1+\lambda_2+\lambda_3}{3}
"""
return self.trace / 3.0
@auto_attr
def rd(self):