-
Notifications
You must be signed in to change notification settings - Fork 429
/
shm.py
executable file
·1577 lines (1299 loc) · 54 KB
/
shm.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
"""Tools for using spherical harmonic models to fit diffusion data.
References
----------
.. [1] Aganj, I., et al. 2009. ODF Reconstruction in Q-Ball Imaging With Solid
Angle Consideration.
.. [2] Descoteaux, M., et al. 2007. Regularized, fast, and robust analytical
Q-ball imaging.
.. [3] Tristan-Vega, A., et al. 2010. A new methodology for estimation of fiber
populations in white matter of the brain with Funk-Radon transform.
.. [4] Tristan-Vega, A., et al. 2009. Estimation of fiber orientation
probability density functions in high angular resolution diffusion
imaging.
Note about the Transpose:
In the literature the matrix representation of these methods is often written
as Y = Bx where B is some design matrix and Y and x are column vectors. In our
case the input data, a dwi stored as a nifti file for example, is stored as row
vectors (ndarrays) of the form (x, y, z, n), where n is the number of diffusion
directions. We could transpose and reshape the data to be (n, x*y*z), so that
we could directly plug it into the above equation. However, I have chosen to
keep the data as is and implement the relevant equations rewritten in the
following form: Y.T = x.T B.T, or in python syntax data = np.dot(sh_coef, B.T)
where data is Y.T and sh_coef is x.T.
"""
from warnings import warn
import numpy as np
import scipy.special as sps
from numpy.random import randint
from dipy.utils.deprecator import deprecate_with_version
from dipy.reconst.odf import OdfModel, OdfFit
from dipy.core.geometry import cart2sphere
from dipy.core.onetime import auto_attr
from dipy.reconst.cache import Cache
descoteaux07_legacy_msg = \
"The legacy descoteaux07 SH basis uses absolute values for negative " \
"harmonic degrees. It is outdated and will be deprecated in a future " \
"DIPY release. Consider using the new descoteaux07 basis by setting the " \
"`legacy` parameter to `False`."
tournier07_legacy_msg = \
"The legacy tournier07 basis is not normalized. It is outdated and will " \
"be deprecated in a future release of DIPY. Consider using the new " \
"tournier07 basis by setting the `legacy` parameter to `False`."
def _copydoc(obj):
def bandit(f):
f.__doc__ = obj.__doc__
return f
return bandit
def forward_sdeconv_mat(r_rh, n):
""" Build forward spherical deconvolution matrix
Parameters
----------
r_rh : ndarray
Rotational harmonics coefficients for the single fiber response
function. Each element ``rh[i]`` is associated with spherical harmonics
of degree ``2*i``.
n : ndarray
The order of spherical harmonic function associated with each row of
the deconvolution matrix. Only even orders are allowed
Returns
-------
R : ndarray (N, N)
Deconvolution matrix with shape (N, N)
"""
if np.any(n % 2):
raise ValueError("n has odd orders, expecting only even orders")
return np.diag(r_rh[n // 2])
def sh_to_rh(r_sh, m, n):
""" Spherical harmonics (SH) to rotational harmonics (RH)
Calculate the rotational harmonic decomposition up to
harmonic order ``n``, degree ``m`` for an axially and antipodally
symmetric function. Note that all ``m != 0`` coefficients
will be ignored as axial symmetry is assumed. Hence, there
will be ``(sh_order/2 + 1)`` non-zero coefficients.
Parameters
----------
r_sh : ndarray (N,)
ndarray of SH coefficients for the single fiber response function.
These coefficients must correspond to the real spherical harmonic
functions produced by `shm.real_sh_descoteaux_from_index`.
m : ndarray (N,)
The degree of the spherical harmonic function associated with each
coefficient.
n : ndarray (N,)
The order of the spherical harmonic function associated with each
coefficient.
Returns
-------
r_rh : ndarray (``(sh_order + 1)*(sh_order + 2)/2``,)
Rotational harmonics coefficients representing the input `r_sh`
See Also
--------
shm.real_sh_descoteaux_from_index, shm.real_sh_descoteaux
References
----------
.. [1] Tournier, J.D., et al. NeuroImage 2007. Robust determination of the
fibre orientation distribution in diffusion MRI: Non-negativity
constrained super-resolved spherical deconvolution
"""
mask = m == 0
# The delta function at theta = phi = 0 is known to have zero coefficients
# where m != 0, therefore we need only compute the coefficients at m=0.
dirac_sh = gen_dirac(0, n[mask], 0, 0)
r_rh = r_sh[mask] / dirac_sh
return r_rh
def gen_dirac(m, n, theta, phi, legacy=True):
""" Generate Dirac delta function orientated in (theta, phi) on the sphere
The spherical harmonics (SH) representation of this Dirac is returned as
coefficients to spherical harmonic functions produced from ``descoteaux07``
basis.
Parameters
----------
m : ndarray (N,)
The degree of the spherical harmonic function associated with each
coefficient.
n : ndarray (N,)
The order of the spherical harmonic function associated with each
coefficient.
theta : float [0, pi]
The polar (colatitudinal) coordinate.
phi : float [0, 2*pi]
The azimuthal (longitudinal) coordinate.
legacy: bool, optional
If true, uses DIPY's legacy descoteaux07 implementation (where |m|
is used for m < 0). Else, implements the basis as defined in
Descoteaux et al. 2007 (without the absolute value).
See Also
--------
shm.real_sh_descoteaux_from_index, shm.real_sh_descoteaux
Returns
-------
dirac : ndarray
SH coefficients representing the Dirac function. The shape of this is
`(m + 2) * (m + 1) / 2`.
"""
return real_sh_descoteaux_from_index(m, n, theta, phi, legacy=legacy)
def spherical_harmonics(m, n, theta, phi, use_scipy=True):
"""Compute spherical harmonics.
This may take scalar or array arguments. The inputs will be broadcast
against each other.
Parameters
----------
m : int ``|m| <= n``
The degree of the harmonic.
n : int ``>= 0``
The order of the harmonic.
theta : float [0, 2*pi]
The azimuthal (longitudinal) coordinate.
phi : float [0, pi]
The polar (colatitudinal) coordinate.
use_scipy : bool, optional
If True, use scipy implementation.
Returns
-------
y_mn : complex float
The harmonic $Y^m_n$ sampled at ``theta`` and ``phi``.
Notes
-----
This is a faster implementation of scipy.special.sph_harm for
scipy version < 0.15.0. For scipy 0.15 and onwards, we use the scipy
implementation of the function.
The usual definitions for ``theta` and `phi`` used in DIPY are interchanged
in the method definition to agree with the definitions in
scipy.special.sph_harm, where `theta` represents the azimuthal coordinate
and `phi` represents the polar coordinate.
Although scipy uses a naming convention where ``m`` is the order and ``n``
is the degree of the SH, the opposite of DIPY's, their definition for both
parameters is the same as ours, with ``n >= 0`` and ``|m| <= n``.
"""
if use_scipy:
return sps.sph_harm(m, n, theta, phi, dtype=complex)
x = np.cos(phi)
val = sps.lpmv(m, n, x).astype(complex)
val *= np.sqrt((2 * n + 1) / 4.0 / np.pi)
val *= np.exp(0.5 * (sps.gammaln(n - m + 1) - sps.gammaln(n + m + 1)))
val = val * np.exp(1j * m * theta)
return val
@deprecate_with_version('dipy.reconst.shm.real_sph_harm is deprecated, '
'Please use '
'dipy.reconst.shm.real_sh_descoteaux_from_index '
'instead', since='1.3', until='2.0')
def real_sph_harm(m, n, theta, phi):
""" Compute real spherical harmonics.
Where the real harmonic $Y^m_n$ is defined to be:
Imag($Y^m_n$) * sqrt(2) if m > 0
$Y^0_n$ if m = 0
Real($Y^|m|_n$) * sqrt(2) if m < 0
This may take scalar or array arguments. The inputs will be broadcast
against each other.
Parameters
----------
m : int ``|m| <= n``
The degree of the harmonic.
n : int ``>= 0``
The order of the harmonic.
theta : float [0, pi]
The polar (colatitudinal) coordinate.
phi : float [0, 2*pi]
The azimuthal (longitudinal) coordinate.
Returns
-------
y_mn : real float
The real harmonic $Y^m_n$ sampled at `theta` and `phi`.
See Also
--------
scipy.special.sph_harm
"""
return real_sh_descoteaux_from_index(m, n, theta, phi, legacy=True)
def real_sh_tournier_from_index(m, n, theta, phi, legacy=True):
""" Compute real spherical harmonics as initially defined in Tournier
2007 [1]_ then updated in MRtrix3 [2]_, where the real harmonic $Y^m_n$
is defined to be:
Real($Y^m_n$) * sqrt(2) if m > 0
$Y^0_n$ if m = 0
Imag($Y^|m|_n$) * sqrt(2) if m < 0
This may take scalar or array arguments. The inputs will be broadcast
against each other.
Parameters
----------
m : int ``|m| <= n``
The degree of the harmonic.
n : int ``>= 0``
The order of the harmonic.
theta : float [0, pi]
The polar (colatitudinal) coordinate.
phi : float [0, 2*pi]
The azimuthal (longitudinal) coordinate.
legacy: bool, optional
If true, uses MRtrix 0.2 SH basis definition, where the ``sqrt(2)``
factor is omitted. Else, uses the MRtrix 3 definition presented above.
Returns
-------
real_sh : real float
The real harmonics $Y^m_n$ sampled at ``theta`` and ``phi``.
References
----------
.. [1] Tournier J.D., Calamante F. and Connelly A. Robust determination
of the fibre orientation distribution in diffusion MRI:
Non-negativity constrained super-resolved spherical deconvolution.
NeuroImage. 2007;35(4):1459-1472.
.. [2] Tournier J-D, Smith R, Raffelt D, Tabbara R, Dhollander T,
Pietsch M, et al. MRtrix3: A fast, flexible and open software
framework for medical image processing and visualisation.
NeuroImage. 2019 Nov 15;202:116-137.
"""
# In the m < 0 case, Tournier basis considers |m|
sh = spherical_harmonics(np.abs(m), n, phi, theta)
real_sh = np.where(m < 0, sh.imag, sh.real)
if not legacy:
# The Tournier basis from MRtrix3 is normalized
real_sh *= np.where(m == 0, 1., np.sqrt(2))
else:
warn(tournier07_legacy_msg, category=PendingDeprecationWarning)
return real_sh
def real_sh_descoteaux_from_index(m, n, theta, phi, legacy=True):
""" Compute real spherical harmonics as in Descoteaux et al. 2007 [1]_,
where the real harmonic $Y^m_n$ is defined to be:
Imag($Y^m_n$) * sqrt(2) if m > 0
$Y^0_n$ if m = 0
Real($Y^m_n$) * sqrt(2) if m < 0
This may take scalar or array arguments. The inputs will be broadcast
against each other.
Parameters
----------
m : int ``|m| <= n``
The degree of the harmonic.
n : int ``>= 0``
The order of the harmonic.
theta : float [0, pi]
The polar (colatitudinal) coordinate.
phi : float [0, 2*pi]
The azimuthal (longitudinal) coordinate.
legacy: bool, optional
If true, uses DIPY's legacy descoteaux07 implementation (where |m|
is used for m < 0). Else, implements the basis as defined in
Descoteaux et al. 2007 (without the absolute value).
Returns
-------
real_sh : real float
The real harmonic $Y^m_n$ sampled at ``theta`` and ``phi``.
References
----------
.. [1] Descoteaux, M., Angelino, E., Fitzgibbons, S. and Deriche, R.
Regularized, Fast, and Robust Analytical Q-ball Imaging.
Magn. Reson. Med. 2007;58:497-510.
"""
if legacy:
# In the case where m < 0, legacy descoteaux basis considers |m|
warn(descoteaux07_legacy_msg, category=PendingDeprecationWarning)
sh = spherical_harmonics(np.abs(m), n, phi, theta)
else:
# In the cited paper, the basis is defined without the absolute value
sh = spherical_harmonics(m, n, phi, theta)
real_sh = np.where(m > 0, sh.imag, sh.real)
real_sh *= np.where(m == 0, 1., np.sqrt(2))
return real_sh
def real_sh_tournier(sh_order, theta, phi,
full_basis=False,
legacy=True):
""" Compute real spherical harmonics as initially defined in Tournier
2007 [1]_ then updated in MRtrix3 [2]_, where the real harmonic $Y^m_n$
is defined to be:
Real($Y^m_n$) * sqrt(2) if m > 0
$Y^0_n$ if m = 0
Imag($Y^|m|_n$) * sqrt(2) if m < 0
This may take scalar or array arguments. The inputs will be broadcast
against each other.
Parameters
----------
sh_order : int
The maximum degree or the spherical harmonic basis.
theta : float [0, pi]
The polar (colatitudinal) coordinate.
phi : float [0, 2*pi]
The azimuthal (longitudinal) coordinate.
full_basis: bool, optional
If true, returns a basis including odd order SH functions as well as
even order SH functions. Else returns only even order SH functions.
legacy: bool, optional
If true, uses MRtrix 0.2 SH basis definition, where the ``sqrt(2)``
factor is omitted. Else, uses MRtrix 3 definition presented above.
Returns
-------
real_sh : real float
The real harmonic $Y^m_n$ sampled at ``theta`` and ``phi``.
m : array
The degree of the harmonics.
n : array
The order of the harmonics.
References
----------
.. [1] Tournier J.D., Calamante F. and Connelly A. Robust determination
of the fibre orientation distribution in diffusion MRI:
Non-negativity constrained super-resolved spherical deconvolution.
NeuroImage. 2007;35(4):1459-1472.
.. [2] Tournier J-D, Smith R, Raffelt D, Tabbara R, Dhollander T,
Pietsch M, et al. MRtrix3: A fast, flexible and open software
framework for medical image processing and visualisation.
NeuroImage. 2019 Nov 15;202:116-137.
"""
m, n = sph_harm_ind_list(sh_order, full_basis)
phi = np.reshape(phi, [-1, 1])
theta = np.reshape(theta, [-1, 1])
real_sh = real_sh_tournier_from_index(m, n, theta, phi, legacy)
return real_sh, m, n
def real_sh_descoteaux(sh_order, theta, phi,
full_basis=False,
legacy=True):
""" Compute real spherical harmonics as in Descoteaux et al. 2007 [1]_,
where the real harmonic $Y^m_n$ is defined to be:
Imag($Y^m_n$) * sqrt(2) if m > 0
$Y^0_n$ if m = 0
Real($Y^m_n$) * sqrt(2) if m < 0
This may take scalar or array arguments. The inputs will be broadcast
against each other.
Parameters
----------
sh_order : int
The maximum degree or the spherical harmonic basis.
theta : float [0, pi]
The polar (colatitudinal) coordinate.
phi : float [0, 2*pi]
The azimuthal (longitudinal) coordinate.
full_basis: bool, optional
If true, returns a basis including odd order SH functions as well as
even order SH functions. Otherwise returns only even order SH
functions.
legacy: bool, optional
If true, uses DIPY's legacy descoteaux07 implementation (where |m|
for m < 0). Else, implements the basis as defined in Descoteaux et al.
2007.
Returns
-------
real_sh : real float
The real harmonic $Y^m_n$ sampled at ``theta`` and ``phi``.
m : array
The degree of the harmonics.
n : array
The order of the harmonics.
References
----------
.. [1] Descoteaux, M., Angelino, E., Fitzgibbons, S. and Deriche, R.
Regularized, Fast, and Robust Analytical Q-ball Imaging.
Magn. Reson. Med. 2007;58:497-510.
"""
m, n = sph_harm_ind_list(sh_order, full_basis)
phi = np.reshape(phi, [-1, 1])
theta = np.reshape(theta, [-1, 1])
real_sh = real_sh_descoteaux_from_index(m, n, theta, phi, legacy)
return real_sh, m, n
@deprecate_with_version('dipy.reconst.shm.real_sym_sh_mrtrix is deprecated, '
'Please use dipy.reconst.shm.real_sh_tournier instead',
since='1.3', until='2.0')
def real_sym_sh_mrtrix(sh_order, theta, phi):
"""
Compute real symmetric spherical harmonics as in Tournier 2007 [2]_, where
the real harmonic $Y^m_n$ is defined to be::
Real($Y^m_n$) if m > 0
$Y^0_n$ if m = 0
Imag($Y^|m|_n$) if m < 0
This may take scalar or array arguments. The inputs will be broadcast
against each other.
Parameters
----------
sh_order : int
The maximum order or the spherical harmonic basis.
theta : float [0, pi]
The polar (colatitudinal) coordinate.
phi : float [0, 2*pi]
The azimuthal (longitudinal) coordinate.
Returns
-------
y_mn : real float
The real harmonic $Y^m_n$ sampled at ``theta`` and ``phi`` as
implemented in mrtrix. Warning: the basis is Tournier et al.
2007 [2]_; 2004 [1]_ is slightly different.
m : array
The degree of the harmonics.
n : array
The order of the harmonics.
References
----------
.. [1] Tournier J.D., Calamante F., Gadian D.G. and Connelly A.
Direct estimation of the fibre orientation density function from
diffusion-weighted MRI data using spherical deconvolution.
NeuroImage. 2004;23:1176-1185.
.. [2] Tournier J.D., Calamante F. and Connelly A. Robust determination
of the fibre orientation distribution in diffusion MRI:
Non-negativity constrained super-resolved spherical deconvolution.
NeuroImage. 2007;35(4):1459-1472.
"""
return real_sh_tournier(sh_order, theta, phi, legacy=True)
@deprecate_with_version('dipy.reconst.shm.real_sym_sh_basis is deprecated, '
'Please use dipy.reconst.shm.real_sh_descoteaux '
'instead', since='1.3', until='2.0')
def real_sym_sh_basis(sh_order, theta, phi):
"""Samples a real symmetric spherical harmonic basis at point on the sphere
Samples the basis functions up to order `sh_order` at points on the sphere
given by `theta` and `phi`. The basis functions are defined here the same
way as in Descoteaux et al. 2007 [1]_ where the real harmonic $Y^m_n$ is
defined to be:
Imag($Y^m_n$) * sqrt(2) if m > 0
$Y^0_n$ if m = 0
Real($Y^|m|_n$) * sqrt(2) if m < 0
This may take scalar or array arguments. The inputs will be broadcast
against each other.
Parameters
----------
sh_order : int
even int > 0, max spherical harmonic order
theta : float [0, 2*pi]
The azimuthal (longitudinal) coordinate.
phi : float [0, pi]
The polar (colatitudinal) coordinate.
Returns
-------
y_mn : real float
The real harmonic $Y^m_n$ sampled at ``theta`` and ``phi``
m : array
The degree of the harmonics.
n : array
The order of the harmonics.
References
----------
.. [1] Descoteaux, M., Angelino, E., Fitzgibbons, S. and Deriche, R.
Regularized, Fast, and Robust Analytical Q-ball Imaging.
Magn. Reson. Med. 2007;58:497-510.
"""
return real_sh_descoteaux(sh_order, theta, phi, legacy=True)
sph_harm_lookup = {None: real_sh_descoteaux,
"tournier07": real_sh_tournier,
"descoteaux07": real_sh_descoteaux}
def sph_harm_ind_list(sh_order, full_basis=False):
"""
Returns the degree (``m``) and order (``n``) of all the symmetric spherical
harmonics of degree less then or equal to ``sh_order``. The results,
``m_list`` and ``n_list`` are kx1 arrays, where k depends on ``sh_order``.
They can be passed to :func:`real_sh_descoteaux_from_index` and
:func:``real_sh_tournier_from_index``.
Parameters
----------
sh_order : int
even int > 0, max order to return
full_basis: bool, optional
True for SH basis with even and odd order terms
Returns
-------
m_list : array
degrees of even spherical harmonics
n_list : array
orders of even spherical harmonics
See Also
--------
shm.real_sh_descoteaux_from_index, shm.real_sh_tournier_from_index
"""
if full_basis:
n_range = np.arange(0, sh_order + 1, dtype=int)
ncoef = int((sh_order + 1) * (sh_order + 1))
else:
if sh_order % 2 != 0:
raise ValueError('sh_order must be an even integer >= 0')
n_range = np.arange(0, sh_order + 1, 2, dtype=int)
ncoef = int((sh_order + 2) * (sh_order + 1) // 2)
n_list = np.repeat(n_range, n_range * 2 + 1)
offset = 0
m_list = np.empty(ncoef, 'int')
for ii in n_range:
m_list[offset:offset + 2 * ii + 1] = np.arange(-ii, ii + 1)
offset = offset + 2 * ii + 1
# makes the arrays ncoef by 1, allows for easy broadcasting later in code
return m_list, n_list
def order_from_ncoef(ncoef, full_basis=False):
"""
Given a number ``n`` of coefficients, calculate back the ``sh_order``
Parameters
----------
ncoef: int
number of coefficients
full_basis: bool, optional
True when coefficients are for a full SH basis.
Returns
-------
sh_order: int
maximum order of SH basis
"""
if full_basis:
# Solve the equation :
# ncoef = (sh_order + 1) * (sh_order + 1)
return int(np.sqrt(ncoef) - 1)
# Solve the quadratic equation derived from :
# ncoef = (sh_order + 2) * (sh_order + 1) / 2
return -1 + int(np.sqrt(9 - 4 * (2-2*ncoef))//2)
def smooth_pinv(B, L):
"""Regularized pseudo-inverse
Computes a regularized least square inverse of B
Parameters
----------
B : array_like (n, m)
Matrix to be inverted
L : array_like (m,)
Returns
-------
inv : ndarray (m, n)
regularized least square inverse of B
Notes
-----
In the literature this inverse is often written $(B^{T}B+L^{2})^{-1}B^{T}$.
However here this inverse is implemented using the pseudo-inverse because
it is more numerically stable than the direct implementation of the matrix
product.
"""
L = np.diag(L)
inv = np.linalg.pinv(np.concatenate((B, L)))
return inv[:, :len(B)]
def lazy_index(index):
"""Produces a lazy index
Returns a slice that can be used for indexing an array, if no slice can be
made index is returned as is.
"""
index = np.array(index)
assert index.ndim == 1
if index.dtype.kind == 'b':
index = index.nonzero()[0]
if len(index) == 1:
return slice(index[0], index[0] + 1)
step = np.unique(np.diff(index))
if len(step) != 1 or step[0] == 0:
return index
else:
return slice(index[0], index[-1] + 1, step[0])
def _gfa_sh(coef, sh0_index=0):
"""The gfa of the odf, computed from the spherical harmonic coefficients
This is a private function because it only works for coefficients of
normalized sh bases.
Parameters
----------
coef : array
The coefficients, using a normalized sh basis, that represent each odf.
sh0_index : int, optional
The index of the coefficient associated with the 0th order sh harmonic.
Returns
-------
gfa_values : array
The gfa of each odf.
"""
coef_sq = coef**2
numer = coef_sq[..., sh0_index]
denom = coef_sq.sum(-1)
# The sum of the square of the coefficients being zero is the same as all
# the coefficients being zero
allzero = denom == 0
# By adding 1 to numer and denom where both and are 0, we prevent 0/0
numer = numer + allzero
denom = denom + allzero
return np.sqrt(1. - (numer / denom))
class SphHarmModel(OdfModel, Cache):
"""To be subclassed by all models that return a SphHarmFit when fit."""
def sampling_matrix(self, sphere):
"""The matrix needed to sample ODFs from coefficients of the model.
Parameters
----------
sphere : Sphere
Points used to sample ODF.
Returns
-------
sampling_matrix : array
The size of the matrix will be (N, M) where N is the number of
vertices on sphere and M is the number of coefficients needed by
the model.
"""
sampling_matrix = self.cache_get("sampling_matrix", sphere)
if sampling_matrix is None:
sh_order = self.sh_order
theta = sphere.theta
phi = sphere.phi
sampling_matrix, m, n = real_sh_descoteaux(sh_order, theta, phi)
self.cache_set("sampling_matrix", sphere, sampling_matrix)
return sampling_matrix
class QballBaseModel(SphHarmModel):
"""To be subclassed by Qball type models."""
def __init__(self, gtab, sh_order, smooth=0.006, min_signal=1e-5,
assume_normed=False):
"""Creates a model that can be used to fit or sample diffusion data
Parameters
----------
gtab : GradientTable
Diffusion gradients used to acquire data
sh_order : even int >= 0
the spherical harmonic order of the model
smooth : float between 0 and 1, optional
The regularization parameter of the model
min_signal : float, > 0, optional
During fitting, all signal values less than `min_signal` are
clipped to `min_signal`. This is done primarily to avoid values
less than or equal to zero when taking logs.
assume_normed : bool, optional
If True, clipping and normalization of the data with respect to the
mean B0 signal are skipped during mode fitting. This is an advanced
feature and should be used with care.
See Also
--------
normalize_data
"""
SphHarmModel.__init__(self, gtab)
self._where_b0s = lazy_index(gtab.b0s_mask)
self._where_dwi = lazy_index(~gtab.b0s_mask)
self.assume_normed = assume_normed
self.min_signal = min_signal
x, y, z = gtab.gradients[self._where_dwi].T
r, theta, phi = cart2sphere(x, y, z)
B, m, n = real_sh_descoteaux(sh_order, theta[:, None], phi[:, None])
L = -n * (n + 1)
legendre0 = sps.lpn(sh_order, 0)[0]
F = legendre0[n]
self.sh_order = sh_order
self.B = B
self.m = m
self.n = n
self._set_fit_matrix(B, L, F, smooth)
def _set_fit_matrix(self, *args):
"""Should be set in a subclass and is called by __init__"""
msg = "User must implement this method in a subclass"
raise NotImplementedError(msg)
def fit(self, data, mask=None):
"""Fits the model to diffusion data and returns the model fit"""
# Normalize the data and fit coefficients
if not self.assume_normed:
data = normalize_data(data, self._where_b0s, self.min_signal)
# Compute coefficients using abstract method
coef = self._get_shm_coef(data)
# Apply the mask to the coefficients
if mask is not None:
mask = np.asarray(mask, dtype=bool)
coef *= mask[..., None]
return SphHarmFit(self, coef, mask)
class SphHarmFit(OdfFit):
"""Diffusion data fit to a spherical harmonic model"""
def __init__(self, model, shm_coef, mask):
self.model = model
self._shm_coef = shm_coef
self.mask = mask
@property
def shape(self):
return self._shm_coef.shape[:-1]
def __getitem__(self, index):
"""Allowing indexing into fit"""
# Index shm_coefficients
if isinstance(index, tuple):
coef_index = index + (Ellipsis,)
else:
coef_index = index
new_coef = self._shm_coef[coef_index]
# Index mask
if self.mask is not None:
new_mask = self.mask[index]
assert new_mask.shape == new_coef.shape[:-1]
else:
new_mask = None
return SphHarmFit(self.model, new_coef, new_mask)
def odf(self, sphere):
"""Samples the odf function on the points of a sphere
Parameters
----------
sphere : Sphere
The points on which to sample the odf.
Returns
-------
values : ndarray
The value of the odf on each point of `sphere`.
"""
B = self.model.sampling_matrix(sphere)
return np.dot(self.shm_coeff, B.T)
@auto_attr
def gfa(self):
return _gfa_sh(self.shm_coeff, 0)
@property
def shm_coeff(self):
"""The spherical harmonic coefficients of the odf
Make this a property for now, if there is a use case for modifying
the coefficients we can add a setter or expose the coefficients more
directly
"""
return self._shm_coef
def predict(self, gtab=None, S0=1.0):
"""
Predict the diffusion signal from the model coefficients.
Parameters
----------
gtab : a GradientTable class instance
The directions and bvalues on which prediction is desired
S0 : float array
The mean non-diffusion-weighted signal in each voxel.
"""
if not hasattr(self.model, 'predict'):
msg = "This model does not have prediction implemented yet"
raise NotImplementedError(msg)
return self.model.predict(self._shm_coef, gtab, S0)
class CsaOdfModel(QballBaseModel):
"""Implementation of Constant Solid Angle reconstruction method.
References
----------
.. [1] Aganj, I., et al. 2009. ODF Reconstruction in Q-Ball Imaging With
Solid Angle Consideration.
"""
min = .001
max = .999
_n0_const = .5 / np.sqrt(np.pi)
def _set_fit_matrix(self, B, L, F, smooth):
"""The fit matrix, is used by fit_coefficients to return the
coefficients of the odf"""
invB = smooth_pinv(B, np.sqrt(smooth) * L)
L = L[:, None]
F = F[:, None]
self._fit_matrix = (F * L) / (8 * np.pi) * invB
def _get_shm_coef(self, data, mask=None):
"""Returns the coefficients of the model"""
data = data[..., self._where_dwi]
data = data.clip(self.min, self.max)
loglog_data = np.log(-np.log(data))
sh_coef = np.dot(loglog_data, self._fit_matrix.T)
sh_coef[..., 0] = self._n0_const
return sh_coef
class OpdtModel(QballBaseModel):
"""Implementation of Orientation Probability Density Transform
reconstruction method.
References
----------
.. [1] Tristan-Vega, A., et al. 2010. A new methodology for estimation of
fiber populations in white matter of the brain with Funk-Radon
transform.
.. [2] Tristan-Vega, A., et al. 2009. Estimation of fiber orientation
probability density functions in high angular resolution diffusion
imaging.
"""
def _set_fit_matrix(self, B, L, F, smooth):
invB = smooth_pinv(B, np.sqrt(smooth) * L)
L = L[:, None]
F = F[:, None]
delta_b = F * L * invB
delta_q = 4 * F * invB
self._fit_matrix = delta_b, delta_q
def _get_shm_coef(self, data, mask=None):
"""Returns the coefficients of the model"""
delta_b, delta_q = self._fit_matrix
return _slowadc_formula(data[..., self._where_dwi], delta_b, delta_q)
def _slowadc_formula(data, delta_b, delta_q):
"""formula used in SlowAdcOpdfModel"""
logd = -np.log(data)
return (np.dot(logd * (1.5 - logd) * data, delta_q.T)
- np.dot(data, delta_b.T))
class QballModel(QballBaseModel):
"""Implementation of regularized Qball reconstruction method.
References
----------
.. [1] Descoteaux, M., et al. 2007. Regularized, fast, and robust
analytical Q-ball imaging.
"""
def _set_fit_matrix(self, B, L, F, smooth):
invB = smooth_pinv(B, np.sqrt(smooth) * L)
F = F[:, None]
self._fit_matrix = F * invB
def _get_shm_coef(self, data, mask=None):
"""Returns the coefficients of the model"""
return np.dot(data[..., self._where_dwi], self._fit_matrix.T)
def normalize_data(data, where_b0, min_signal=1e-5, out=None):
"""Normalizes the data with respect to the mean b0
"""
if out is None:
out = np.array(data, dtype='float32', copy=True)
else:
if out.dtype.kind != 'f':
raise ValueError("out must be floating point")
out[:] = data
out.clip(min_signal, out=out)
b0 = out[..., where_b0].mean(-1)
out /= b0[..., None]
return out