Base-classes for reconstruction models and reconstruction fits.
All the models in the reconst module follow the same template: a Model object
is used to represent the abstract properties of the model, that are independent
of the specifics of the data . These properties are reused whenever fitting a
particular set of data (different voxels, for example).
Build forward sharpening deconvolution transform (SDT) matrix
Parameters
----------
ratio : float
ratio = \(\frac{\lambda_2}{\lambda_1}\) of the single fiber response
function
l_values : ndarray (N,)
The order (l) of spherical harmonic function associated with each row
of the deconvolution matrix.
Constrained-regularized spherical deconvolution (CSD) [1]_
Deconvolves the axially symmetric single fiber response function r_rh in
rotational harmonics coefficients from the diffusion weighted signal in
dwsignal.
ODF constrained-regularized spherical deconvolution using
the Sharpening Deconvolution Transform (SDT) [1]_, [2]_. Parameters
----------
odf_sh : ndarray ((sh_order_max+1)*(sh_order_max+2)/2,)
ndarray of SH coefficients for the ODF spherical function to be
deconvolved
R : ndarray ((sh_order_max+1)(sh_order_max+2)/2,
(sh_order_max+1)(sh_order_max+2)/2)
SDT matrix in SH basis
B_reg : ndarray ((sh_order_max+1)(sh_order_max+2)/2,
(sh_order_max+1)(sh_order_max+2)/2)
SH basis matrix used for deconvolution
lambda_ : float
lambda parameter in minimization equation (default 1.0)
tau : float
threshold (tau *max(fODF)) controlling the amplitude below
which the corresponding fODF is assumed to be zero. r2_term : bool
True if ODF is computed from model that uses the \(r^2\) term in the
integral. Recall that Tuch's ODF (used in Q-ball Imaging [1]_) and
the true normalized ODF definition differ from a \(r^2\) term in the ODF
integral. The original Sharpening Deconvolution Transform (SDT)
technique [2]_ is expecting Tuch's ODF without the \(r^2\) (see [3]_ for
the mathematical details). Now, this function supports ODF that have
been computed using the \(r^2\) term because the proper analytical
response function has be derived. For example, models such as DSI,
GQI, SHORE, CSA, Tensor, Multi-tensor ODFs, should now be deconvolved
with the r2_term=True. Returns
-------
fodf_sh : ndarray ((sh_order_max+1)(sh_order_max+2)/2,)
Spherical harmonics coefficients of the constrained-regularized fiber
ODF
num_it : int
Number of iterations in the constrained-regularization used for
convergence
References
----------
.. [1] Tuch, D. MRM 2004. Q-Ball Imaging. .. [2] Descoteaux, M., et al. IEEE TMI 2009. Deterministic and
Probabilistic Tractography Based on Complex Fibre Orientation
Distributions
.. [3] Descoteaux, M, PhD thesis, INRIA Sophia-Antipolis, 2008. .
Calculate the apparent kurtosis coefficient (AKC) in each direction
of a sphere [1]_
Parameters
----------
dki_params : ndarray (x, y, z, 27) or (n, 27)
All parameters estimated from the diffusion kurtosis model.
Compute mean kurtosis (MK) from the kurtosis tensor
Parameters
----------
dki_params : ndarray (x, y, z, 27) or (n, 27)
All parameters estimated from the diffusion kurtosis model.
Compute the anisotropy of the kurtosis tensor (KFA) [1]_
Parameters
----------
dki_params : ndarray (x, y, z, 27) or (n, 27)
All parameters estimated from the diffusion kurtosis model.
Extract the diffusion tensor eigenvalues, the diffusion tensor eigenvector matrix, and the 15 independent elements of the kurtosis tensor from the model parameters estimated from the DKI model
Signal prediction given the DKI microstructure model parameters. Parameters
----------
params : ndarray (x, y, z, 40) or (n, 40)
All parameters estimated from the diffusion kurtosis microstructure model. Parameters are ordered as follows:
1) Three diffusion tensor's eigenvalues
2) Three lines of the eigenvector matrix each containing the
first, second and third coordinates of the eigenvector
3) Fifteen elements of the kurtosis tensor
4) Six elements of the hindered diffusion tensor
5) Six elements of the restricted diffusion tensor
6) Axonal water fraction
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
Returns
-------
S : (..., N) ndarray
Simulated signal based on the DKI microstructure model
Notes
-----
1) The predicted signal is given by:
\(S(\theta, b) = S_0 * [f * e^{-b ADC_{r}} + (1-f) * e^{-b ADC_{h}]\), where
:math:` ADC_{r} and ADC_{h} are the apparent diffusion coefficients of the
diffusion hindered and restricted compartment for a given direction
theta:math:, b:math: is the b value provided in the GradientTable input for that
direction, `f$ is the volume fraction of the restricted diffusion
compartment (also known as the axonal water fraction). 2) In the original article of DKI microstructural model [1]_, the hindered
and restricted tensors were defined as the intra-cellular and
extra-cellular diffusion compartments respectively. .
Selector function to switch between the 2-stage Trust-Region Reflective based NLLS fitting method (also containing the linear fit): trr and the Variable Projections based fitting method: varpro.
Computes the average signal across different diffusion directions
for each unique b-value
Parameters
----------
data : ndarray ([X, Y, Z, ...], g)
ndarray containing the data signals in its last dimension.
The general fractional anisotropy of a function evaluated
on the unit sphere
Parameters
----------
samples : ndarray
Values of data on the unit sphere.
The q:math:tau-dMRI model [1] to analytically and continuously represent
the q:math:tau diffusion signal attenuation over diffusion sensitization
q and diffusion time \(\tau\).
Classes and functions for fitting the covariance tensor model of q-space
trajectory imaging (QTI) by Westin et al. as presented in “Q-space trajectory
imaging for multidimensional diffusion MRI of the human brain” NeuroImage vol.
135 (2016): 345-62. https://doi.org/10.1016/j.neuroimage.2016.02.039
Apply a function of two arguments cumulatively to the items of a sequence or iterable, from left to right, so as to reduce the iterable to a single value.
This is an implementation of the sparse fascicle model described in
[Rokem2015]. The multi b-value version of this model is described in
[Rokem2014].
[Rokem2015]
Ariel Rokem, Jason D. Yeatman, Franco Pestilli, Kendrick
N. Kay, Aviv Mezer, Stefan van der Walt, Brian A. Wandell
(2015). Evaluating the accuracy of diffusion MRI models in white
matter. PLoS ONE 10(4): e0123272. doi:10.1371/journal.pone.0123272
[Rokem2014]
Ariel Rokem, Kimberly L. Chan, Jason D. Yeatman, Franco
Pestilli, Brian A. Wandell (2014). Evaluating the accuracy of diffusion
models at multiple b-values with cross-validation. ISMRM 2014.
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.
Compute real spherical harmonics as initially defined in Tournier
2007 [1]_ then updated in MRtrix3 [2]_, where the real harmonic \(Y^m_l\)
is defined to be:
Real(\(Y^m_l\)) * sqrt(2) if m > 0
\(Y^0_l\) if m = 0
Imag(\(Y^|m|_l\)) * sqrt(2) if m < 0
This may take scalar or array arguments.
Compute real spherical harmonics as in Descoteaux et al. 2007 [1]_,
where the real harmonic \(Y^m_l\) is defined to be:
Imag(\(Y^m_l\)) * sqrt(2) if m > 0
\(Y^0_l\) if m = 0
Real(\(Y^m_l\)) * sqrt(2) if m < 0
This may take scalar or array arguments.
Compute real spherical harmonics as initially defined in Tournier
2007 [1]_ then updated in MRtrix3 [2]_, where the real harmonic \(Y^m_l\)
is defined to be:
Real(\(Y^m_l\)) * sqrt(2) if m > 0
\(Y^0_l\) if m = 0
Imag(\(Y^|m|_l\)) * sqrt(2) if m < 0
This may take scalar or array arguments.
Compute real spherical harmonics as in Descoteaux et al. 2007 [1]_,
where the real harmonic \(Y^m_l\) is defined to be:
Imag(\(Y^m_l\)) * sqrt(2) if m > 0
\(Y^0_l\) if m = 0
Real(\(Y^m_l\)) * sqrt(2) if m < 0
This may take scalar or array arguments.
dipy.reconst.shm.real_sym_sh_mrtrix is deprecated, Please use dipy.reconst.shm.real_sh_tournier instead
* deprecated from version: 1.3
* Will raise <class 'dipy.utils.deprecator.ExpiredDeprecationError'> as of version: 2.0
Compute real symmetric spherical harmonics as in Tournier 2007 [2]_, where
the real harmonic \(Y^m_l\) is defined to be::
Real(\(Y^m_l\)) if m > 0
\(Y^0_l\) if m = 0
Imag(\(Y^|m|_l\)) if m < 0
This may take scalar or array arguments.
Samples a real symmetric spherical harmonic basis at point on the sphere
dipy.reconst.shm.real_sym_sh_basis is deprecated, Please use dipy.reconst.shm.real_sh_descoteaux instead
* deprecated from version: 1.3
* Will raise <class 'dipy.utils.deprecator.ExpiredDeprecationError'> as of version: 2.0
Samples the basis functions up to order sh_order_max at points on the
sphere given by theta and phi.
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}\).
Calculate anisotropic power map with a given SH coefficient matrix. Parameters
----------
sh_coeffs : ndarray
A ndarray where the last dimension is the
SH coefficients estimates for that voxel. norm_factor: float, optional
The value to normalize the ap values. power : int, optional
The degree to which power maps are calculated. non_negative: bool, optional
Whether to rectify the resulting map to be non-negative. Returns
-------
log_ap : ndarray
The log of the resulting power image. Notes
-----
Calculate AP image based on a IxJxKxC SH coefficient matrix based on the
equation:
.. math::
AP = sum_{l=2,4,6,...}{frac{1}{2l+1} sum_{m=-l}^l{|a_{l,m}|^n}}
Where the last dimension, C, is made of a flattened array of \(l`x:math:`m\)
coefficients, where \(l\) are the SH orders, and \(m = 2l+1\),
So l=1 has 1 coefficient, l=2 has 5, ... l=8 has 17 and so on. A l=2 SH coefficient matrix will then be composed of a IxJxKx6 volume. The power, \(n\) is usually set to \(n=2\). The final AP image is then shifted by -log(norm_factor), to be strictly
non-negative. Remaining values < 0 are discarded (set to 0), per default,
and this option is controlled through the non_negative keyword argument. References
----------
.. [1] Dell'Acqua, F., Lacerda, L., Catani, M., Simmons, A., 2014. Anisotropic Power Maps: A diffusion contrast to reveal low
anisotropy tissues from HARDI data,
in: Proceedings of International Society for Magnetic Resonance in
Medicine. Milan, Italy. .
Given the basis order and the index, return the shore indices n, l, m
for modified Merlet's 3D-SHORE
..math::
:nowrap:
begin{equation}
textbf{E}(qtextbf{u})=sum_{l=0, even}^{N_{max}}
sum_{n=l}^{(N_{max}+l)/2}
sum_{m=-l}^l c_{nlm}
phi_{nlm}(qtextbf{u})
end{equation}
where \(\phi_{nlm}\) is
..math::
:nowrap:
begin{equation}
phi_{nlm}^{SHORE}(qtextbf{u})=Biggl[dfrac{2(n-l)!}
{zeta^{3/2} Gamma(n+3/2)} Biggr]^{1/2}
Biggl(dfrac{q^2}{zeta}Biggr)^{l/2}
expBiggl(dfrac{-q^2}{2zeta}Biggr)
L^{l+1/2}_{n-l} Biggl(dfrac{q^2}{zeta}Biggr)
Y_l^m(textbf{u}).
The coefficient of determination is calculated as:
\[R^2 = 100 * (1 - \]
rac{SSE}{SSD})
where SSE is the sum of the squared error between the model and the data
(sum of the squared residuals) and SSD is the sum of the squares of the
deviations of the data from the mean of the data (variance * N).
The type of the model to use for prediction. The corresponding Fit
object must have a predict function implemented One of the following:
reconst.dti.TensorModel or
reconst.csdeconv.ConstrainedSphericalDeconvModel.
datandarray
Diffusion MRI data acquired with the GradientTable of the model. Shape
will typically be (x, y, z, b) where xyz are spatial dimensions and
b is the number of bvals/bvecs in the GradientTable.
foldsint
The number of divisions to apply to the data
model_argslist
Additional arguments to the model initialization
model_kwargsdict
Additional key-word arguments to the model initialization. If contains
the kwarg mask, this will be used as a key-word argument to the fit
method of the model object, rather than being used in the
initialization of the model object
This function assumes that a prediction API is implemented in the Model
class for which prediction is conducted. That is, the Fit object that gets
generated upon fitting the model needs to have a predict method, which
receives a GradientTable class instance as input and produces a predicted
signal as output.
It also assumes that the model object has bval and bvec attributes
holding b-values and corresponding unit vectors.
Spherical deconvolution computes a fiber orientation distribution
(FOD), also called fiber ODF (fODF) [2]_, as opposed to a diffusion ODF
as the QballModel or the CsaOdfModel. This results in a sharper angular
profile with better angular resolution that is the best object to be
used for later deterministic and probabilistic tractography [3]_.
A sharp fODF is obtained because a single fiber response function is
injected as a priori knowledge. The response function is often
data-driven and is thus provided as input to the
ConstrainedSphericalDeconvModel. It will be used as deconvolution
kernel, as described in [1]_.
gtab : GradientTable
response : tuple or AxSymShResponse object
A tuple with two elements. The first is the eigen-values as an (3,)
ndarray and the second is the signal value for the response
function without diffusion weighting (i.e. S0). This is to be able
to generate a single fiber synthetic signal. The response function
will be used as deconvolution kernel ([1]_).
reg_sphereSphere (optional)
sphere used to build the regularization B matrix.
Default: ‘symmetric362’.
weight given to the constrained-positivity regularization part of
the deconvolution equation (see [1]_). Default: 1
taufloat (optional)
threshold controlling the amplitude below which the corresponding
fODF is assumed to be zero. Ideally, tau should be set to
zero. However, to improve the stability of the algorithm, tau is
set to tau*100 % of the mean fODF amplitude (here, 10% by default)
(see [1]_). Default: 0.1
convergenceint
Maximum number of iterations to allow the deconvolution to
converge.
The SDT computes a fiber orientation distribution (FOD) as opposed to a
diffusion ODF as the QballModel or the CsaOdfModel. This results in a
sharper angular profile with better angular resolution. The Constrained
SDTModel is similar to the Constrained CSDModel but mathematically it
deconvolves the q-ball ODF as oppposed to the HARDI signal (see [1]_
for a comparison and a through discussion).
A sharp fODF is obtained because a single fiber response function is
injected as a priori knowledge. In the SDTModel, this response is a
single fiber q-ball ODF as opposed to a single fiber signal function
for the CSDModel. The response function will be used as deconvolution
kernel.
Center of ROI in data. If center is None, it is assumed that it is
the center of the volume with shape data.shape[:3].
roi_radiusint
radius of cubic ROI
fa_thrfloat
FA threshold
fa_callablecallable
A callable that defines an operation that compares FA with the fa_thr.
The operator should have two positional arguments
(e.g., fa_operator(FA, fa_thr)) and it should return a bool array.
return_number_of_voxelsbool
If True, returns the number of voxels used for estimating the response
function
In CSD there is an important pre-processing step: the estimation of the
fiber response function. In order to do this, we look for voxels with very
anisotropic configurations. We get this information from
csdeconv.mask_for_response_ssst(), which returns a mask of selected voxels
(more details are available in the description of the function).
With the mask, we compute the response function by using
csdeconv.response_from_mask_ssst(), which returns the response and the
ratio (more details are available in the description of the function).
In CSD there is an important pre-processing step: the estimation of the
fiber response function. In order to do this, we look for voxels with very
anisotropic configurations. This information can be obtained by using
csdeconv.mask_for_response_ssst() through a mask of selected voxels
(see[1]_). The present function uses such a mask to compute the ssst
response function.
For the response we also need to find the average S0 in the ROI. This is
possible using gtab.b0s_mask() we can find all the S0 volumes (which
correspond to b-values equal 0) in the dataset.
The response consists always of a prolate tensor created by averaging
the highest and second highest eigenvalues in the ROI with FA higher than
threshold. We also include the average S0s.
We also return the ratio which is used for the SDT models.
Build forward sharpening deconvolution transform (SDT) matrix
Parameters
———-
ratio : float
ratio = \(\frac{\lambda_2}{\lambda_1}\) of the single fiber response
function
l_values : ndarray (N,)
The order (l) of spherical harmonic function associated with each row
of the deconvolution matrix. Only even orders are allowed.
r2_term : bool
True if ODF comes from an ODF computed from a model using the \(r^2\)
term in the integral. For example, DSI, GQI, SHORE, CSA, Tensor,
Multi-tensor ODFs. This results in using the proper analytical response
function solution solving from the single-fiber ODF with the r^2 term.
This derivation is not published anywhere but is very similar to [1]_.
Returns
——-
R : ndarray (N, N)
SDT deconvolution matrix
P : ndarray (N, N)
Funk-Radon Transform (FRT) matrix
References
———-
.. [1] Descoteaux, M. PhD Thesis. INRIA Sophia-Antipolis. 2008.
Constrained-regularized spherical deconvolution (CSD) [1]_
Deconvolves the axially symmetric single fiber response function r_rh in
rotational harmonics coefficients from the diffusion weighted signal in
dwsignal.
Parameters
———-
dwsignal : array
Diffusion weighted signals to be deconvolved.
X : array
Prediction matrix which estimates diffusion weighted signals from FOD
coefficients.
B_reg : array (N, B)
SH basis matrix which maps FOD coefficients to FOD values on the
surface of the sphere. B_reg should be scaled to account for lambda.
tau : float
Threshold controlling the amplitude below which the corresponding fODF
is assumed to be zero. Ideally, tau should be set to zero. However, to
improve the stability of the algorithm, tau is set to tau*100 % of the
max fODF amplitude (here, 10% by default). This is similar to peak
detection where peaks below 0.1 amplitude are usually considered noise
peaks. Because SDT is based on a q-ball ODF deconvolution, and not
signal deconvolution, using the max instead of mean (as in CSD), is
more stable.
convergence : int
Maximum number of iterations to allow the deconvolution to converge.
P : ndarray
This is an optimization to avoid computing dot(X.T,X) many times.
If the same X is used many times, P can be precomputed and
passed to this function.
Returns
——-
fodf_sh : ndarray ((sh_order_max+1)*(sh_order_max+2)/2,)
Spherical harmonics coefficients of the constrained-regularized fiber
ODF.
num_it : int
Number of iterations in the constrained-regularization used for
convergence.
Notes
—–
This section describes how the fitting of the SH coefficients is done.
Problem is to minimise per iteration:
\(F(f_n) = ||Xf_n - S||^2 + \lambda^2 ||H_{n-1} f_n||^2\)
Where \(X\) maps current FOD SH coefficients \(f_n\) to DW signals \(s\) and
\(H_{n-1}\) maps FOD SH coefficients \(f_n\) to amplitudes along set of
negative directions identified in previous iteration, i.e. the matrix
formed by the rows of \(B_{reg}\) for which \(Hf_{n-1}<0\) where \(B_{reg}\)
maps \(f_n\) to FOD amplitude on a sphere.
Solve by differentiating and setting to zero:
\(\Rightarrow \frac{\delta F}{\delta f_n} = 2X^T(Xf_n - S) + 2 \lambda^2
H_{n-1}^TH_{n-1}f_n=0\)
Or:
\((X^TX + \lambda^2 H_{n-1}^TH_{n-1})f_n = X^Ts\)
Define \(Q = X^TX + \lambda^2 H_{n-1}^TH_{n-1}\) , which by construction is a
square positive definite symmetric matrix of size \(n_{SH} by n_{SH}\). If
needed, positive definiteness can be enforced with a small minimum norm
regulariser (helps a lot with poorly conditioned direction sets and/or
superresolution):
\(Q = X^TX + (\lambda H_{n-1}^T) (\lambda H_{n-1}) + \mu I\)
Solve \(Qf_n = X^Ts\) using Cholesky decomposition:
\(Q = LL^T\)
where \(L\) is lower triangular. Then problem can be solved by
back-substitution:
\(L_y = X^Ts\)\(L^Tf_n = y\)
To speeds things up further, form \(P = X^TX + \mu I\), and update to form
\(Q\) by rankn update with \(H_{n-1}\). The dipy implementation looks like:
form initially \(P = X^T X + \mu I\) and \(\lambda B_{reg}\)
for each voxel: form \(z = X^Ts\)
estimate \(f_0\) by solving \(Pf_0=z\). We use a simplified \(l_{max}=4\)
solution here, but it might not make a big difference.
Then iterate until no change in rows of \(H\) used in \(H_n\)
form \(H_{n}\) given \(f_{n-1}\)
form \(Q = P + (\lambda H_{n-1}^T) (\lambda H_{n-1}\)) (this can
be done by rankn update, but we currently do not use rankn
update).
solve \(Qf_n = z\) using Cholesky decomposition
We’d like to thanks Donald Tournier for his help with describing and
implementing this algorithm.
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.
ODF constrained-regularized spherical deconvolution using
the Sharpening Deconvolution Transform (SDT) [1]_, [2]_.
Parameters
———-
odf_sh : ndarray ((sh_order_max+1)*(sh_order_max+2)/2,)
ndarray of SH coefficients for the ODF spherical function to be
deconvolved
R : ndarray ((sh_order_max+1)(sh_order_max+2)/2,
(sh_order_max+1)(sh_order_max+2)/2)
SDT matrix in SH basis
B_reg : ndarray ((sh_order_max+1)(sh_order_max+2)/2,
(sh_order_max+1)(sh_order_max+2)/2)
SH basis matrix used for deconvolution
lambda_ : float
lambda parameter in minimization equation (default 1.0)
tau : float
threshold (tau *max(fODF)) controlling the amplitude below
which the corresponding fODF is assumed to be zero.
r2_term : bool
True if ODF is computed from model that uses the \(r^2\) term in the
integral. Recall that Tuch’s ODF (used in Q-ball Imaging [1]_) and
the true normalized ODF definition differ from a \(r^2\) term in the ODF
integral. The original Sharpening Deconvolution Transform (SDT)
technique [2]_ is expecting Tuch’s ODF without the \(r^2\) (see [3]_ for
the mathematical details). Now, this function supports ODF that have
been computed using the \(r^2\) term because the proper analytical
response function has be derived. For example, models such as DSI,
GQI, SHORE, CSA, Tensor, Multi-tensor ODFs, should now be deconvolved
with the r2_term=True.
Returns
——-
fodf_sh : ndarray ((sh_order_max+1)(sh_order_max+2)/2,)
Spherical harmonics coefficients of the constrained-regularized fiber
ODF
num_it : int
Number of iterations in the constrained-regularization used for
convergence
References
———-
.. [1] Tuch, D. MRM 2004. Q-Ball Imaging.
.. [2] Descoteaux, M., et al. IEEE TMI 2009. Deterministic and
Probabilistic Tractography Based on Complex Fibre Orientation
Distributions
.. [3] Descoteaux, M, PhD thesis, INRIA Sophia-Antipolis, 2008.
Sharpen odfs using the sharpening deconvolution transform [2]_
This function can be used to sharpen any smooth ODF spherical function. In
theory, this should only be used to sharpen QballModel ODFs, but in
practice, one can play with the deconvolution ratio and sharpen almost any
ODF-like spherical function. The constrained-regularization is stable and
will not only sharpen the ODF peaks but also regularize the noisy peaks.
Parameters
———-
odfs_sh : ndarray ((sh_order_max+1)*(sh_order_max+2)/2, )
array of odfs expressed as spherical harmonics coefficients
sphere : Sphere
sphere used to build the regularization matrix
basis : {None, ‘tournier07’, ‘descoteaux07’}
different spherical harmonic basis:
None for the default DIPY basis,
tournier07 for the Tournier 2007 [4]_ basis, and
descoteaux07 for the Descoteaux 2007 [3]_ basis
(None defaults to descoteaux07).
ratio : float,
ratio of the smallest vs the largest eigenvalue of the single prolate
tensor response function (\(\frac{\lambda_2}{\lambda_1}\))
sh_order_max : int
maximal SH order (l) of the SH representation
lambda_ : float
lambda parameter (see odfdeconv) (default 1.0)
tau : float
tau parameter in the L matrix construction (see odfdeconv)
(default 0.1)
r2_term : bool
True if ODF is computed from model that uses the \(r^2\) term in the
integral. Recall that Tuch’s ODF (used in Q-ball Imaging [1]_) and
the true normalized ODF definition differ from a \(r^2\) term in the ODF
integral. The original Sharpening Deconvolution Transform (SDT)
technique [2]_ is expecting Tuch’s ODF without the \(r^2\) (see [3]_ for
the mathematical details). Now, this function supports ODF that have
been computed using the \(r^2\) term because the proper analytical
response function has be derived. For example, models such as DSI,
GQI, SHORE, CSA, Tensor, Multi-tensor ODFs, should now be deconvolved
with the r2_term=True.
Returns
——-
fodf_sh : ndarray
sharpened odf expressed as spherical harmonics coefficients
References
———-
.. [1] Tuch, D. MRM 2004. Q-Ball Imaging.
.. [2] Descoteaux, M., et al. IEEE TMI 2009. Deterministic and
Probabilistic Tractography Based on Complex Fibre Orientation
Distributions
.. [3] Descoteaux, M., Angelino, E., Fitzgibbons, S. and Deriche, R.
Regularized, Fast, and Robust Analytical Q-ball Imaging.
Magn. Reson. Med. 2007;58:497-510.
.. [4] 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.
In CSD there is an important pre-processing step: the estimation of the
fiber response function. In order to do this, we look for voxels with very
anisotropic configurations. This function aims to accomplish that by
returning a mask of voxels within a ROI, that have a FA value above a
given threshold. For example we can use a ROI (20x20x20) at
the center of the volume and store the signal values for the voxels with
FA values higher than 0.7 (see [1]_).
In CSD there is an important pre-processing step: the estimation of the
fiber response function. In order to do this, we look for voxels with very
anisotropic configurations. This information can be obtained by using
csdeconv.mask_for_response_ssst() through a mask of selected voxels
(see[1]_). The present function uses such a mask to compute the ssst
response function.
For the response we also need to find the average S0 in the ROI. This is
possible using gtab.b0s_mask() we can find all the S0 volumes (which
correspond to b-values equal 0) in the dataset.
The response consists always of a prolate tensor created by averaging
the highest and second highest eigenvalues in the ROI with FA higher than
threshold. We also include the average S0s.
We also return the ratio which is used for the SDT models.
In CSD there is an important pre-processing step: the estimation of the
fiber response function. In order to do this, we look for voxels with very
anisotropic configurations. We get this information from
csdeconv.mask_for_response_ssst(), which returns a mask of selected voxels
(more details are available in the description of the function).
With the mask, we compute the response function by using
csdeconv.response_from_mask_ssst(), which returns the response and the
ratio (more details are available in the description of the function).
mask for recursive calibration, for example a white matter mask. It has
shape data.shape[0:3] and dtype=bool. Default: use the entire data
array.
sh_order_maxint, optional
maximal spherical harmonics order (l). Default: 8
peak_thrfloat, optional
peak threshold, how large the second peak can be relative to the first
peak in order to call it a single fiber population [1]. Default: 0.01
init_fafloat, optional
FA of the initial ‘fat’ response function (tensor). Default: 0.08
init_tracefloat, optional
trace of the initial ‘fat’ response function (tensor). Default: 0.0021
iterint, optional
maximum number of iterations for calibration. Default: 8.
convergencefloat, optional
convergence criterion, maximum relative change of SH
coefficients. Default: 0.001.
parallelbool, optional
Whether to use parallelization in peak-finding during the calibration
procedure. Default: True
num_processesint, optional
If parallel is True, the number of subprocesses to use
(default multiprocessing.cpu_count()). If < 0 the maximal number of
cores minus num_processes+1 is used (enter -1 to use as many
cores as possible). 0 raises an error.
sphereSphere, optional.
The sphere used for peak finding. Default: default_sphere.
In CSD there is an important pre-processing step: the estimation of the
fiber response function. Using an FA threshold is not a very robust method.
It is dependent on the dataset (non-informed used subjectivity), and still
depends on the diffusion tensor (FA and first eigenvector),
which has low accuracy at high b-value. This function recursively
calibrates the response function, for more information see [1].
cti_params: numpy.ndarray (…, 48)
All parameters estimated from the correlation tensor model.
Parameters are ordered as follows:
Three diffusion tensor’s eigenvalues
2. Three lines of the eigenvector matrix each containing the
first, second and third coordinates of the eigenvector
3. Fifteen elements of the kurtosis tensor
4. Twenty-One elements of the covariance tensor
gtab1: dipy.core.gradients.GradientTable
A GradientTable class instance for first DDE diffusion epoch
gtab2: dipy.core.gradients.GradientTable
A GradientTable class instance for second DDE diffusion epoch
S0float or ndarray (optional)
The non diffusion-weighted signal in every voxel, or across all
voxels. Default: 1
Returns the anisotropic Source of Kurtosis (K_aniso)
Notes
—–
The K_aniso is defined as[1]_:
:math::
[K_{aniso} = frac{6}{5} cdot frac{langle V_{lambda}(D_c)
rangle}{overline{D}^2}]
where: \(K_{aniso}\) is the anisotropic kurtosis,
\(\langle V_{\lambda}(D_c) \rangle\) represents the mean of the
variance of eigenvalues of the diffusion tensor,
\(\overline{D}\) is the mean of the diffusion tensor.
References
———-
.. [1] [NetoHe2020] Henriques, R.N., Jespersen, S.N., Shemesh, N., 2020.
Correlation tensor magnetic resonance imaging. Neuroimage 211.
doi: 10.1016/j.neuroimage.2020.116605
Returns the isotropic Source of Kurtosis (K_iso)
Notes
—–
The K_iso is defined as :
:math::
$$ K_{text{iso}} = 3 cdot frac{V(overline{D}^c)}{overline{D}^2} $$
where: :math:` K_{text{iso}} ` is the isotropic kurtosis,
(V({overline{D}^c})) represents the variance of the diffusion
tensor raised to the power c,
(overline{D}) is the mean of the diffusion tensor.
Returns the total excess kurtosis.
Notes
—–
\(K_total\) is defined as :
:math::
[Psi = frac{2}{5} cdot frac{D_{11}^2 + D_{22}^2 + D_{33}^2
+ 2D_{12}^2 + 2D_{13}^2 +
2D_{23}^2{overline{D}^2} -
frac{6}{5} ]
[{overline{W}} = frac{1}{5} cdot (W_{1111} + W_{2222}
+ W_{3333} + 2W_{1122}
+ 2W_{1133} + 2W_{2233}) ]
where (Psi) is a variable representing a part of the total
excess kurtosis,
(D_{ij}) are elements of the diffusion tensor,
(overline{D}) is the mean of the diffusion tensor.
{overline{W}} is the mean kurtosis,
(W_{ijkl}) are elements of the kurtosis tensor.
All parameters estimated from the correlation tensor model.
Parameters are ordered as follows:
Three diffusion tensor’s eigenvalues
2. Three lines of the eigenvector matrix each containing the
first, second and third coordinates of the eigenvector
3. Fifteen elements of the kurtosis tensor
4. Twenty-One elements of the covariance tensor
gtab1: dipy.core.gradients.GradientTable
A GradientTable class instance for first DDE diffusion epoch
gtab2: dipy.core.gradients.GradientTable
A GradientTable class instance for second DDE diffusion epoch
S0float or ndarray (optional)
The non diffusion-weighted signal in every voxel, or across all
voxels. Default: 1
Extract the diffusion tensor eigenvalues, the diffusion tensor
eigenvector matrix, and the 21 independent elements of the covariance
tensor, and the 15 independent elements of the kurtosis tensor from the
model parameters estimated from the CTI model
params: numpy.ndarray (…, 48)
All parameters estimated from the correlation tensor model.
Parameters are ordered as follows:
Three diffusion tensor’s eigenvalues
2. Three lines of the eigenvector matrix each containing the
first, second and third coordinates of the eigenvector
3. Fifteen elements of the kurtosis tensor
4. Twenty-One elements of the covariance tensor
cti_params: numpy.ndarray (…, 48)
All parameters estimated from the correlation tensor model.
Parameters are ordered as follows:
Three diffusion tensor’s eigenvalues
2. Three lines of the eigenvector matrix each containing the
first, second and third coordinates of the eigenvector
3. Fifteen elements of the kurtosis tensor
4. Twenty-One elements of the covariance tensor
gtab1: dipy.core.gradients.GradientTable
A GradientTable class instance for first DDE diffusion epoch
gtab2: dipy.core.gradients.GradientTable
A GradientTable class instance for second DDE diffusion epoch
S0float or ndarray (optional)
The non diffusion-weighted signal in every voxel, or across all
voxels. Default: 1
Design matrix holding the covariants used to solve for the regression
coefficients.
dataarray (g)
Data or response variables holding the data.
inverse_design_matrixarray (43, g)
Inverse of the design matrix.
weightsbool, optional
Parameter indicating whether weights are used. Default: True.
min_diffusivityfloat, optional
Because negative eigenvalues are not physical and small eigenvalues,
much smaller than the diffusion weighting, cause quite a lot of noise
in metrics such as fa, diffusivity values smaller than min_diffusivity
are replaced with min_diffusivity.
dki_params : ndarray (x, y, z, 27) or (n, 27)
All parameters estimated from the diffusion kurtosis model.
Parameters are ordered as follows:
Three diffusion tensor’s eigenvalues
2. Three lines of the eigenvector matrix each containing the
first, second and third coordinates of the eigenvector
3. Fifteen elements of the kurtosis tensor
S0float or ndarray (optional)
The non diffusion-weighted signal in every voxel, or across all
voxels. Default: 1
Class instance containing the Diffusion Kurtosis Model for the fit
model_paramsndarray (x, y, z, 27) or (n, 27)
All parameters estimated from the diffusion kurtosis model,
not including S0.
Parameters are ordered as follows:
1) Three diffusion tensor’s eigenvalues
2) Three lines of the eigenvector matrix each containing the
first, second and third coordinates of the eigenvector
To keep kurtosis values within a plausible biophysical range, axial
kurtosis values that are smaller than min_kurtosis are replaced
with -3./7 (theoretical kurtosis limit
for regions that consist of water confined to spherical pores [2]_)
max_kurtosisfloat (optional)
To keep kurtosis values within a plausible biophysical range, axial
kurtosis values that are larger than max_kurtosis are replaced
with max_kurtosis. Default = 10
analyticalbool (optional)
If True, AK is calculated from rotated diffusion kurtosis tensor,
otherwise it will be computed from the apparent diffusion kurtosis
values along the principal axis of the diffusion tensor
(see notes). Default is set to True.
AK can be sampled from the principal axis of the diffusion tensor:
\[AK = K(\mathbf{\mathbf{e}_1)\]
Although both approaches leads to an exact calculation of AK, the
first approach will be referred to as the analytical method while the
second approach will be referred to as the numerical method based on
their analogy to the estimation strategies for MK and RK.
Calculate the apparent kurtosis coefficient (AKC) in each
direction on the sphere for each voxel in the data
Parameters
———-
sphere : Sphere class instance
Returns
——-
akc : ndarray
The estimates of the apparent kurtosis coefficient in every
direction on the input sphere
Notes
—–
For each sphere direction with coordinates \((n_{1}, n_{2}, n_{3})\), the
calculation of AKC is done using formula:
.. math ::
AKC(n)=frac{MD^{2}}{ADC(n)^{2}}sum_{i=1}^{3}sum_{j=1}^{3}
sum_{k=1}^{3}sum_{l=1}^{3}n_{i}n_{j}n_{k}n_{l}W_{ijkl}
where \(W_{ijkl}\) are the elements of the kurtosis tensor, MD the mean
diffusivity and ADC the apparent diffusion coefficient computed as:
.. math ::
ADC(n)=sum_{i=1}^{3}sum_{j=1}^{3}n_{i}n_{j}D_{ij}
where \(D_{ij}\) are the elements of the diffusion tensor.
Return the kurtosis tensor (KFA) [1]_
Notes
—–
The KFA is defined as [1]_:
.. math::
KFA equiv
frac{||mathbf{W} - MKT mathbf{I}^{(4)}||_F}{||mathbf{W}||_F}
where \(W\) is the kurtosis tensor, MKT the kurtosis tensor mean, \(I^(4)\)
is the fully symmetric rank 2 isotropic tensor and \(||...||_F\) is the
tensor’s Frobenius norm [1]_.
References
———-
.. [1] Glenn, G. R., Helpern, J. A., Tabesh, A., and Jensen, J. H.
(2015). Quantitative assessment of diffusional kurtosis
anisotropy. NMR in Biomedicine 28, 448–459. doi:10.1002/nbm.3271
The sphere providing sample directions for the initial search of
the maximum value of kurtosis.
gtolfloat, optional
This input is to refine kurtosis maximum under the precision of the
directions sampled on the sphere class instance. The gradient of
the convergence procedure must be less than gtol before successful
termination. If gtol is None, fiber direction is directly taken
from the initial sampled directions of the given sphere object
Compute mean kurtosis (MK) from the kurtosis tensor
Parameters
———-
min_kurtosis : float (optional)
To keep kurtosis values within a plausible biophysical range, mean
kurtosis values that are smaller than min_kurtosis are replaced
with min_kurtosis. Default = -3./7 (theoretical kurtosis limit
for regions that consist of water confined to spherical pores [4]_)
max_kurtosis : float (optional)
To keep kurtosis values within a plausible biophysical range, mean
kurtosis values that are larger than max_kurtosis are replaced
with max_kurtosis. Default = 10
analytical : bool (optional)
If True, MK is calculated using its analytical solution, otherwise
an exact numerical estimator is used (see Notes). Default is set to
True.
Returns
——-
mk : array
Calculated MK.
Notes
—–
The MK is defined as the average of directional kurtosis coefficients
across all spatial directions, which can be formulated by the following
surface integral[1]_:
.. math::
MK equiv frac{1}{4pi} int dOmega_mathbf{n} K(mathbf{n})
This integral can be numerically solved by averaging directional
kurtosis values sampled for directions of a spherical t-design [2]_.
Alternatively, MK can be solved from the analytical solution derived by
Tabesh et al. [3]_. This solution is given by:
.. math::
MK=F_1(lambda_1,lambda_2,lambda_3)hat{W}_{1111}+
F_1(lambda_2,lambda_1,lambda_3)hat{W}_{2222}+
F_1(lambda_3,lambda_2,lambda_1)hat{W}_{3333}+ \
F_2(lambda_1,lambda_2,lambda_3)hat{W}_{2233}+
F_2(lambda_2,lambda_1,lambda_3)hat{W}_{1133}+
F_2(lambda_3,lambda_2,lambda_1)hat{W}_{1122}
where \(\hat{W}_{ijkl}\) are the components of the \(W\) tensor in the
coordinates system defined by the eigenvectors of the diffusion tensor
\(\mathbf{D}\) and
.. math::
F_1(lambda_1,lambda_2,lambda_3)=
frac{(lambda_1+lambda_2+lambda_3)^2}
{18(lambda_1-lambda_2)(lambda_1-lambda_3)}
[frac{sqrt{lambda_2lambda_3}}{lambda_1}
R_F(frac{lambda_1}{lambda_2},frac{lambda_1}{lambda_3},1)+\
frac{3lambda_1^2-lambda_1lambda_2-lambda_2lambda_3-
lambda_1lambda_3}
{3lambda_1 sqrt{lambda_2 lambda_3}}
R_D(frac{lambda_1}{lambda_2},frac{lambda_1}{lambda_3},1)-1 ]
F_2(lambda_1,lambda_2,lambda_3)=
frac{(lambda_1+lambda_2+lambda_3)^2}
{3(lambda_2-lambda_3)^2}
[frac{lambda_2+lambda_3}{sqrt{lambda_2lambda_3}}
R_F(frac{lambda_1}{lambda_2},frac{lambda_1}{lambda_3},1)+\
frac{2lambda_1-lambda_2-lambda_3}{3sqrt{lambda_2 lambda_3}}
R_D(frac{lambda_1}{lambda_2},frac{lambda_1}{lambda_3},1)-2]
where \(R_f\) and \(R_d\) are the Carlson’s elliptic integrals.
References
———-
.. [1] Jensen, J.H., Helpern, J.A., 2010. MRI quantification of
non-Gaussian water diffusion by kurtosis analysis. NMR in
Biomedicine 23(7): 698-710
.. [2] Hardin, R.H., Sloane, N.J.A., 1996. McLaren’s Improved Snub Cube
and Other New Spherical Designs in Three Dimensions. Discrete
and Computational Geometry 15, 429-441.
.. [3] Tabesh, A., Jensen, J.H., Ardekani, B.A., Helpern, J.A., 2011.
Estimation of tensors and tensor-derived measures in diffusional
kurtosis imaging. Magn Reson Med. 65(3), 823-836
.. [4] Barmpoutis, A., & Zhuo, J., 2011. Diffusion kurtosis imaging:
Robust estimation from DW-MRI using homogeneous polynomials.
Proceedings of the 8th {IEEE} International Symposium on
Biomedical Imaging: From Nano to Macro, ISBI 2011, 262-265.
doi: 10.1109/ISBI.2011.5872402
To keep kurtosis values within a plausible biophysical range, mean
kurtosis values that are smaller than min_kurtosis are replaced
with min_kurtosis. Default = -3./7 (theoretical kurtosis limit
for regions that consist of water confined to spherical pores [2]_)
max_kurtosisfloat (optional)
To keep kurtosis values within a plausible biophysical range, mean
kurtosis values that are larger than max_kurtosis are replaced
with max_kurtosis. Default = 10
Given a DKI model fit, predict the signal on the vertices of a
gradient table
Parameters
———-
gtab : a GradientTable class instance
The gradient table for this prediction
S0 : float or ndarray (optional)
The non diffusion-weighted signal in every voxel, or across all
voxels. Default: 1
Notes
—–
The predicted signal is given by:
.. math::
S(n,b)=S_{0}e^{-bD(n)+frac{1}{6}b^{2}D(n)^{2}K(n)}
\(\mathbf{D(n)}\) and \(\mathbf{K(n)}\) can be computed from the DT and KT
using the following equations:
.. math::
D(n)=sum_{i=1}^{3}sum_{j=1}^{3}n_{i}n_{j}D_{ij}
and
.. math::
K(n)=frac{MD^{2}}{D(n)^{2}}sum_{i=1}^{3}sum_{j=1}^{3}
sum_{k=1}^{3}sum_{l=1}^{3}n_{i}n_{j}n_{k}n_{l}W_{ijkl}
where \(D_{ij}\) and \(W_{ijkl}\) are the elements of the second-order DT
and the fourth-order KT tensors, respectively, and \(MD\) is the mean
diffusivity.
To keep kurtosis values within a plausible biophysical range,
radial kurtosis values that are smaller than min_kurtosis are
replaced with min_kurtosis. Default = -3./7 (theoretical kurtosis
limit for regions that consist of water confined to spherical pores
[3]_)
max_kurtosisfloat (optional)
To keep kurtosis values within a plausible biophysical range,
radial kurtosis values that are larger than max_kurtosis are
replaced with max_kurtosis. Default = 10
analyticalbool (optional)
If True, RK is calculated using its analytical solution, otherwise
an exact numerical estimator is used (see Notes). Default is set to
True
Because negative eigenvalues are not physical and small eigenvalues
cause quite a lot of noise in diffusion-based metrics, diffusivity
values smaller than min_diffusivity are replaced with
min_diffusivity. Default = 0
Because high-amplitude negative values of kurtosis are not physically
and biologicaly pluasible, and these cause artefacts in
kurtosis-based measures, directional kurtosis values smaller than
min_kurtosis are replaced with min_kurtosis. Default = -3./7
(theoretical kurtosis limit for regions that consist of water confined
to spherical pores [2]_)
adcndarray(g,) (optional)
Apparent diffusion coefficient (adc) in all g directions of a sphere
for a single voxel.
advndarray(g,) (optional)
Apparent diffusion variance coefficient (advc) in all g directions of
a sphere for a single voxel.
Because negative eigenvalues are not physical and small eigenvalues
cause quite a lot of noise in diffusion-based metrics, diffusivity
values smaller than min_diffusivity are replaced with
min_diffusivity. Default = 0
min_kurtosisfloat (optional)
Because high-amplitude negative values of kurtosis are not physically
and biologicaly pluasible, and these cause artefacts in
kurtosis-based measures, directional kurtosis values smaller than
min_kurtosis are replaced with min_kurtosis. Default = -3./7
(theoretical kurtosis limit for regions that consist of water confined
to spherical pores [2]_)
adcndarray(g,) (optional)
Apparent diffusion coefficient (adc) in all g directions of a sphere
for a single voxel.
advndarray(g,) (optional)
Apparent diffusion variance (advc) in all g directions of a sphere for
a single voxel.
Calculate the apparent kurtosis coefficient (AKC) in each direction
of a sphere [1]_
Parameters
———-
dki_params : ndarray (x, y, z, 27) or (n, 27)
All parameters estimated from the diffusion kurtosis model.
Parameters are ordered as follows:
1) Three diffusion tensor’s eigenvalues
2) Three lines of the eigenvector matrix each containing the first,
second and third coordinates of the eigenvectors respectively
3) Fifteen elements of the kurtosis tensor
sphere : a Sphere class instance
The AKC will be calculated for each of the vertices in the sphere
min_diffusivity : float (optional)
Because negative eigenvalues are not physical and small eigenvalues
cause quite a lot of noise in diffusion-based metrics, diffusivity
values smaller than min_diffusivity are replaced with
min_diffusivity. Default = 0
min_kurtosis : float (optional)
Because high-amplitude negative values of kurtosis are not physically
and biologicaly pluasible, and these cause artefacts in
kurtosis-based measures, directional kurtosis values smaller than
min_kurtosis are replaced with min_kurtosis. Default = -3./7
(theoretical kurtosis limit for regions that consist of water confined
to spherical pores [2]_)
Returns
——-
akc : ndarray (x, y, z, g) or (n, g)
Apparent kurtosis coefficient (AKC) for all g directions of a sphere.
Notes
—–
For each sphere direction with coordinates \((n_{1}, n_{2}, n_{3})\), the
calculation of AKC is done using formula [1]_:
.. math ::
AKC(n)=frac{MD^{2}}{ADC(n)^{2}}sum_{i=1}^{3}sum_{j=1}^{3}
sum_{k=1}^{3}sum_{l=1}^{3}n_{i}n_{j}n_{k}n_{l}W_{ijkl}
where \(W_{ijkl}\) are the elements of the kurtosis tensor, MD the mean
diffusivity and ADC the apparent diffusion coefficient computed as:
.. math ::
ADC(n)=sum_{i=1}^{3}sum_{j=1}^{3}n_{i}n_{j}D_{ij}
where \(D_{ij}\) are the elements of the diffusion tensor.
References
———-
.. [1] Neto Henriques R, Correia MM, Nunes RG, Ferreira HA (2015).
Exploring the 3D geometry of the diffusion kurtosis tensor -
Impact on the development of robust tractography procedures and
novel biomarkers, NeuroImage 111: 85-99
.. [2] Barmpoutis, A., & Zhuo, J., 2011. Diffusion kurtosis imaging:
Robust estimation from DW-MRI using homogeneous polynomials.
Proceedings of the 8th {IEEE} International Symposium on
Biomedical Imaging: From Nano to Macro, ISBI 2011, 262-265.
doi: 10.1109/ISBI.2011.5872402
Compute mean kurtosis (MK) from the kurtosis tensor
Parameters
———-
dki_params : ndarray (x, y, z, 27) or (n, 27)
All parameters estimated from the diffusion kurtosis model.
Parameters are ordered as follows:
1) Three diffusion tensor’s eigenvalues
2) Three lines of the eigenvector matrix each containing the first,
second and third coordinates of the eigenvector
3) Fifteen elements of the kurtosis tensor
min_kurtosis : float (optional)
To keep kurtosis values within a plausible biophysical range, mean
kurtosis values that are smaller than min_kurtosis are replaced with
min_kurtosis. Default = -3./7 (theoretical kurtosis limit for regions
that consist of water confined to spherical pores [4]_)
max_kurtosis : float (optional)
To keep kurtosis values within a plausible biophysical range, mean
kurtosis values that are larger than max_kurtosis are replaced with
max_kurtosis. Default = 10
analytical : bool (optional)
If True, MK is calculated using its analytical solution, otherwise an
exact numerical estimator is used (see Notes). Default is set to True
Returns
——-
mk : array
Calculated MK.
Notes
—–
The MK is defined as the average of directional kurtosis coefficients
across all spatial directions, which can be formulated by the following
surface integral[1]_:
.. math::
MK equiv frac{1}{4pi} int dOmega_mathbf{n} K(mathbf{n})
This integral can be numerically solved by averaging directional
kurtosis values sampled for directions of a spherical t-design [2]_.
Alternatively, MK can be solved from the analytical solution derived by
Tabesh et al. [3]_. This solution is given by:
.. math::
MK=F_1(lambda_1,lambda_2,lambda_3)hat{W}_{1111}+
F_1(lambda_2,lambda_1,lambda_3)hat{W}_{2222}+
F_1(lambda_3,lambda_2,lambda_1)hat{W}_{3333}+ \
F_2(lambda_1,lambda_2,lambda_3)hat{W}_{2233}+
F_2(lambda_2,lambda_1,lambda_3)hat{W}_{1133}+
F_2(lambda_3,lambda_2,lambda_1)hat{W}_{1122}
where \(\hat{W}_{ijkl}\) are the components of the \(W\) tensor in the
coordinates system defined by the eigenvectors of the diffusion tensor
\(\mathbf{D}\) and
.. math::
F_1(lambda_1,lambda_2,lambda_3)=
frac{(lambda_1+lambda_2+lambda_3)^2}
{18(lambda_1-lambda_2)(lambda_1-lambda_3)}
[frac{sqrt{lambda_2lambda_3}}{lambda_1}
R_F(frac{lambda_1}{lambda_2},frac{lambda_1}{lambda_3},1)+\
frac{3lambda_1^2-lambda_1lambda_2-lambda_2lambda_3-
lambda_1lambda_3}
{3lambda_1 sqrt{lambda_2 lambda_3}}
R_D(frac{lambda_1}{lambda_2},frac{lambda_1}{lambda_3},1)-1 ]
F_2(lambda_1,lambda_2,lambda_3)=
frac{(lambda_1+lambda_2+lambda_3)^2}
{3(lambda_2-lambda_3)^2}
[frac{lambda_2+lambda_3}{sqrt{lambda_2lambda_3}}
R_F(frac{lambda_1}{lambda_2},frac{lambda_1}{lambda_3},1)+\
frac{2lambda_1-lambda_2-lambda_3}{3sqrt{lambda_2 lambda_3}}
R_D(frac{lambda_1}{lambda_2},frac{lambda_1}{lambda_3},1)-2]
where \(R_f\) and \(R_d\) are the Carlson’s elliptic integrals.
References
———-
.. [1] Jensen, J.H., Helpern, J.A., 2010. MRI quantification of
non-Gaussian water diffusion by kurtosis analysis. NMR in
Biomedicine 23(7): 698-710
.. [2] Hardin, R.H., Sloane, N.J.A., 1996. McLaren’s Improved Snub Cube and
Other New Spherical Designs in Three Dimensions. Discrete and
Computational Geometry 15, 429-441.
.. [3] Tabesh, A., Jensen, J.H., Ardekani, B.A., Helpern, J.A., 2011.
Estimation of tensors and tensor-derived measures in diffusional
kurtosis imaging. Magn Reson Med. 65(3), 823-836
.. [4] Barmpoutis, A., & Zhuo, J., 2011. Diffusion kurtosis imaging:
Robust estimation from DW-MRI using homogeneous polynomials.
Proceedings of the 8th {IEEE} International Symposium on
Biomedical Imaging: From Nano to Macro, ISBI 2011, 262-265.
doi: 10.1109/ISBI.2011.5872402
dki_params : ndarray (x, y, z, 27) or (n, 27)
All parameters estimated from the diffusion kurtosis model.
Parameters are ordered as follows:
Three diffusion tensor’s eigenvalues
Three lines of the eigenvector matrix each containing the first,
second and third coordinates of the eigenvector
Fifteen elements of the kurtosis tensor
min_kurtosisfloat (optional)
To keep kurtosis values within a plausible biophysical range, radial
kurtosis values that are smaller than min_kurtosis are replaced with
min_kurtosis. Default = -3./7 (theoretical kurtosis limit for regions
that consist of water confined to spherical pores [3]_)
max_kurtosisfloat (optional)
To keep kurtosis values within a plausible biophysical range, radial
kurtosis values that are larger than max_kurtosis are replaced with
max_kurtosis. Default = 10
analyticalbool (optional)
If True, RK is calculated using its analytical solution, otherwise an
exact numerical estimator is used (see Notes). Default is set to True.
dki_params : ndarray (x, y, z, 27) or (n, 27)
All parameters estimated from the diffusion kurtosis model.
Parameters are ordered as follows:
Three diffusion tensor’s eigenvalues
Three lines of the eigenvector matrix each containing the first,
second and third coordinates of the eigenvector
Fifteen elements of the kurtosis tensor
min_kurtosisfloat (optional)
To keep kurtosis values within a plausible biophysical range, axial
kurtosis values that are smaller than min_kurtosis are replaced with
min_kurtosis. Default = -3./7 (theoretical kurtosis limit for regions
that consist of water confined to spherical pores [3]_)
max_kurtosisfloat (optional)
To keep kurtosis values within a plausible biophysical range, axial
kurtosis values that are larger than max_kurtosis are replaced with
max_kurtosis. Default = 10
analyticalbool (optional)
If True, AK is calculated from rotated diffusion kurtosis tensor,
otherwise it will be computed from the apparent diffusion kurtosis
values along the principal axis of the diffusion tensor (see notes).
Default is set to True.
AK can be sampled from the principal axis of the diffusion tensor:
\[AK = K(\mathbf{\mathbf{e}_1)\]
Although both approaches leads to an exact calculation of AK, the first
approach will be referred to as the analytical method while the second
approach will be referred to as the numerical method based on their analogy
to the estimation strategies for MK and RK.
dki_params : ndarray (x, y, z, 27) or (n, 27)
All parameters estimated from the diffusion kurtosis model.
Parameters are ordered as follows:
Three diffusion tensor’s eingenvalues
Three lines of the eigenvector matrix each containing the first,
second and third coordinates of the eigenvector
Fifteen elements of the kurtosis tensor
sphereSphere class instance, optional
The sphere providing sample directions for the initial search of the
maximal value of kurtosis.
gtolfloat, optional
This input is to refine kurtosis maximum under the precision of the
directions sampled on the sphere class instance. The gradient of the
convergence procedure must be less than gtol before successful
termination. If gtol is None, fiber direction is directly taken from
the initial sampled directions of the given sphere object
maskndarray
A boolean array used to mark the coordinates in the data that should be
analyzed that has the shape dki_params.shape[:-1]
dki_params : ndarray (x, y, z, 27) or (n, 27)
All parameters estimated from the diffusion kurtosis model.
Parameters are ordered as follows:
Three diffusion tensor’s eigenvalues
Three lines of the eigenvector matrix each containing the first,
second and third coordinates of the eigenvector
Fifteen elements of the kurtosis tensor
min_kurtosisfloat (optional)
To keep kurtosis values within a plausible biophysical range, mean
kurtosis values that are smaller than min_kurtosis are replaced with
min_kurtosis. Default = -3./7 (theoretical kurtosis limit for regions
that consist of water confined to spherical pores [2]_)
max_kurtosisfloat (optional)
To keep kurtosis values within a plausible biophysical range, mean
kurtosis values that are larger than max_kurtosis are replaced with
max_kurtosis. Default = 10
Compute the anisotropy of the kurtosis tensor (KFA) [1]_
Parameters
———-
dki_params : ndarray (x, y, z, 27) or (n, 27)
All parameters estimated from the diffusion kurtosis model.
Parameters are ordered as follows:
1) Three diffusion tensor’s eigenvalues
2) Three lines of the eigenvector matrix each containing the first,
second and third coordinates of the eigenvector
3) Fifteen elements of the kurtosis tensor
Returns
——-
kfa : array
Calculated mean kurtosis tensor.
Notes
—–
The KFA is defined as [1]_:
.. math::
KFA equiv
frac{||mathbf{W} - MKT mathbf{I}^{(4)}||_F}{||mathbf{W}||_F}
where \(W\) is the kurtosis tensor, MKT the kurtosis tensor mean, \(I^(4)\) is
the fully symmetric rank 2 isotropic tensor and \(||...||_F\) is the tensor’s
Frobenius norm [1]_.
References
———-
.. [1] Glenn, G. R., Helpern, J. A., Tabesh, A., and Jensen, J. H. (2015).
Quantitative assessment of diffusional kurtosis anisotropy.
NMR in Biomedicine 28, 448–459. doi:10.1002/nbm.3271
Design matrix holding the covariants used to solve for the regression
coefficients.
dataarray (g)
Data or response variables holding the data.
inverse_design_matrixarray (22, g)
Inverse of the design matrix.
return_S0_hatbool, optional
Boolean to return (True) or not (False) the S0 values for the fit.
weightsbool, optional
Parameter indicating whether weights are used. Default: True.
min_diffusivityfloat, optional
Because negative eigenvalues are not physical and small eigenvalues,
much smaller than the diffusion weighting, cause quite a lot of noise
in metrics such as fa, diffusivity values smaller than
min_diffusivity are replaced with min_diffusivity.
Design matrix holding the covariants used to solve for the regression
coefficients.
dataarray (g)
Data or response variables holding the data.
inverse_design_matrixarray (22, g)
Inverse of the design matrix.
sdpPositiveDefiniteLeastSquares instance
A CVXPY representation of a regularized least squares optimization
problem.
return_S0_hatbool, optional
Boolean to return (True) or not (False) the S0 values for the fit.
weightsbool, optional
Parameter indicating whether weights are used. Default: True.
min_diffusivityfloat, optional
Because negative eigenvalues are not physical and small eigenvalues,
much smaller than the diffusion weighting, cause quite a lot of noise
in metrics such as fa, diffusivity values smaller than
min_diffusivity are replaced with min_diffusivity.
cvxpy_solverstr, optional
cvxpy solver name. Optionally optimize the positivity constraint with a
particular cvxpy solver. See https://www.cvxpy.org/ for details.
Default: None (cvxpy chooses its own solver).
Vector with the 15 independent elements of the kurtosis tensor
Basisarray (3, 3)
Vectors of the basis column-wise oriented
indsarray(m, 4) (optional)
Array of vectors containing the four indexes of m specific elements of
the rotated kurtosis tensor. If not specified all 15 elements of the
rotated kurtosis tensor are computed.
Vector with the m independent elements of the rotated kurtosis tensor.
If ‘indices’ is not specified all 15 elements of the rotated kurtosis
tensor are computed.
Extract the diffusion tensor eigenvalues, the diffusion tensor
eigenvector matrix, and the 15 independent elements of the kurtosis tensor
from the model parameters estimated from the DKI model
An 4D matrix containing the diffusion-weighted data.
maskarray
A boolean array used to mark the coordinates in the data that
should be analyzed that has the shape data.shape[-1]
sphereSphere class instance, optional
The sphere providing sample directions for the initial search of
the maximal value of kurtosis.
gtolfloat, optional
This input is to refine kurtosis maxima under the precision of the
directions sampled on the sphere class instance. The gradient of
the convergence procedure must be less than gtol before successful
termination. If gtol is None, fiber direction is directly taken
from the initial sampled directions of the given sphere object
awf_onlybool, optiomal
If set to true only the axonal volume fraction is computed from
the kurtosis tensor. Default = False
In the original article of DKI microstructural model [1]_, the hindered
and restricted tensors were defined as the intra-cellular and
extra-cellular diffusion compartments respectively.
In the original article of DKI microstructural model [1]_, the hindered
and restricted tensors were defined as the intra-cellular and
extra-cellular diffusion compartments respectively.
Given a DKI microstructural model fit, predict the signal on the
vertices of a gradient table
gtab : a GradientTable class instance
The gradient table for this prediction
S0 : float or ndarray (optional)
The non diffusion-weighted signal in every voxel, or across all
voxels. Default: 1
Notes
—–
The predicted signal is given by:
\(S(\theta, b) = S_0 * [f * e^{-b ADC_{r}} + (1-f) * e^{-b ADC_{h}]\),
where \(ADC_{r}\) and \(ADC_{h}\) are the apparent diffusion coefficients
of the diffusion hindered and restricted compartment for a given
direction \(\theta\), \(b\) is the b value provided in the GradientTable
input for that direction, \(f\) is the volume fraction of the restricted
diffusion compartment (also known as the axonal water fraction).
Returns the tortuosity of the hindered diffusion which is defined
by ADe / RDe, where ADe and RDe are the axial and radial diffusivities
of the hindered compartment [1]_.
All parameters estimated from the diffusion kurtosis model.
Parameters are ordered as follows:
Three diffusion tensor’s eigenvalues
Three lines of the eigenvector matrix each containing the first,
second and third coordinates of the eigenvector
Fifteen elements of the kurtosis tensor
sphereSphere class instance, optional
The sphere providing sample directions for the initial search of the
maximal value of kurtosis.
gtolfloat, optional
This input is to refine kurtosis maxima under the precision of the
directions sampled on the sphere class instance. The gradient of the
convergence procedure must be less than gtol before successful
termination. If gtol is None, fiber direction is directly taken from
the initial sampled directions of the given sphere object
maskndarray
A boolean array used to mark the coordinates in the data that should be
analyzed that has the shape dki_params.shape[:-1]
All parameters estimated from the diffusion kurtosis model.
Parameters are ordered as follows:
Three diffusion tensor’s eigenvalues
Three lines of the eigenvector matrix each containing the first,
second and third coordinates of the eigenvector
Fifteen elements of the kurtosis tensor
sphereSphere class instance, optional
The sphere providing sample directions to sample the restricted and
hindered cellular diffusion tensors. For more details see Fieremans
et al., 2011.
awfndarray (optional)
Array containing values of the axonal water fraction that has the shape
dki_params.shape[:-1]. If not given this will be automatically computed
using axonal_water_fraction()” with function’s default precision.
maskndarray (optional)
A boolean array used to mark the coordinates in the data that should be
analyzed that has the shape dki_params.shape[:-1]
In the original article of DKI microstructural model [1]_, the hindered and
restricted tensors were defined as the intra-cellular and extra-cellular
diffusion compartments respectively.
Signal prediction given the DKI microstructure model parameters.
Parameters
———-
params : ndarray (x, y, z, 40) or (n, 40)
All parameters estimated from the diffusion kurtosis microstructure model.
Parameters are ordered as follows:
1) Three diffusion tensor’s eigenvalues
2) Three lines of the eigenvector matrix each containing the
first, second and third coordinates of the eigenvector
3) Fifteen elements of the kurtosis tensor
4) Six elements of the hindered diffusion tensor
5) Six elements of the restricted diffusion tensor
6) Axonal water fraction
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
Returns
——-
S : (…, N) ndarray
Simulated signal based on the DKI microstructure model
Notes
—–
1) The predicted signal is given by:
\(S(\theta, b) = S_0 * [f * e^{-b ADC_{r}} + (1-f) * e^{-b ADC_{h}]\), where
:math:` ADC_{r} and ADC_{h} are the apparent diffusion coefficients of the
diffusion hindered and restricted compartment for a given direction
theta:math:, b:math: is the b value provided in the GradientTable input for that
direction, `f$ is the volume fraction of the restricted diffusion
compartment (also known as the axonal water fraction).
2) In the original article of DKI microstructural model [1]_, the hindered
and restricted tensors were defined as the intra-cellular and
extra-cellular diffusion compartments respectively.
Diffusion Spectrum Imaging
The theoretical idea underlying this method is that the diffusion
propagator \(P(\mathbf{r})\) (probability density function of the average
spin displacements) can be estimated by applying 3D FFT to the signal
values \(S(\mathbf{q})\)
..math::
:nowrap:
begin{eqnarray}
P(mathbf{r}) & = & S_{0}^{-1}int S(mathbf{q})exp(-i2pimathbf{q}cdotmathbf{r})dmathbf{r}
end{eqnarray}
where \(\mathbf{r}\) is the displacement vector and \(\mathbf{q}\) is the
wave vector which corresponds to different gradient directions. Method
used to calculate the ODFs. Here we implement the method proposed by
Wedeen et al. [1]_.
The main assumption for this model is fast gradient switching and that
the acquisition gradients will sit on a keyhole Cartesian grid in
q_space [3]_.
Parameters
———-
gtab : GradientTable,
Gradient directions and bvalues container class
qgrid_size : int,
has to be an odd number. Sets the size of the q_space grid.
For example if qgrid_size is 17 then the shape of the grid will be
(17,17,17).
r_start : float,
ODF is sampled radially in the PDF. This parameters shows where the
sampling should start.
r_end : float,
Radial endpoint of ODF sampling
r_step : float,
Step size of the ODf sampling from r_start to r_end
filter_width : float,
Strength of the hanning filter
References
———-
.. [1] Wedeen V.J et al., “Mapping Complex Tissue Architecture With
Diffusion Spectrum Magnetic Resonance Imaging”, MRM 2005.
.. [2] Canales-Rodriguez E.J et al., “Deconvolution in Diffusion
Spectrum Imaging”, Neuroimage, 2010.
.. [3] Garyfallidis E, “Towards an accurate brain tractography”, PhD
thesis, University of Cambridge, 2012.
Examples
——–
In this example where we provide the data, a gradient table
and a reconstruction sphere, we calculate generalized FA for the first
voxel in the data with the reconstruction performed using DSI.
>>> import warnings
>>> from dipy.data import dsi_voxels, default_sphere
>>> data, gtab = dsi_voxels()
>>> from dipy.reconst.dsi import DiffusionSpectrumModel
>>> ds = DiffusionSpectrumModel(gtab)
>>> dsfit = ds.fit(data)
>>> from dipy.reconst.odf import gfa
>>> np.round(gfa(dsfit.odf(default_sphere))[0, 0, 0], 2)
0.11
Notes
—–
A. Have in mind that DSI expects gradients on both hemispheres. If your
gradients span only one hemisphere you need to duplicate the data and
project them to the other hemisphere before calling this class. The
function dipy.reconst.dsi.half_to_full_qspace can be used for this
purpose.
B. If you increase the size of the grid (parameter qgrid_size) you will
most likely also need to update the r_* parameters. This is because
the added zero padding from the increase of gqrid_size also introduces
a scaling of the PDF.
C. We assume that data only one b0 volume is provided.
See Also
——–
dipy.reconst.gqi.GeneralizedQSampling
Calculates the mean squared displacement on the discrete propagator
..math::
:nowrap:
begin{equation}
MSD:{DSI}=int_{-infty}^{infty}int_{-infty}^{infty}int_{-infty}^{infty} P(hat{mathbf{r}}) cdot hat{mathbf{r}}^{2} dr_x dr_y dr_z
end{equation}
where \(\hat{\mathbf{r}}\) is a point in the 3D Propagator space
(see Wu et al. [1]_).
Parameters
———-
normalized : boolean, optional
Whether to normalize the propagator by its sum in order to obtain a
pdf. Default: True
Returns
——-
msd : float
the mean square displacement
References
———-
.. [1] Wu Y. et al., “Hybrid diffusion imaging”, NeuroImage, vol 36,
p. 617-629, 2007.
Calculates the real discrete odf for a given discrete sphere
..math::
:nowrap:
begin{equation}
psi_{DSI}(hat{mathbf{u}})=int_{0}^{infty}P(rhat{mathbf{u}})r^{2}dr
end{equation}
where \(\hat{\mathbf{u}}\) is the unit vector which corresponds to a
sphere point.
Calculates the return to origin probability from the propagator, which is
the propagator evaluated at zero (see Descoteaux et Al. [1]_,
Tuch [2]_, Wu et al. [3]_)
rtop = P(0)
Diffusion Spectrum Deconvolution
The idea is to remove the convolution on the DSI propagator that is
caused by the truncation of the q-space in the DSI sampling.
..math::
:nowrap:
begin{eqnarray*}
P_{dsi}(mathbf{r}) & = & S_{0}^{-1}iiintlimits_{| mathbf{q} | le mathbf{q_{max}}} S(mathbf{q})exp(-i2pimathbf{q}cdotmathbf{r})dmathbf{q} \
& = & S_{0}^{-1}iiintlimits_{mathbf{q}} left( S(mathbf{q}) cdot M(mathbf{q}) right) exp(-i2pimathbf{q}cdotmathbf{r})dmathbf{q} \
& = & P(mathbf{r}) otimes left( S_{0}^{-1}iiintlimits_{mathbf{q}} M(mathbf{q}) exp(-i2pimathbf{q}cdotmathbf{r})dmathbf{q} right) \
end{eqnarray*}
where \(\mathbf{r}\) is the displacement vector and \(\mathbf{q}\) is the
wave vector which corresponds to different gradient directions,
\(M(\mathbf{q})\) is a mask corresponding to your q-space sampling and
\(\otimes\) is the convolution operator [1]_.
Parameters
———-
gtab : GradientTable,
Gradient directions and bvalues container class
qgrid_size : int,
has to be an odd number. Sets the size of the q_space grid.
For example if qgrid_size is 35 then the shape of the grid will be
(35,35,35).
r_start : float,
ODF is sampled radially in the PDF. This parameters shows where the
sampling should start.
r_end : float,
Radial endpoint of ODF sampling
r_step : float,
Step size of the ODf sampling from r_start to r_end
filter_width : float,
Strength of the hanning filter
References
———-
.. [1] Canales-Rodriguez E.J et al., “Deconvolution in Diffusion
Spectrum Imaging”, Neuroimage, 2010.
.. [2] Biggs David S.C. et al., “Acceleration of Iterative Image
Restoration Algorithms”, Applied Optics, vol. 36, No. 8, p. 1766-1775,
1997.
Applies the 3D FFT in the q-space grid to generate
the DSI diffusion propagator, remove the background noise with a
hard threshold and then deconvolve the propagator with the
Lucy-Richardson deconvolution algorithm
We assume here that only on b0 is provided with the initial data. If that
is not the case then you will need to write your own preparation function
before providing the gradients and the data to the DiffusionSpectrumModel
class.
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.
The diffusion orientation distribution function (dODF). This is an
estimate of the diffusion distance in each direction
Parameters
———-
sphere : Sphere class instance.
The dODF is calculated in the vertices of this input.
Returns
——-
odf : ndarray
The diffusion distance in every direction of the sphere in every
voxel in the input data.
Notes
—–
This is based on equation 3 in [1]_. To re-derive it from
scratch, follow steps in [2]_, Section 7.9 Equation
7.24 but with an \(r^2\) term in the integral.
References
———-
.. [1] Aganj, I., Lenglet, C., Sapiro, G., Yacoub, E., Ugurbil,
K., & Harel, N. (2010). Reconstruction of the orientation
distribution function in single- and multiple-shell q-ball imaging
within constant solid angle. Magnetic Resonance in Medicine, 64(2),
554-566. doi:DOI: 10.1002/mrm.22365
.. [2] Descoteaux, M. (2008). PhD Thesis: High Angular
Resolution Diffusion MRI: from Local Estimation to Segmentation and
Tractography.
ftp://ftp-sop.inria.fr/athena/Publications/PhDs/descoteaux_thesis.pdf
Given a model fit, predict the signal on the vertices of a sphere
Parameters
———-
gtab : a GradientTable class instance
This encodes the directions for which a prediction is made
S0 : float array
The mean non-diffusion weighted signal in each voxel. Default:
The fitted S0 value in all voxels if it was fitted. Otherwise 1 in
all voxels.
step : int
The chunk size as a number of voxels. Optional parameter with
default value 10,000.
In order to increase speed of processing, tensor fitting is done
simultaneously over many voxels. This parameter sets the number of
voxels that will be fit at once in each iteration. 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.
Notes
—–
The predicted signal is given by:
.. math ::
S( heta, b) = S_0 * e^{-b ADC}
Where:
.. math ::
ADC = heta Q heta^T
:math:` heta` is a unit vector pointing at any direction on the sphere for
which a signal is to be predicted and \(b\) is the b value provided in
the GradientTable input for that direction
Geodesic anisotropy (GA) of a diffusion tensor.
Parameters
———-
evals : array-like
Eigenvalues of a diffusion tensor.
axis : int
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 [1]_:
.. math::
GA = sqrt{sum_{i=1}^3
log^2{left ( lambda_i/<mathbf{D}> right )}},
quad textrm{where} quad <mathbf{D}> =
(lambda_1lambda_2lambda_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 [1]_ versus [2]_ versus [3]_ for example). Reference [2]_ defines
geodesic anisotropy (GA) with \(<D>\) as the MD in the denominator of the
sum. This is wrong. The original paper [1]_ 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 [1]_ and
log-Euclidean derivations from [3]_ are clear on this. Hence, all that to
say that \(<D> = det(D)^{1/3}\) here for the GA definition and not MD.
References
———-
.. [1] P. G. Batchelor, M. Moakher, D. Atkinson, F. Calamante,
A. Connelly, “A rigorous framework for diffusion tensor calculus”,
Magnetic Resonance in Medicine, vol. 53, pp. 221-225, 2005.
.. [2] M. M. Correia, V. F. Newcombe, G.B. Williams.
“Contrast-to-noise ratios for indices of anisotropy obtained from
diffusion MRI: a study with standard clinical b-values at 3T”.
NeuroImage, vol. 57, pp. 1103-1115, 2011.
.. [3] A. D. Lee, etal, P. M. Thompson.
“Comparison of fractional and geodesic anisotropy in diffusion tensor
images of 90 monozygotic and dizygotic twins”. 5th IEEE International
Symposium on Biomedical Imaging (ISBI), pp. 943-946, May 2008.
.. [4] V. Arsigny, P. Fillard, X. Pennec, N. Ayache.
“Log-Euclidean metrics for fast and simple calculus on diffusion
tensors.” Magnetic Resonance in Medecine, vol 56, pp. 411-421, 2006.
Calculate the deviatoric (anisotropic) part of the tensor [1]_.
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 [1]_):
.. math ::
widetilde{A} = A - bar{A}
Where \(A\) is the tensor quadratic form and \(\bar{A}\) is the anisotropic
part of the tensor.
References
———-
.. [1] Daniel B. Ennis and G. Kindlmann, “Orthogonal Tensor
Invariants and the Analysis of Diffusion Tensor Magnetic Resonance
Images”, Magnetic Resonance in Medicine, vol. 55, no. 1, pp. 136-146,
2006.
Mode (MO) of a diffusion tensor [1]_.
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 orthotropy. Mode is calculated with the
following equation (equation 9 in [1]_):
.. math::
Mode = 3*sqrt{6}*det(widetilde{A}/norm(widetilde{A}))
Where \(\widetilde{A}\) is the deviatoric part of the tensor quadratic form.
References
———-
.. [1] Daniel B. Ennis and G. Kindlmann, “Orthogonal Tensor
Invariants and the Analysis of Diffusion Tensor Magnetic Resonance
Images”, Magnetic Resonance in Medicine, vol. 55, no. 1, pp. 136-146,
2006.
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: \(S( heta, b) = S_0 * e^{-b ADC}\), where
\(ADC = heta Q heta^T\), :math:` heta` 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.
Wrap a fit_tensor func and iterate over chunks of data with given length
Splits data into a number of chunks of specified size and iterates the
decorated fit_tensor function over them. This is useful to counteract the
temporary but significant memory usage increase in fit_tensor functions
that use vectorized operations and need to store large temporary arrays for
their vectorized operations.
The chunk size as a number of voxels. Optional parameter with default
value 10,000.
In order to increase speed of processing, tensor fitting is done
simultaneously over many voxels. This parameter sets the number of
voxels that will be fit at once in each iteration. 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.
In Chung, et al. 2006, the regression of the WLS fit needed an unbiased
preliminary estimate of the weights and therefore the ordinary least
squares (OLS) estimates were used. A “two pass” method was implemented:
calculate OLS estimates of the data
apply the OLS estimates as weights to the WLS fit of the data
This ensured heteroscedasticity could be properly modeled for various
types of bootstrap resampling (namely residual bootstrap).
\[\begin{split}y = \mathrm{data} \\
X = \mathrm{design matrix} \\
\hat{\beta}_\mathrm{WLS} =
\mathrm{desired regression coefficients (e.g. tensor)}\\
\\
\hat{\beta}_\mathrm{WLS} = (X^T W X)^{-1} X^T W y \\
\\
W = \mathrm{diag}((X \hat{\beta}_\mathrm{OLS})^2),
\mathrm{where} \hat{\beta}_\mathrm{OLS} = (X^T X)^{-1} X^T y\end{split}\]
Design matrix holding the covariants used to solve for the regression
coefficients. First six parameters of design matrix should correspond
to the six unique diffusion tensor elements in the lower triangular
order (Dxx, Dxy, Dyy, Dxz, Dyz, Dzz), while last parameter to -log(S0)
dataarray ([X, Y, Z, …], g)
Data or response variables holding the data. Note that the last
dimension should contain the data. It makes no copies of data.
weighting: str
the weighting scheme to use in considering the
squared-error. Default behavior is to use uniform weighting. Other
options: ‘sigma’ ‘gmm’
sigmaarray (optional)
If ‘sigma’ weighting is used, we will weight the error function
according to 1/sigma^2. If ‘gmm’, the Geman-Mclure
M-estimator is used for weighting (see below).
jacbool
Use the Jacobian? Default: True
return_S0_hatbool
Boolean to return (True) or not (False) the S0 values for the fit.
fail_is_nanbool
Boolean to set failed NL fitting to NaN (True) or LS (False, default).
Design matrix holding the covariants used to solve for the regression
coefficients.
dataarray of shape ([X, Y, Z, n_directions], g)
Data or response variables holding the data. Note that the last
dimension should contain the data. It makes no copies of data.
sigmafloat, array of shape [n_directions], array of shape [X, Y, Z]
An estimate of the variance. [1]_ recommend to use
1.5267 * std(background_noise), where background_noise is estimated
from some part of the image known to contain no signal (only noise).
Array with ndim > 1 corresponds to spatially varying sigma, so if
providing spatially-flattened data and spatially-varying sigma,
provide array with shape [num_vox, 1].
jacbool, optional
Whether to use the Jacobian of the tensor to speed the non-linear
optimization procedure used to fit the tensor parameters (see also
nlls_fit_tensor()). Default: True
return_S0_hatbool
Boolean to return (True) or not (False) the S0 values for the fit.
fail_is_nanbool
Boolean to set failed NL fitting to NaN (True) or LS (False, default).
An array object represents a multidimensional, homogeneous array
of fixed-size items. An associated data-type object describes the
format of each element in the array (its byte-order, how many bytes it
occupies in memory, whether it is an integer, a floating point number,
or something else, etc.)
Arrays should be constructed using array, zeros or empty (refer
to the See Also section below). The parameters given here refer to
a low-level method (ndarray(…)) for instantiating an array.
For more information, refer to the numpy module and examine the
methods and attributes of an array.
Describes the format of the elements in the array.
flagsdict
Dictionary containing information related to memory use, e.g.,
‘C_CONTIGUOUS’, ‘OWNDATA’, ‘WRITEABLE’, etc.
flatnumpy.flatiter object
Flattened version of the array as an iterator. The iterator
allows assignments, e.g., x.flat=3 (See ndarray.flat for
assignment examples; TODO).
imagndarray
Imaginary part of the array.
realndarray
Real part of the array.
sizeint
Number of elements in the array.
itemsizeint
The memory use of each array element in bytes.
nbytesint
The total number of bytes required to store the array data,
i.e., itemsize*size.
ndimint
The array’s number of dimensions.
shapetuple of ints
Shape of the array.
stridestuple of ints
The step-size required to move from one element to the next in
memory. For example, a contiguous (3,4) array of type
int16 in C-order has strides (8,2). This implies that
to move from element to element in memory requires jumps of 2 bytes.
To move from row-to-row, one needs to jump 8 bytes at a time
(2*4).
ctypesctypes object
Class containing properties of the array needed for interaction
with ctypes.
basendarray
If the array is a view into another array, that array is its base
(unless that array is also a view). The base array is where the
array data is actually stored.
array : Construct an array.
zeros : Create an array, each element of which is zero.
empty : Create an array, but leave its allocated memory unchanged (i.e.,
it contains “garbage”).
dtype : Create a data-type.
numpy.typing.NDArray : An ndarray alias generic
An array object represents a multidimensional, homogeneous array
of fixed-size items. An associated data-type object describes the
format of each element in the array (its byte-order, how many bytes it
occupies in memory, whether it is an integer, a floating point number,
or something else, etc.)
Arrays should be constructed using array, zeros or empty (refer
to the See Also section below). The parameters given here refer to
a low-level method (ndarray(…)) for instantiating an array.
For more information, refer to the numpy module and examine the
methods and attributes of an array.
Describes the format of the elements in the array.
flagsdict
Dictionary containing information related to memory use, e.g.,
‘C_CONTIGUOUS’, ‘OWNDATA’, ‘WRITEABLE’, etc.
flatnumpy.flatiter object
Flattened version of the array as an iterator. The iterator
allows assignments, e.g., x.flat=3 (See ndarray.flat for
assignment examples; TODO).
imagndarray
Imaginary part of the array.
realndarray
Real part of the array.
sizeint
Number of elements in the array.
itemsizeint
The memory use of each array element in bytes.
nbytesint
The total number of bytes required to store the array data,
i.e., itemsize*size.
ndimint
The array’s number of dimensions.
shapetuple of ints
Shape of the array.
stridestuple of ints
The step-size required to move from one element to the next in
memory. For example, a contiguous (3,4) array of type
int16 in C-order has strides (8,2). This implies that
to move from element to element in memory requires jumps of 2 bytes.
To move from row-to-row, one needs to jump 8 bytes at a time
(2*4).
ctypesctypes object
Class containing properties of the array needed for interaction
with ctypes.
basendarray
If the array is a view into another array, that array is its base
(unless that array is also a view). The base array is where the
array data is actually stored.
array : Construct an array.
zeros : Create an array, each element of which is zero.
empty : Create an array, but leave its allocated memory unchanged (i.e.,
it contains “garbage”).
dtype : Create a data-type.
numpy.typing.NDArray : An ndarray alias generic
An array object represents a multidimensional, homogeneous array
of fixed-size items. An associated data-type object describes the
format of each element in the array (its byte-order, how many bytes it
occupies in memory, whether it is an integer, a floating point number,
or something else, etc.)
Arrays should be constructed using array, zeros or empty (refer
to the See Also section below). The parameters given here refer to
a low-level method (ndarray(…)) for instantiating an array.
For more information, refer to the numpy module and examine the
methods and attributes of an array.
Describes the format of the elements in the array.
flagsdict
Dictionary containing information related to memory use, e.g.,
‘C_CONTIGUOUS’, ‘OWNDATA’, ‘WRITEABLE’, etc.
flatnumpy.flatiter object
Flattened version of the array as an iterator. The iterator
allows assignments, e.g., x.flat=3 (See ndarray.flat for
assignment examples; TODO).
imagndarray
Imaginary part of the array.
realndarray
Real part of the array.
sizeint
Number of elements in the array.
itemsizeint
The memory use of each array element in bytes.
nbytesint
The total number of bytes required to store the array data,
i.e., itemsize*size.
ndimint
The array’s number of dimensions.
shapetuple of ints
Shape of the array.
stridestuple of ints
The step-size required to move from one element to the next in
memory. For example, a contiguous (3,4) array of type
int16 in C-order has strides (8,2). This implies that
to move from element to element in memory requires jumps of 2 bytes.
To move from row-to-row, one needs to jump 8 bytes at a time
(2*4).
ctypesctypes object
Class containing properties of the array needed for interaction
with ctypes.
basendarray
If the array is a view into another array, that array is its base
(unless that array is also a view). The base array is where the
array data is actually stored.
array : Construct an array.
zeros : Create an array, each element of which is zero.
empty : Create an array, but leave its allocated memory unchanged (i.e.,
it contains “garbage”).
dtype : Create a data-type.
numpy.typing.NDArray : An ndarray alias generic
Because negative eigenvalues are not physical and small eigenvalues,
much smaller than the diffusion weighting, cause quite a lot of noise
in metrics such as fa, diffusivity values smaller than
min_diffusivity are replaced with min_diffusivity.
Fiber ORientation Estimated using Continuous Axially Symmetric Tensors
(FORECAST) [1,2,3]_. FORECAST is a Spherical Deconvolution reconstruction
model for multi-shell diffusion data which enables the calculation of a
voxel adaptive response function using the Spherical Mean Technique (SMT)
[2,3]_.
With FORECAST it is possible to calculate crossing invariant parallel
diffusivity, perpendicular diffusivity, mean diffusivity, and fractional
anisotropy [2]_
Analytical and continuous modeling of the diffusion signal with
respect to the FORECAST basis [1,2,3]_.
This implementation is a modification of the original FORECAST
model presented in [1]_ adapted for multi-shell data as in [2,3]_ .
The main idea is to model the diffusion signal as the combination of a
single fiber response function \(F(\mathbf{b})\) times the fODF
\(\rho(\mathbf{v})\)
..math::
:nowrap:
begin{equation}
E(mathbf{b}) = int_{mathbf{v} in mathcal{S}^2} rho(mathbf{v}) F({mathbf{b}} | mathbf{v}) d mathbf{v}
end{equation}
where \(\mathbf{b}\) is the b-vector (b-value times gradient direction)
and \(\mathbf{v}\) is an unit vector representing a fiber direction.
In FORECAST \(\rho\) is modeled using real symmetric Spherical Harmonics
(SH) and \(F(\mathbf(b))\) is an axially symmetric tensor.
Parameters
———-
gtab : GradientTable,
gradient directions and bvalues container class.
sh_order_max : unsigned int,
an even integer that represent the maximal SH order (l) of the
basis (max 12)
lambda_lb: float,
Laplace-Beltrami regularization weight.
dec_alg : str,
Spherical deconvolution algorithm. The possible values are Weighted Least Squares (‘WLS’),
Positivity Constraints using CVXPY (‘POS’) and the Constraint
Spherical Deconvolution algorithm (‘CSD’). Default is ‘CSD’.
sphere : array, shape (N,3),
sphere points where to enforce positivity when ‘POS’ or ‘CSD’
dec_alg are selected.
lambda_csd : float,
CSD regularization weight.
References
———-
.. [1] Anderson A. W., “Measurement of Fiber Orientation Distributions
Using High Angular Resolution Diffusion Imaging”, Magnetic
Resonance in Medicine, 2005.
.. [2] Kaden E. et al., “Quantitative Mapping of the Per-Axon Diffusion
Coefficients in Brain White Matter”, Magnetic Resonance in
Medicine, 2016.
.. [3] Zucchelli M. et al., “A generalized SMT-based framework for
Diffusion MRI microstructural model estimation”, MICCAI Workshop
on Computational DIFFUSION MRI (CDMRI), 2017.
Examples
——–
In this example, where the data, gradient table and sphere tessellation
used for reconstruction are provided, we model the diffusion signal
with respect to the FORECAST and compute the fODF, parallel and
perpendicular diffusivity.
>>> import warnings
>>> from dipy.data import default_sphere, get_3shell_gtab
>>> gtab = get_3shell_gtab()
>>> from dipy.sims.voxel import multi_tensor
>>> mevals = np.array(([0.0017, 0.0003, 0.0003],
… [0.0017, 0.0003, 0.0003]))
>>> angl = [(0, 0), (60, 0)]
>>> data, sticks = multi_tensor(gtab,
… mevals,
… S0=100.0,
… angles=angl,
… fractions=[50, 50],
… snr=None)
>>> from dipy.reconst.forecast import ForecastModel
>>> from dipy.reconst.shm import descoteaux07_legacy_msg
>>> with warnings.catch_warnings():
… warnings.filterwarnings(
… “ignore”, message=descoteaux07_legacy_msg,
… category=PendingDeprecationWarning)
… fm = ForecastModel(gtab, sh_order_max=6)
>>> f_fit = fm.fit(data)
>>> d_par = f_fit.dpar
>>> d_perp = f_fit.dperp
>>> with warnings.catch_warnings():
… warnings.filterwarnings(
… “ignore”, message=descoteaux07_legacy_msg,
… category=PendingDeprecationWarning)
… fodf = f_fit.odf(default_sphere)
The last dimension should have 13 parameters: the 12 tensor
parameters (3 eigenvalues, followed by the 3 corresponding
eigenvectors) and the free water volume fraction.
S0float or ndarray
The non diffusion-weighted signal in every voxel, or across all
voxels. Default: 1
Initialize a FreeWaterTensorFit class instance.
Since the free water tensor model is an extension of DTI, class
instance is defined as subclass of the TensorFit from dti.py
Signal prediction given the free water DTI model parameters.
Parameters
———-
params : (…, 13) ndarray
Model parameters. The last dimension should have the 12 tensor
parameters (3 eigenvalues, followed by the 3 corresponding
eigenvectors) and the volume fraction of the free water compartment.
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
Diso : float, optional
Value of the free water isotropic diffusion. Default is set to 3e-3
\(mm^{2}.s^{-1}\). Please adjust this value if you are assuming different
units of diffusion.
Returns
——-
S : (…, N) ndarray
Simulated signal based on the free water DTI model
Notes
—–
The predicted signal is given by:
\(S(\theta, b) = S_0 * [(1-f) * e^{-b ADC} + f * e^{-b D_{iso}]\), 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, \(f\) is the
free water diffusion compartment, \(D_{iso}\) is the free water diffusivity
which is equal to $3 * 10^{-3} mm^{2}s^{-1} [1]_.
References
———-
.. [1] Henriques, R.N., Rokem, A., Garyfallidis, E., St-Jean, S.,
Peterson E.T., Correia, M.M., 2017. [Re] Optimization of a free
water elimination two-compartment model for diffusion tensor
imaging. ReScience volume 3, issue 1, article number 2
Applies weighted linear least squares fit of the water free elimination
model to single voxel signals.
Parameters
———-
design_matrix : array (g, 7)
Design matrix holding the covariants used to solve for the regression
coefficients.
sig : array (g, )
Diffusion-weighted signal for a single voxel data.
S0 : float
Non diffusion weighted signal (i.e. signal for b-value=0).
Diso : float, optional
Value of the free water isotropic diffusion. Default is set to 3e-3
\(mm^{2}.s^{-1}\). Please adjust this value if you are assuming different
units of diffusion.
mdreg : float, optimal
DTI’s mean diffusivity regularization threshold. If standard DTI
diffusion tensor’s mean diffusivity is almost near the free water
diffusion value, the diffusion signal is assumed to be only free water
diffusion (i.e. volume fraction will be set to 1 and tissue’s diffusion
parameters are set to zero). Default md_reg is 2.7e-3 \(mm^{2}.s^{-1}\)
(corresponding to 90% of the free water diffusion value).
min_signal : float
The minimum signal value. Needs to be a strictly positive
number. Default: minimal signal in the data provided to fit.
piterations : inter, optional
Number of iterations used to refine the precision of f. Default is set
to 3 corresponding to a precision of 0.01.
Returns
——-
All parameters estimated from the free water tensor model.
Parameters are ordered as follows:
1) Three diffusion tensor’s eigenvalues
2) Three lines of the eigenvector matrix each containing the
first, second and third coordinates of the eigenvector
3) The volume fraction of the free water compartment
Computes weighted least squares (WLS) fit to calculate self-diffusion
tensor using a linear regression model [1]_.
Parameters
———-
gtab : a GradientTable class instance
The gradient table containing diffusion acquisition parameters.
data : ndarray ([X, Y, Z, …], g)
Data or response variables holding the data. Note that the last
dimension should contain the data. It makes no copies of data.
Diso : float, optional
Value of the free water isotropic diffusion. Default is set to 3e-3
\(mm^{2}.s^{-1}\). Please adjust this value if you are assuming different
units of diffusion.
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]
min_signal : float
The minimum signal value. Needs to be a strictly positive
number. Default: 1.0e-6.
piterations : inter, optional
Number of iterations used to refine the precision of f. Default is set
to 3 corresponding to a precision of 0.01.
mdreg : float, optimal
DTI’s mean diffusivity regularization threshold. If standard DTI
diffusion tensor’s mean diffusivity is almost near the free water
diffusion value, the diffusion signal is assumed to be only free water
diffusion (i.e. volume fraction will be set to 1 and tissue’s diffusion
parameters are set to zero). Default md_reg is 2.7e-3 \(mm^{2}.s^{-1}\)
(corresponding to 90% of the free water diffusion value).
Returns
——-
fw_params : ndarray (x, y, z, 13)
Matrix containing in the last dimension the free water model parameters
in the following order:
1) Three diffusion tensor’s eigenvalues
2) Three lines of the eigenvector matrix each containing the
first, second and third coordinates of the eigenvector
3) The volume fraction of the free water compartment.
References
———-
.. [1] Henriques, R.N., Rokem, A., Garyfallidis, E., St-Jean, S.,
Peterson E.T., Correia, M.M., 2017. [Re] Optimization of a free
water elimination two-compartment model for diffusion tensor
imaging. ReScience volume 3, issue 1, article number 2
Applies non linear least squares fit of the water free elimination
model to single voxel signals.
Parameters
———-
design_matrix : array (g, 7)
Design matrix holding the covariants used to solve for the regression
coefficients.
sig : array (g, )
Diffusion-weighted signal for a single voxel data.
S0 : float
Non diffusion weighted signal (i.e. signal for b-value=0).
Diso : float, optional
Value of the free water isotropic diffusion. Default is set to 3e-3
\(mm^{2}.s^{-1}\). Please adjust this value if you are assuming different
units of diffusion.
mdreg : float, optimal
DTI’s mean diffusivity regularization threshold. If standard DTI
diffusion tensor’s mean diffusivity is almost near the free water
diffusion value, the diffusion signal is assumed to be only free water
diffusion (i.e. volume fraction will be set to 1 and tissue’s diffusion
parameters are set to zero). Default md_reg is 2.7e-3 \(mm^{2}.s^{-1}\)
(corresponding to 90% of the free water diffusion value).
min_signal : float
The minimum signal value. Needs to be a strictly positive
number.
cholesky : bool, optional
If true it uses Cholesky decomposition to insure that diffusion tensor
is positive define.
Default: False
f_transform : bool, optional
If true, the water volume fractions is converted during the convergence
procedure to ft = arcsin(2*f - 1) + pi/2, insuring f estimates between
0 and 1.
Default: True
jac : bool
Use the Jacobian? Default: False
weighting: str, optional
the weighting scheme to use in considering the
squared-error. Default behavior is to use uniform weighting. Other
options: ‘sigma’ ‘gmm’
sigma: float, optional
If the ‘sigma’ weighting scheme is used, a value of sigma needs to be
provided here. According to [Chang2005], a good value to use is
1.5267 * std(background_noise), where background_noise is estimated
from some part of the image known to contain no signal (only noise).
Returns
——-
All parameters estimated from the free water tensor model.
Parameters are ordered as follows:
1) Three diffusion tensor’s eigenvalues
2) Three lines of the eigenvector matrix each containing the
first, second and third coordinates of the eigenvector
3) The volume fraction of the free water compartment.
Fit the water elimination tensor model using the non-linear least-squares.
Parameters
———-
gtab : a GradientTable class instance
The gradient table containing diffusion acquisition parameters.
data : ndarray ([X, Y, Z, …], g)
Data or response variables holding the data. Note that the last
dimension should contain the data. It makes no copies of data.
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]
Diso : float, optional
Value of the free water isotropic diffusion. Default is set to 3e-3
\(mm^{2}.s^{-1}\). Please adjust this value if you are assuming different
units of diffusion.
mdreg : float, optimal
DTI’s mean diffusivity regularization threshold. If standard DTI
diffusion tensor’s mean diffusivity is almost near the free water
diffusion value, the diffusion signal is assumed to be only free water
diffusion (i.e. volume fraction will be set to 1 and tissue’s diffusion
parameters are set to zero). Default md_reg is 2.7e-3 \(mm^{2}.s^{-1}\)
(corresponding to 90% of the free water diffusion value).
min_signal : float
The minimum signal value. Needs to be a strictly positive
number. Default: 1.0e-6.
f_transform : bool, optional
If true, the water volume fractions is converted during the convergence
procedure to ft = arcsin(2*f - 1) + pi/2, insuring f estimates between
0 and 1.
Default: True
cholesky : bool, optional
If true it uses Cholesky decomposition to insure that diffusion tensor
is positive define.
Default: False
jac : bool
Use the Jacobian? Default: False
weighting: str, optional
the weighting scheme to use in considering the
squared-error. Default behavior is to use uniform weighting. Other
options: ‘sigma’ ‘gmm’
sigma: float, optional
If the ‘sigma’ weighting scheme is used, a value of sigma needs to be
provided here. According to [Chang2005], a good value to use is
1.5267 * std(background_noise), where background_noise is estimated
from some part of the image known to contain no signal (only noise).
Returns
——-
fw_params : ndarray (x, y, z, 13)
Matrix containing in the dimension the free water model parameters in
the following order:
1) Three diffusion tensor’s eigenvalues
2) Three lines of the eigenvector matrix each containing the
first, second and third coordinates of the eigenvector
3) The volume fraction of the free water compartment
This model has the same assumptions as the DSI method i.e. Cartesian
grid sampling in q-space and fast gradient switching.
Implements equations 2.14 from [2]_ for standard GQI and equation 2.16
from [2]_ for GQI2. You can think of GQI2 as an analytical solution of
the DSI ODF.
As of version 0.9, range of the sampling length in GQI2 has changed
to match the same scale used in the ‘standard’ method [1]_. This
means that the value of sampling_length should be approximately
1 - 1.3 (see [1]_, pg. 1628).
Here we create an example where we provide the data, a gradient table
and a reconstruction sphere and calculate the ODF for the first
voxel in the data.
Normalized quantitative anisotropy has the very useful property
to be very small near gray matter and background areas. Therefore,
it can be used to mask out white matter areas.
The IVIM model assumes that biological tissue includes a volume
fraction ‘f’ of water flowing with a pseudo-diffusion coefficient
D* and a fraction (1-f) of static (diffusion only), intra and
extracellular water, with a diffusion coefficient D. In this model
the echo attenuation of a signal in a single voxel can be written as
The b-value to split the data on for two-stage fit. This will be
used while estimating the value of D. The assumption is that at
higher b values the effects of perfusion is less and hence the
signal can be approximated as a mono-exponential decay.
default : 400.
split_b_S0float, optional
The b-value to split the data on for two-stage fit for estimation
of S0 and initial guess for D_star. The assumption here is that
at low bvalues the effects of perfusion are more.
default : 200.
boundstuple of arrays with 4 elements, optional
Bounds to constrain the fitted model parameters. This is only
supported for Scipy version > 0.17. When using a older Scipy
version, this function will raise an error if bounds are different
from None. This parameter is also used to fill nan values for out
of bounds parameters in the IvimFit class using the method
fill_na. default : ([0., 0., 0., 0.], [np.inf, .3, 1., 1.])
two_stagebool
Argument to specify whether to perform a non-linear fitting of all
parameters after the linear fitting by splitting the data based on
bvalues. This gives more accurate parameters but takes more time.
The linear fit can be used to get a quick estimation of the
parameters. default : False
tolfloat, optional
Tolerance for convergence of minimization.
default : 1e-15
x_scalearray-like, optional
Scaling for the parameters. This is passed to least_squares which
is only available for Scipy version > 0.17.
default: [1000, 0.01, 0.001, 0.0001]
gtolfloat, optional
Tolerance for termination by the norm of the gradient.
default : 1e-15
ftolfloat, optional
Tolerance for termination by the change of the cost function.
default : 1e-15
epsfloat, optional
Step size used for numerical approximation of the jacobian.
default : 1e-15
maxiterint, optional
Maximum number of iterations to perform.
default : 1000
The ivim parameters as an array [S0, f, D_star and D]
gtabGradientTable class instance
Gradient directions and bvalues.
S0float, optional
This has been added just for consistency with the existing
API. Unlike other models, IVIM predicts S0 and this is over written
by the S0 value in params.
The IVIM model assumes that biological tissue includes a volume
fraction ‘f’ of water flowing with a pseudo-diffusion coefficient
D* and a fraction (1-f: treated as a separate fraction in the variable
projection method) of static (diffusion only), intra and
extracellular water, with a diffusion coefficient D. In this model
the echo attenuation of a signal in a single voxel can be written as
\[\]
S(b) = S_0*[f*e^{(-b*D*)} + (1-f)e^{(-b*D)}]
Where:
.. math:
S_0, f, D* and D are the IVIM parameters.
maxiter: int, optional
Maximum number of iterations for the Differential Evolution in
SciPy.
default : 10
xtolfloat, optional
Tolerance for convergence of minimization.
default : 1e-8
Performs the constrained search for the linear parameters f after
the estimation of x is done. Estimation of the linear parameters f
is a constrained linear least-squares optimization problem solved by
using a convex optimizer from cvxpy. The IVIM equation contains two
parameters that depend on the same volume fraction. Both are estimated
as separately in the convex optimizer.
Constructs the objective for the :func: stoc_search_cost.
First calculates the Moore-Penrose inverse of the input phi and takes
a dot product with the measured signal. The result obtained is again
multiplied with phi to complete the projection of the variable into
a transformed space. (see [1]_ and [2]_ for thorough discussion on
Variable Projections and relevant cost functions).
Cost function for the least square problem. The cost function is used
in the Least Squares function of SciPy in :func: fit. It guarantees
that stopping point of the algorithm is at least a stationary point
with reduction in the the number of iterations required by the
differential evolution optimizer.
Creates a structure for the combining the diffusion and pseudo-
diffusion by multiplying with the bvals and then exponentiating each of
the two components for fitting as per the IVIM- two compartment model.
Cost function for differential evolution algorithm. Performs a
stochastic search for the non-linear parameters ‘x’. The objective
function is calculated in the :func: ivim_mix_cost_one. The function
constructs the parameters using :func: phi.
The parameters of the model. In this case it is an
array of ivim parameters. If the fitting is done
for multi_voxel data, the multi_voxel decorator will
run the fitting on all the voxels and model_params
will be an array of the dimensions (data[:-1], 4),
i.e., there will be 4 parameters for each of the voxels.
S0 value here is not necessary and will not be used to predict the
signal. It has been added to conform to the structure of the
predict method in multi_voxel which requires a keyword argument S0.
This has been added just for consistency with the existing
API. Unlike other models, IVIM predicts S0 and this is over written
by the S0 value in params.
Selector function to switch between the 2-stage Trust-Region Reflective
based NLLS fitting method (also containing the linear fit): trr and the
Variable Projections based fitting method: varpro.
Mean Apparent Propagator MRI (MAPMRI) [1]_ of the diffusion signal.
The main idea is to model the diffusion signal as a linear combination of
the continuous functions presented in [2]_ but extending it in three
dimensions.
The main difference with the SHORE proposed in [3]_ is that MAPMRI 3D
extension is provided using a set of three basis functions for the radial
part, one for the signal along x, one for y and one for z, while [3]_
uses one basis function to model the radial part and real Spherical
Harmonics to model the angular part.
From the MAPMRI coefficients is possible to use the analytical formulae
to estimate the ODF.
Analytical and continuous modeling of the diffusion signal with
respect to the MAPMRI basis [1]_.
The main idea is to model the diffusion signal as a linear combination
of the continuous functions presented in [2]_ but extending it in three
dimensions.
The main difference with the SHORE proposed in [3]_ is that MAPMRI 3D
extension is provided using a set of three basis functions for the
radial part, one for the signal along x, one for y and one for z, while
[3]_ uses one basis function to model the radial part and real
Spherical Harmonics to model the angular part.
From the MAPMRI coefficients it is possible to estimate various
q-space indices, the PDF and the ODF.
The fitting procedure can be constrained using the positivity
constraint proposed in [1]_ or [4]_ and/or the laplacian regularization
proposed in [5]_.
For the estimation of q-space indices we recommend using the ‘regular’
anisotropic implementation of MAPMRI. However, it has been shown that
the ODF estimation in this implementation has a bias which
‘squeezes together’ the ODF peaks when there is a crossing at an angle
smaller than 90 degrees [5]_. When you want to estimate ODFs for
tractography we therefore recommend using the isotropic implementation
(which is equivalent to [3]_).
The switch between isotropic and anisotropic can be easily made through
the anisotropic_scaling option.
gradient directions and bvalues container class.
the gradient table has to include b0-images.
radial_orderunsigned int,
an even integer that represent the order of the basis
laplacian_regularization: bool,
Regularize using the Laplacian of the MAP-MRI basis.
laplacian_weighting: string or scalar,
The string ‘GCV’ makes it use generalized cross-validation to find
the regularization weight [4]. A scalar sets the regularization
weight to that value and an array will make it selected the
optimal weight from the values in the array.
positivity_constraintbool,
Constrain the propagator to be positive.
global_constraintsbool, optional
If set to False, positivity is enforced on a grid determined by
pos_grid and pos_radius. If set to True, positivity is enforced
everywhere using the constraints of [6]_. Global constraints are
currently supported for anisotropic_scaling=True and for
radial_order <= 10. Default: False.
pos_gridinteger,
The number of points in the grid that is used in the local
positivity constraint.
pos_radiusfloat or string,
If set to a float, the maximum distance the local positivity
constraint constrains to posivity is that value. If set to
‘adaptive’, the maximum distance is dependent on the estimated
tissue diffusivity.
anisotropic_scalingbool,
If True, uses the standard anisotropic MAP-MRI basis. If False,
uses the isotropic MAP-MRI basis (equal to 3D-SHORE).
eigenvalue_thresholdfloat,
Sets the minimum of the tensor eigenvalues in order to avoid
stability problem.
bval_thresholdfloat,
Sets the b-value threshold to be used in the scale factor
estimation. In order for the estimated non-Gaussianity to have
meaning this value should set to a lower value (b<2000 s/mm^2)
such that the scale factors are estimated on signal points that
reasonably represent the spins at Gaussian diffusion.
dti_scale_estimationbool,
Whether or not DTI fitting is used to estimate the isotropic scale
factor for isotropic MAP-MRI.
When set to False the algorithm presets the isotropic tissue
diffusivity to static_diffusivity. This vastly increases fitting
speed but at the cost of slightly reduced fitting quality. Can
still be used in combination with regularization and constraints.
static_diffusivityfloat,
the tissue diffusivity that is used when dti_scale_estimation is
set to False. The default is that of typical white matter
D=0.7e-3 _[5].
cvxpy_solverstr, optional
cvxpy solver name. Optionally optimize the positivity constraint
with a particular cvxpy solver. See https://www.cvxpy.org/ for
details.
Default: None (cvxpy chooses its own solver)
In this example, where the data, gradient table and sphere tessellation
used for reconstruction are provided, we model the diffusion signal
with respect to the SHORE basis and compute the real and analytical
ODF.
regularization weight used for laplacian regularization
errorcodeint
provides information on whether errors occurred in the fitting
of each voxel. 0 means no problem, 1 means a LinAlgError
occurred when trying to invert the design matrix. 2 means the
positivity constraint was unable to solve the problem. 3 means
that after positivity constraint failed, also matrix inversion
failed.
Calculates the analytical Mean Squared Displacement (MSD).
It is defined as the Laplacian of the origin of the estimated signal
[1]_. The analytical formula for the MAP-MRI basis was derived in [2]_
eq. (C13, D1).
Calculates the analytical non-Gaussiannity (NG) [1]_.
For the NG to be meaningful the mapmri scale factors must be
estimated only on data representing Gaussian diffusion of spins, i.e.,
bvals smaller than about 2000 s/mm^2 [2]_.
Calculates the analytical parallel non-Gaussiannity (NG) [1]_.
For the NG to be meaningful the mapmri scale factors must be
estimated only on data representing Gaussian diffusion of spins, i.e.,
bvals smaller than about 2000 s/mm^2 [2]_.
Calculates the analytical perpendicular non-Gaussiannity (NG)
[1]_. For the NG to be meaningful the mapmri scale factors must be
estimated only on data representing Gaussian diffusion of spins, i.e.,
bvals smaller than about 2000 s/mm^2 [2]_.
Calculates the norm of the laplacian of the fitted signal [1]_.
This information could be useful to assess if the extrapolation of the
fitted signal contains spurious oscillations. A high laplacian may
indicate that these are present, and any q-space indices that
use integrals of the signal may be corrupted (e.g. RTOP, RTAP, RTPP,
QIV).
Calculates the real analytical odf for a given discrete sphere.
Computes the design matrix of the ODF for the given sphere vertices
and radial moment [1]_ eq. (32). The radial moment s acts as a
sharpening method. The analytical equation for the spherical ODF basis
is given in [2]_ eq. (C8).
Diffusion propagator on a given set of real points.
if the array r_points is non writeable, then intermediate
results are cached for faster recalculation
Calculates the analytical Q-space Inverse Variance (QIV).
It is defined as the inverse of the Laplacian of the origin of the
estimated propagator [1]_ eq. (22). The analytical formula for the
MAP-MRI basis was derived in [2]_ eq. (C14, D2).
(bfor): An analytical diffusion propagator reconstruction for hybrid
diffusion imaging and computation of q-space indices. NeuroImage 64,
2013, 650-670.
using Laplacian-regularized MAP-MRI and its application to HCP data.”
NeuroImage (2016).
Calculates the analytical return to the axis probability (RTAP)
[1]_ eq. (40, 44a). The analytical formula for the isotropic MAP-MRI
basis was derived in [2]_ eq. (C11).
Calculates the analytical return to the origin probability (RTOP)
[1]_ eq. (36, 43). The analytical formula for the isotropic MAP-MRI
basis was derived in [2]_ eq. (C11).
Calculates the analytical return to the plane probability (RTPP)
[1]_ eq. (42). The analytical formula for the isotropic MAP-MRI
basis was derived in [2]_ eq. (C11).
Compute the isotropic MAPMRI ODF matrix [1]_ Eq. 32 for the isotropic
propagator in [1]_ eq. (60). Here we do not compute the sphere function but
the spherical harmonics by only integrating the radial part of the
propagator. We use the same derivation of the ODF in the isotropic
implementation as in [2]_ eq. (C8).
dipy.reconst.mapmri.generalized_crossvalidation_array(data, M, LR, weights_array=None)#
Generalized Cross Validation Function [1]_ eq. (15).
Here weights_array is a numpy array with all values that should be
considered in the GCV. It will run through the weights until the cost
function starts to increase, then stop and take the last value as the
optimum weight.
Estimate Multi Shell response function for multiple tissues and
multiple shells.
The method multi_shell_fiber_response allows to create a multi-shell
fiber response with the right format, for a three compartments model.
It can be referred to in order to understand the inputs of this class.
Multi-shell fiber response. The ordering of the responses should
follow the same logic as S0.
sh_order_maxint
Maximal spherical harmonics order (l).
shellsint
Number of shells in the data
S0array (3,)
Signal with no diffusion weighting for each tissue compartments, in
the same tissue order as response. This S0 can be used for
predicting from a fit model later on.
Multi-Shell Multi-Tissue Constrained Spherical Deconvolution
(MSMT-CSD) [1]_. This method extends the CSD model proposed in [2]_ by
the estimation of multiple response functions as a function of multiple
b-values and multiple tissue types.
Spherical deconvolution computes a fiber orientation distribution
(FOD), also called fiber ODF (fODF) [2]_. The fODF is derived from
different tissue types and thus overcomes the overestimation of WM in
GM and CSF areas.
The response function is based on the different tissue types
and is provided as input to the MultiShellDeconvModel.
It will be used as deconvolution kernel, as described in [2]_.
gtab : GradientTable
response : ndarray or MultiShellResponse object
Pre-computed multi-shell fiber response function in the form of a
MultiShellResponse object, or simple response function as a ndarray.
The later must be of shape (3, len(bvals)-1, 4), because it will be
converted into a MultiShellResponse object via the
multi_shell_fiber_response method (important note: the function
unique_bvals_tolerance is used here to select unique bvalues from
gtab as input). Each column (3,) has two elements. The first is the
eigen-values as a (3,) ndarray and the second is the signal value
for the response function without diffusion weighting (S0). Note
that in order to use more than three compartments, one must create
a MultiShellResponse object on the side.
reg_sphereSphere (optional)
sphere used to build the regularization B matrix.
Default: ‘symmetric362’.
sh_order_maxint (optional)
Maximal spherical harmonics order (l). Default: 8
iso: int (optional)
Number of tissue compartments for running the MSMT-CSD. Minimum
number of compartments required is 2.
Default: 2
Abstract class which holds the fit result of MultiShellDeconvModel.
Inherits the SphHarmFit which fits the diffusion data to a spherical
harmonic model.
Makes use of the quadratic programming solver solve_qp to fit the
model. The initialization for the model is done using the warm-start by
default in CVXPY.
Helper function to set up and solve the Quadratic Program (QP) in CVXPY.
A QP problem has the following form:
minimize 1/2 x’ P x + Q’ x
subject to G x <= H
Here the QP solver is based on CVXPY and uses OSQP.
Array containing the b-values. Must be unique b-values, like outputted
by dipy.core.gradients.unique_bvals_tolerance.
wm_rf(N-1, 4) ndarray
Response function of the WM tissue, for each bvals,
where N is the number of unique b-values including the b0.
gm_rf(N-1, 4) ndarray
Response function of the GM tissue, for each bvals.
csf_rf(N-1, 4) ndarray
Response function of the CSF tissue, for each bvals.
spheredipy.core.Sphere instance, optional
Sphere where the signal will be evaluated.
tolint, optional
Tolerance gap for b-values clustering.
btens : can be any of two options, optional
an array of strings of shape (N,) specifying
encoding tensor shape associated with all unique b-values
separately. N corresponds to the number of unique b-values,
including the b0. Options for elements in array: ‘LTE’,
‘PTE’, ‘STE’, ‘CTE’ corresponding to linear, planar, spherical, and
“cigar-shaped” tensor encoding.
an array of shape (N,3,3) specifying the b-tensor of each unique
b-values exactly. N corresponds to the number of unique b-values,
including the b0.
In msmt-CSD there is an important pre-processing step: the estimation of
every tissue’s response function. In order to do this, we look for voxels
corresponding to WM, GM and CSF. This function aims to accomplish that by
returning a mask of voxels within a ROI and who respect some threshold
constraints, for each tissue. More precisely, the WM mask must have a FA
value above a given threshold. The GM mask and CSF mask must have a FA
below given thresholds and a MD below other thresholds. To get the FA and
MD, we need to fit a Tensor model to the datasets.
In msmt-CSD there is an important pre-processing step: the estimation of
every tissue’s response function. In order to do this, we look for voxels
corresponding to WM, GM and CSF. This information can be obtained by using
mcsd.mask_for_response_msmt() through masks of selected voxels. The present
function uses such masks to compute the msmt response functions.
For the responses, we base our approach on the function
csdeconv.response_from_mask_ssst(), with the added layers of multishell and
multi-tissue (see the ssst function for more information about the
computation of the ssst response function). This means that for each tissue
we use the previously found masks and loop on them. For each mask, we loop
on the b-values (clustered using the tolerance gap) to get many responses
and then average them to get one response per tissue.
In msmt-CSD there is an important pre-processing step: the estimation of
every tissue’s response function. In order to do this, we look for voxels
corresponding to WM, GM and CSF. We get this information from
mcsd.mask_for_response_msmt(), which returns masks of selected voxels
(more details are available in the description of the function).
With the masks, we compute the response functions by using
mcsd.response_from_mask_msmt(), which returns the response for each
tissue (more details are available in the description of the function).
Mean Signal Diffusion Kurtosis Model [1]_.
Parameters
———-
gtab : GradientTable class instance
bmag : int
The order of magnitude that the bvalues have to differ to be
considered an unique b-value. Default: derive this value from the
maximal b-value provided: \(bmag=log_{10}(max(bvals)) - 1\).
return_S0_hat : bool
If True, also return S0 values for the fit.
args, kwargs : arguments and keyword arguments passed to the
fit_method. See msdki.wls_fit_msdki for details
References
———-
.. [1] Henriques, R.N., 2018. Advanced Methods for Diffusion MRI Data
Analysis and their Application to the Healthy Ageing Brain
(Doctoral thesis). Downing College, University of Cambridge.
https://doi.org/10.17863/CAM.29356
Predict a signal for this MeanDiffusionKurtosisModel class instance
given parameters.
Parameters
———-
msdki_params : ndarray
The parameters of the mean signal diffusion kurtosis model
S0 : float or ndarray
The non diffusion-weighted signal in every voxel, or across all
voxels. Default: 1
Returns
——-
S : (…, N) ndarray
Simulated mean signal based on the mean signal diffusion kurtosis
model
Notes
—–
The predicted signal is given by:
\(MS(b) = S_0 * exp(-bD + 1/6 b^{2} D^{2} K)\), where \(D\) and \(K\) are
the mean signal diffusivity and mean signal kurtosis.
References
———-
.. [1] Henriques, R.N., 2018. Advanced Methods for Diffusion MRI Data
Analysis and their Application to the Healthy Ageing Brain
(Doctoral thesis). Downing College, University of Cambridge.
https://doi.org/10.17863/CAM.29356
Given a mean signal diffusion kurtosis model fit, predict the signal
on the vertices of a sphere
Parameters
———-
gtab : a GradientTable class instance
This encodes the directions for which a prediction is made
S0 : float array
The mean non-diffusion weighted signal in each voxel. Default:
The fitted S0 value in all voxels if it was fitted. Otherwise 1 in
all voxels.
Returns
——-
S : (…, N) ndarray
Simulated mean signal based on the mean signal kurtosis model
Notes
—–
The predicted signal is given by:
\(MS(b) = S_0 * exp(-bD + 1/6 b^{2} D^{2} K)\), where \(D\) and \(k\) are the
mean signal diffusivity and mean signal kurtosis.
References
———-
.. [1] Henriques, R.N., 2018. Advanced Methods for Diffusion MRI Data
Analysis and their Application to the Healthy Ageing Brain
(Doctoral thesis). Downing College, University of Cambridge.
https://doi.org/10.17863/CAM.29356
Computes the intrisic diffusivity from the mean signal diffusional
kurtosis parameters assuming the 2-compartmental spherical mean
technique model [1]_, [2]_
Computes the microscopic fractional anisotropy from the mean signal
diffusional kurtosis parameters assuming the 2-compartmental spherical
mean technique model [1]_, [2]_
Computes the average signal across different diffusion directions
for each unique b-value
Parameters
———-
data : ndarray ([X, Y, Z, …], g)
ndarray containing the data signals in its last dimension.
gtab : a GradientTable class instance
The gradient table containing diffusion acquisition parameters.
bmag : The order of magnitude that the bvalues have to differ to be
considered an unique b-value. Default: derive this value from the
maximal b-value provided: \(bmag=log_{10}(max(bvals)) - 1\).
Returns
——-
msignal : ndarray ([X, Y, Z, …, nub])
Mean signal along all gradient directions for each unique b-value
Note that the last dimension contains the signal means and nub is the
number of unique b-values.
ng : ndarray(nub)
Number of gradient directions used to compute the mean signal for
all unique b-values
Notes
—–
This function assumes that directions are evenly sampled on the sphere or
on the hemisphere
Predict the mean signal given the parameters of the mean signal DKI, an
GradientTable object and S0 signal.
Parameters
———-
msdki_params : ndarray ([X, Y, Z, …], 2)
Array containing the mean signal diffusivity and mean signal kurtosis
in its last axis
gtab : a GradientTable class instance
The gradient table for this prediction
S0 : float or ndarray (optional)
The non diffusion-weighted signal in every voxel, or across all
voxels. Default: 1
Notes
—–
The predicted signal is given by:
\(MS(b) = S_0 * exp(-bD + 1/6 b^{2} D^{2} K)\), where \(D\) and \(K\) are the
mean signal diffusivity and mean signal kurtosis.
References
———-
.. [1] Henriques, R.N., 2018. Advanced Methods for Diffusion MRI Data
Analysis and their Application to the Healthy Ageing Brain (Doctoral
thesis). Downing College, University of Cambridge.
https://doi.org/10.17863/CAM.29356
Design matrix holding the covariants used to solve for the regression
coefficients of the mean signal diffusion kurtosis model. Note that
nub is the number of unique b-values
msignalndarray ([X, Y, Z, …, nub])
Mean signal along all gradient directions for each unique b-value
Note that the last dimension should contain the signal means and nub
is the number of unique b-values.
ngndarray(nub)
Number of gradient directions used to compute the mean signal for
all unique b-values
maskarray
A boolean array used to mark the coordinates in the data that
should be analyzed that has the shape data.shape[:-1]
min_signalfloat, optional
Voxel with mean signal intensities lower than the min positive signal
are not processed. Default: 0.0001
Design matrix or B matrix for the mean signal diffusion kurtosis
model assuming that parameters are in the following order:
design_matrix[j, :] = (msd, msk, S0)
The general fractional anisotropy of a function evaluated
on the unit sphere
Parameters
———-
samples : ndarray
Values of data on the unit sphere.
Returns
——-
gfa : ndarray
GFA evaluated in each entry of the array, along the last dimension.
An np.nan is returned for coordinates that contain all-zeros in
samples.
Notes
—–
The GFA is defined as [1]_ ::
sqrt{frac{n sum_i{(Psi_i - <Psi>)^2}}{(n-1) sum{Psi_i ^ 2}}}
Where \(\Psi\) is an orientation distribution function sampled discretely on
the unit sphere and angle brackets denote average over the samples on the
sphere.
.. [1] Quality assessment of High Angular Resolution Diffusion Imaging
data using bootstrap on Q-ball reconstruction. J. Cohen Adad, M.
Descoteaux, L.L. Wald. JMRI 33: 1194-1208.
The q:math:tau-dMRI model [1] to analytically and continuously represent
the q:math:tau diffusion signal attenuation over diffusion sensitization
q and diffusion time \(\tau\). The model can be seen as an extension of
the MAP-MRI basis [2] towards different diffusion times.
The main idea is to model the diffusion signal over time and space as
a linear combination of continuous functions,
..math::
:nowrap:
begin{equation}
hat{E}(textbf{q},tau;textbf{c}) =
sum_i^{N_{textbf{q}}}sum_k^{N_tau} textbf{c}_{ik}
,Phi_i(textbf{q}),T_k(tau),
end{equation}
where \(\Phi\) and \(T\) are the spatial and temporal basis functions,
\(N_{\textbf{q}}\) and \(N_\tau\) are the maximum spatial and temporal
order, and \(i,k\) are basis order iterators.
The estimation of the coefficients \(c_i\) can be regularized using
either analytic Laplacian regularization, sparsity regularization using
the l1-norm, or both to do a type of elastic net regularization.
From the coefficients, there exists an analytical formula to estimate
the ODF, RTOP, RTAP, RTPP, QIV and MSD, for any diffusion time.
Parameters
———-
gtab : GradientTable,
gradient directions and bvalues container class. The bvalues
should be in the normal s/mm^2. big_delta and small_delta need to
given in seconds.
radial_order : unsigned int,
an even integer representing the spatial/radial order of the basis.
time_order : unsigned int,
an integer larger or equal than zero representing the time order
of the basis.
laplacian_regularization : bool,
Regularize using the Laplacian of the qt-dMRI basis.
laplacian_weighting: string or scalar,
The string ‘GCV’ makes it use generalized cross-validation to find
the regularization weight [3]. A scalar sets the regularization
weight to that value.
l1_regularization : bool,
Regularize by imposing sparsity in the coefficients using the
l1-norm.
l1_weighting : ‘CV’ or scalar,
The string ‘CV’ makes it use five-fold cross-validation to find
the regularization weight. A scalar sets the regularization weight
to that value.
cartesian : bool
Whether to use the Cartesian or spherical implementation of the
qt-dMRI basis, which we first explored in [4].
anisotropic_scaling : bool
Whether to use anisotropic scaling or isotropic scaling. This
option can be used to test if the Cartesian implementation is
equivalent with the spherical one when using the same scaling.
normalization : bool
Whether to normalize the basis functions such that their inner
product is equal to one. Normalization is only necessary when
imposing sparsity in the spherical basis if cartesian=False.
constrain_q0 : bool
whether to constrain the q0 point to unity along the tau-space.
This is necessary to ensure that \(E(0,\tau)=1\).
bval_threshold : float
the threshold b-value to be used, such that only data points below
that threshold are used when estimating the scale factors.
eigenvalue_threshold : float,
Sets the minimum of the tensor eigenvalues in order to avoid
stability problem.
cvxpy_solver : str, optional
cvxpy solver name. Optionally optimize the positivity constraint
with a particular cvxpy solver. See See https://www.cvxpy.org/ for
details. Default: ECOS.
References
———-
.. [1] Fick, Rutger HJ, et al. “Non-Parametric GraphNet-Regularized
Representation of dMRI in Space and Time”, Medical Image Analysis,
2017.
.. [2] Ozarslan E. et al., “Mean apparent propagator (MAP) MRI: A novel
diffusion imaging method for mapping tissue microstructure”,
NeuroImage, 2013.
.. [3] Craven et al. “Smoothing Noisy Data with Spline Functions.”
NUMER MATH 31.4 (1978): 377-403.
.. [4] Fick, Rutger HJ, et al. “A unifying framework for spatial and
temporal diffusion in diffusion mri.” International Conference on
Information Processing in Medical Imaging. Springer, Cham, 2015.
Calculates the analytical Mean Squared Displacement (MSD) for a
given diffusion time tau. It is defined as the Laplacian of the origin
of the estimated signal [1]_. The analytical formula for the MAP-MRI
basis was derived in [2]_ eq. (C13, D1). The qtdmri coefficients are
first converted to mapmri coefficients following [3].
Calculates the norm of the laplacian of the fitted signal [1]_.
This information could be useful to assess if the extrapolation of the
fitted signal contains spurious oscillations. A high laplacian norm may
indicate that these are present, and any q-space indices that
use integrals of the signal may be corrupted (e.g. RTOP, RTAP, RTPP,
QIV). In contrast to [1], the Laplacian now describes oscillations in
the 4-dimensional qt-signal [2].
Calculates the analytical Orientation Distribution Function (ODF)
for a given diffusion time tau from the signal, [1]_ Eq. (32). The
qtdmri coefficients are first converted to mapmri coefficients
following [2].
Calculates the real analytical odf for a given discrete sphere.
Computes the design matrix of the ODF for the given sphere vertices
and radial moment [1]_ eq. (32). The radial moment s acts as a
sharpening method. The analytical equation for the spherical ODF basis
is given in [2]_ eq. (C8). The qtdmri coefficients are first converted
to mapmri coefficients following [3].
Diffusion propagator on a given set of real points.
if the array r_points is non writeable, then intermediate
results are cached for faster recalculation
Calculates the analytical Q-space Inverse Variance (QIV) for given
diffusion time tau.
It is defined as the inverse of the Laplacian of the origin of the
estimated propagator [1]_ eq. (22). The analytical formula for the
MAP-MRI basis was derived in [2]_ eq. (C14, D2). The qtdmri
coefficients are first converted to mapmri coefficients following [3].
This function converts the qtdmri coefficients to mapmri
coefficients for a given tau [1]_. The conversion is performed by a
matrix multiplication that evaluates the time-depenent part of the
basis and multiplies it with the coefficients, after which coefficients
with the same spatial orders are summed up, resulting in mapmri
coefficients.
Calculates the analytical return to the axis probability (RTAP)
for a given diffusion time tau, [1]_ eq. (40, 44a). The analytical
formula for the isotropic MAP-MRI basis was derived in [2]_ eq. (C11).
The qtdmri coefficients are first converted to mapmri coefficients
following [3].
Calculates the analytical return to the origin probability (RTOP)
for a given diffusion time tau [1]_ eq. (36, 43). The analytical
formula for the isotropic MAP-MRI basis was derived in [2]_ eq. (C11).
The qtdmri coefficients are first converted to mapmri coefficients
following [3].
Calculates the analytical return to the plane probability (RTPP)
for a given diffusion time tau, [1]_ eq. (42). The analytical formula
for the isotropic MAP-MRI basis was derived in [2]_ eq. (C11). The
qtdmri coefficients are first converted to mapmri coefficients
following [3].
Generate the matrix that maps the qtdmri coefficients to MAP-MRI
coefficients for the anisotropic case. The conversion is done by only
evaluating the time basis for a diffusion time tau and summing up
coefficients with the same spatial basis orders [1].
Generate the matrix that maps the spherical qtdmri coefficients to
MAP-MRI coefficients for the isotropic case. The conversion is done by only
evaluating the time basis for a diffusion time tau and summing up
coefficients with the same spatial basis orders [1].
Normalization factor for Spherical MAP-MRI basis. The normalization
for a basis function with orders [j,l,m] depends only on orders j,l and
the isotropic scale factor.
dipy.reconst.qtdmri.qtdmri_signal_matrix(radial_order, time_order, us, ut, q, tau)#
Constructs the design matrix as a product of 3 separated radial,
angular and temporal design matrices. It precomputes the relevant basis
orders for each one and finally puts them together according to the index
matrix
Constructs the design matrix as a product of 3 separated radial,
angular and temporal design matrices. It precomputes the relevant basis
orders for each one and finally puts them together according to the index
matrix
Constructs the design matrix as a product of 3 separated radial,
angular and temporal design matrices. It precomputes the relevant basis
orders for each one and finally puts them together according to the index
matrix
Computes the cartesian qt-dMRI Laplacian regularization matrix. If
given, uses precomputed matrices for temporal and spatial regularization
matrices to speed up computation. Follows the the formulation of Appendix B
in [1].
Computes the spherical qt-dMRI Laplacian regularization matrix. If
given, uses precomputed matrices for temporal and spatial regularization
matrices to speed up computation. Follows the the formulation of Appendix C
in [1].
dipy.reconst.qtdmri.l1_crossvalidation(b0s_mask, E, M, weight_array=array([0.,0.02,0.04,0.06,0.08,0.1,0.12,0.14,0.16,0.18,0.2,0.22,0.24,0.26,0.28,0.3,0.32,0.34,0.36,0.38,0.4]))#
cross-validation function to find the optimal weight of alpha for
sparsity regularization
dipy.reconst.qtdmri.elastic_crossvalidation(b0s_mask, E, M, L, lopt, weight_array=array([0.,0.01,0.02,0.03,0.04,0.05,0.06,0.07,0.08,0.09,0.1,0.11,0.12,0.13,0.14,0.15,0.16,0.17,0.18,0.19,0.2]))#
cross-validation function to find the optimal weight of alpha for
sparsity regularization when also Laplacian regularization is used.
This function visualizes a q-tau acquisition scheme as a function of
gradient strength and pulse separation (big_delta). It represents every
measurements at its G and big_delta position regardless of b-vector, with a
background of b-value isolines for reference. It assumes there is only one
unique pulse length (small_delta) in the acquisition scheme.
Array of shape (…, 28) containing the model parameters. Element 0
is the natural logarithm of the signal without diffusion-weighting,
elements 1-6 are the diffusion tensor elements in Voigt notation,
and elements 7-27 are the covariance tensor elements in Voigt
notation.
Array of shape (…, 28) containing the model parameters. Element 0
is the natural logarithm of the signal without diffusion-weighting,
elements 1-6 are the diffusion tensor elements in Voigt notation,
and elements 7-27 are the covariance tensor elements in Voigt
notation.
Try and make a standard array from an object array
This function takes an object array and attempts to convert it to a more
useful dtype. If array can be converted to a better dtype, Nones are
replaced by fill. To make the behaviour of this function more clear, here
are the most common cases:
obj_arr is an array of scalars of type T. Returns an array like
obj_arr.astype(T)
obj_arr is an array of arrays. All items in obj_arr have the same
shape S. Returns an array with shape obj_arr.shape+S
obj_arr is an array of arrays of different shapes. Returns obj_arr.
Items in obj_arr are not ndarrays or scalars. Returns obj_arr.
Apply a function of two arguments cumulatively to the items of a sequence
or iterable, from left to right, so as to reduce the iterable to a single
value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the iterable in the calculation, and serves as a default when the
iterable is empty.
Indices into vals giving local maxima of vals, given topology
from adj_inds, and restrictions from vertex_inds. Inds are
returned sorted by value at that index - i.e. smallest value (at
index) first.
Indices into vals giving local maxima of vals, given topology
from adj_counts and adj_inds, and restrictions from
vertex_inds. Inds are returned sorted by value at that index -
i.e. smallest value (at index) first.
A point is a local maximum if it is > at least one neighbor and >= all
neighbors. If no points meet the above criteria, 1 maximum is returned such
that odf[maximum] == max(odf).
Remove vertices that are less than theta degrees from any other
Returns vertices that are at least theta degrees from any other vertex.
Vertex v and -v are considered the same so if v and -v are both in
vertices only one is kept. Also if v and w are both in vertices, w must
be separated by theta degrees from both v and -v to be unique. To disable
this, set remove_antipodal to False to keep both directions.
Parameters
———-
vertices : (N, 3) ndarray
N unit vectors.
theta : float
The minimum separation between vertices in degrees.
return_mapping : {False, True}, optional
If True, return mapping as well as vertices and maybe indices
(see below).
return_indices : {False, True}, optional
If True, return indices as well as vertices and maybe mapping
(see below).
remove_antipodal : {False, True}, optional
If True, v and -v are considered equal, and only one will be kept.
Returns
——-
unique_vertices : (M, 3) ndarray
Vertices sufficiently separated from one another.
mapping : (N,) ndarray
For each element vertices[i] (\(i \in 0..N-1\)), the index \(j\) to a
vertex in unique_vertices that is less than theta degrees from
vertices[i]. Only returned if return_mapping is True.
indices : (N,) ndarray
indices gives the reverse of mapping. For each element
unique_vertices[j] (\(j \in 0..M-1\)), the index \(i\) to a vertex in
vertices that is less than theta degrees from
unique_vertices[j]. If there is more than one element of
vertices that is less than theta degrees from unique_vertices[j],
return the first (lowest index) matching value. Only return if
return_indices is True.
i in descending array a so a[i] < a[0] * relative_threshold
Call T=a[0]*relative_threshold. Return value i will be the
smallest index in the descending array a such that a[i]<T.
Equivalently, i will be the largest index such that all(a[:i]>=T).
If all values in a are >= T, return the length of array a.
Robust and Unbiased Model-BAsed Spherical Deconvolution (RUMBA-SD) [1]_
Modification of the Richardson-Lucy algorithm accounting for Rician
and Noncentral Chi noise distributions, which more accurately
represent MRI noise. Computes a maximum likelihood estimation of the
fiber orientation density function (fODF) at each voxel. Includes
white matter compartments alongside optional GM and CSF compartments
to account for partial volume effects. This fit can be performed
voxelwise or globally. The global fit will proceed more quickly than
the voxelwise fit provided that the computer has adequate RAM (>= 16 GB
should be sufficient for most datasets).
Kernel for deconvolution constructed using a priori knowledge of white
matter response function, as well as the mean diffusivity of GM and/or
CSF. RUMBA-SD is robust against impulse response imprecision, and thus
the default diffusivity values are often adequate [2]_.
gtab : GradientTable
wm_response : 1d ndarray or 2d ndarray or AxSymShResponse, optional
Tensor eigenvalues as a (3,) ndarray, multishell eigenvalues as
a (len(unique_bvals_tolerance(gtab.bvals))-1, 3) ndarray in
order of smallest to largest b-value, or an AxSymShResponse.
Default: np.array([1.7e-3, 0.2e-3, 0.2e-3])
gm_responsefloat, optional
Mean diffusivity for GM compartment. If None, then grey
matter volume fraction is not computed. Default: 0.8e-3
csf_responsefloat, optional
Mean diffusivity for CSF compartment. If None, then CSF
volume fraction is not computed. Default: 3.0e-3
n_iterint, optional
Number of iterations for fODF estimation. Must be a positive int.
Default: 600
recon_type{‘smf’, ‘sos’}, optional
MRI reconstruction method: spatial matched filter (SMF) or
sum-of-squares (SoS). SMF reconstruction generates Rician noise
while SoS reconstruction generates Noncentral Chi noise.
Default: ‘smf’
n_coilsint, optional
Number of coils in MRI scanner – only relevant in SoS
reconstruction. Must be a positive int. Default: 1
Rint, optional
Acceleration factor of the acquisition. For SIEMENS,
R = iPAT factor. For GE, R = ASSET factor. For PHILIPS,
R = SENSE factor. Typical values are 1 or 2. Must be a positive
int. Default: 1
voxelwisebool, optional
If true, performs a voxelwise fit. If false, performs a global fit
on the entire brain at once. The global fit requires a 4D brain
volume in fit. Default: True
use_tvbool, optional
If true, applies total variation regularization. This only takes
effect in a global fit (voxelwise is set to False). TV can only
be applied to 4D brain volumes with no singleton dimensions.
Default: False
sphereSphere, optional
Sphere on which to construct fODF. If None, uses repulsion724.
Default: None
verbosebool, optional
If true, logs updates on estimated signal-to-noise ratio after each
iteration. This only takes effect in a global fit (voxelwise is
set to False). Default: False
The gradients for which the signal will be predicted. Use the
model’s gradient table if None. Default: None
S0ndarray ([x, y, z]) or float, optional
The non diffusion-weighted signal value for each voxel. If a float,
the same value is used for each voxel. If None, 1 is used for
each voxel. Default: None
Instances of the Logger class represent a single logging channel. A
“logging channel” indicates an area of an application. Exactly how an
“area” is defined is up to the application developer. Since an
application can have any number of areas, logging channels are identified
by a unique string. Application areas can be nested (e.g. an area
of “input processing” might include sub-areas “read CSV files”, “read
XLS files” and “read Gnumeric files”). To cater for this natural nesting,
channel names are organized into a namespace hierarchy where levels are
separated by periods, much like the Java or Python package namespace. So
in the instance given above, channel names might be “input” for the upper
level, and “input.csv”, “input.xls” and “input.gnu” for the sub-levels.
There is no arbitrary limit to the depth of nesting.
Fit fODF and GM/CSF volume fractions for a voxel using RUMBA-SD [1]_.
Deconvolves the kernel from the diffusion-weighted signal by computing a
maximum likelihood estimation of the fODF. Minimizes the negative
log-likelihood of the data under Rician or Noncentral Chi noise
distributions by adapting the iterative technique developed in
Richardson-Lucy deconvolution.
Parameters
———-
data : 1d ndarray (N,)
Signal values for a single voxel.
kernel : 2d ndarray (N, M)
Deconvolution kernel mapping volume fractions of the M compartments to
N-length signal. Last two columns should be for GM and CSF.
n_iter : int, optional
Number of iterations for fODF estimation. Must be a positive int.
Default: 600
recon_type : {‘smf’, ‘sos’}, optional
MRI reconstruction method: spatial matched filter (SMF) or
sum-of-squares (SoS). SMF reconstruction generates Rician noise while
SoS reconstruction generates Noncentral Chi noise. Default: ‘smf’
n_coils : int, optional
Number of coils in MRI scanner – only relevant in SoS reconstruction.
Must be a positive int. Default: 1
Returns
——-
fit_vec : 1d ndarray (M,)
Vector containing fODF and GM/CSF volume fractions. First M-2
components are fODF while last two are GM and CSF respectively.
Notes
—–
The diffusion MRI signal measured at a given voxel is a sum of
contributions from each intra-voxel compartment, including parallel white
matter (WM) fiber populations in a given orientation as well as effects
from GM and CSF. The equation governing these contributions is:
\(S_i = S_0\left(\sum_{j=1}^{M}f_j\exp(-b_i\textbf{v}_i^T\textbf{D}_j
\textbf{v}_i) + f_{GM}\exp(-b_iD_{GM})+f_{CSF}\exp(-b_iD_{CSF})\right)\)
Where \(S_i\) is the resultant signal along the diffusion-sensitizing
gradient unit vector \(\textbf{v_i}; i = 1, ..., N\) with a b-value of \(b_i\).
\(f_j; j = 1, ..., M\) is the volume fraction of the \(j^{th}\) fiber
population with an anisotropic diffusion tensor \(\textbf{D_j}\).
\(f_{GM}\) and \(f_{CSF}\) are the volume fractions and \(D_{GM}\) and \(D_{CSF}\)
are the mean diffusivities of GM and CSF respectively.
This equation is linear in \(f_j, f_{GM}, f_{CSF}\) and can be simplified to
a single matrix multiplication:
\(\textbf{S} = \textbf{Hf}\)
Where \(\textbf{S}\) is the signal vector at a certain voxel, \(\textbf{H}\) is
the deconvolution kernel, and \(\textbf{f}\) is the vector of volume
fractions for each compartment.
Modern MRI scanners produce noise following a Rician or Noncentral Chi
distribution, depending on their signal reconstruction technique [2]_.
Using this linear model, it can be shown that the likelihood of a signal
under a Noncentral Chi noise model is:
\(P(\textbf{S}|\textbf{H}, \textbf{f}, \sigma^2, n) = \prod_{i=1}^{N}\left(
\frac{S_i}{\bar{S_i}}\right)^n\exp\left\{-\frac{1}{2\sigma^2}\left[
S_i^2 + \bar{S}_i^2\right]\right\}I_{n-1}\left(\frac{S_i\bar{S}_i}
{\sigma^2}\right)u(S_i)\)
Where \(S_i\) and \(\bar{S}_i = \textbf{Hf}\) are the measured and expected
signals respectively, and \(n\) is the number of coils in the scanner, and
\(I_{n-1}\) is the modified Bessel function of first kind of order \(n-1\).
This gives the likelihood under a Rician distribution when \(n\) is set to 1.
By taking the negative log of this with respect to \(\textbf{f}\) and setting
the derivative to 0, the \(\textbf{f}\) maximizing likelihood is found to be:
\(\textbf{f} = \textbf{f} \circ \frac{\textbf{H}^T\left[\textbf{S}\circ
\frac{I_n(\textbf{S}\circ \textbf{Hf}/\sigma^2)} {I_{n-1}(\textbf{S}
\circ\textbf{Hf}\sigma^2)} \right ]} {\textbf{H}^T\textbf{Hf}}\)
The solution can be found using an iterative scheme, just as in the
Richardson-Lucy algorithm:
\(\textbf{f}^{k+1} = \textbf{f}^k \circ \frac{\textbf{H}^T\left[\textbf{S}
\circ\frac{I_n(\textbf{S}\circ\textbf{Hf}^k/\sigma^2)} {I_{n-1}(\textbf{S}
\circ\textbf{Hf}^k/\sigma^2)} \right ]} {\textbf{H}^T\textbf{Hf}^k}\)
In order to apply this, a reasonable estimate of \(\sigma^2\) is required.
To find this, a separate iterative scheme is found using the derivative
of the negative log with respect to \(\sigma^2\), and is run in parallel.
This is shown here:
\(\alpha^{k+1} = \frac{1}{nN}\left\{ \frac{\textbf{S}^T\textbf{S} +
\textbf{f}^T\textbf{H}^T\textbf{Hf}}{2} - \textbf{1}^T_N\left[(\textbf{S}
\circ\textbf{Hf})\circ\frac{I_n(\textbf{S}\circ\textbf{Hf}/\alpha^k)}
{I_{n-1}(\textbf{S}\circ\textbf{Hf}/\alpha^k)} \right ]\right \}\)
For more details, see [1]_.
References
———-
.. [1] Canales-Rodríguez, E. J., Daducci, A., Sotiropoulos, S. N., Caruyer,
E., Aja-Fernández, S., Radua, J., Mendizabal, J. M. Y.,
Iturria-Medina, Y., Melie-García, L., Alemán-Gómez, Y., Thiran,
J.-P.,Sarró, S., Pomarol-Clotet, E., & Salvador, R. (2015).
Spherical Deconvolution of Multichannel Diffusion MRI Data with
Non-Gaussian Noise Models and Spatial Regularization. PLOS ONE,
10(10), e0138910. https://doi.org/10.1371/journal.pone.0138910
.. [2] Constantinides, C. D., Atalar, E., & McVeigh, E. R. (1997).
Signal-to-Noise Measurements in Magnitude Images from NMR Phased
Arrays. Magnetic Resonance in Medicine: Official Journal of the
Society of Magnetic Resonance in Medicine / Society of Magnetic
Resonance in Medicine, 38(5), 852–857.
Fast computation of modified Bessel function ratio (first kind).
Computes:
\(I_{n}(x) / I_{n-1}(x)\)
using Perron’s continued fraction equation where \(I_n\) is the modified
Bessel function of first kind, order \(n\)[1]_.
Parameters
———-
n : int
Order of Bessel function in numerator (denominator is of order n-1).
Must be a positive int.
x : float or ndarray
Value or array of values with which to compute ratio.
Returns
——-
y : float or ndarray
Result of ratio computation.
References
———-
.. [1] W. Gautschi and J. Slavik, “On the computation of modified Bessel
function ratios,” Math. Comp., vol. 32, no. 143, pp. 865–875, 1978,
doi: 10.1090/S0025-5718-1978-0470267-9
Compute kernel mapping orientation densities of white matter fiber
populations (along each vertex of the sphere) and isotropic volume
fractions to a diffusion weighted signal.
Sphere with which to sample discrete fiber orientations in order to
construct kernel
wm_response1d ndarray or 2d ndarray or AxSymShResponse, optional
Tensor eigenvalues as a (3,) ndarray, multishell eigenvalues as
a (len(unique_bvals_tolerance(gtab.bvals))-1, 3) ndarray in
order of smallest to largest b-value, or an AxSymShResponse.
gm_responsefloat, optional
Mean diffusivity for GM compartment. If None, then grey
matter compartment set to all zeros.
csf_responsefloat, optional
Mean diffusivity for CSF compartment. If None, then CSF
compartment set to all zeros.
Computed kernel; can be multiplied with a vector consisting of volume
fractions for each of M-2 fiber populations as well as GM and CSF
fractions to produce a diffusion weighted signal.
Fit fODF for all voxels simultaneously using RUMBA-SD.
Deconvolves the kernel from the diffusion-weighted signal at each voxel by
computing a maximum likelihood estimation of the fODF [1]_. Global fitting
also permits the use of total variation regularization (RUMBA-SD + TV). The
spatial dependence introduced by TV promotes smoother solutions (i.e.
prevents oscillations), while still allowing for sharp discontinuities
[2]_. This promotes smoothness and continuity along individual tracts while
preventing smoothing of adjacent tracts.
Generally, global_fit will proceed more quickly than the voxelwise fit
provided that the computer has adequate RAM (>= 16 GB should be more than
sufficient).
Parameters
———-
data : 4d ndarray (x, y, z, N)
Signal values for entire brain. None of the volume dimensions x, y, z
can be 1 if TV regularization is required.
kernel : 2d ndarray (N, M)
Deconvolution kernel mapping volume fractions of the M compartments to
N-length signal. Last two columns should be for GM and CSF.
mask : 3d ndarray(x, y, z)
Binary mask specifying voxels of interest with 1; fODF will only be
fit at these voxels (0 elsewhere).
n_iter : int, optional
Number of iterations for fODF estimation. Must be a positive int.
Default: 600
recon_type : {‘smf’, ‘sos’}, optional
MRI reconstruction method: spatial matched filter (SMF) or
sum-of-squares (SoS). SMF reconstruction generates Rician noise while
SoS reconstruction generates Noncentral Chi noise. Default: ‘smf’
n_coils : int, optional
Number of coils in MRI scanner – only relevant in SoS reconstruction.
Must be a positive int. Default: 1
use_tv : bool, optional
If true, applies total variation regularization. This requires a brain
volume with no singleton dimensions. Default: True
verbose : bool, optional
If true, logs updates on estimated signal-to-noise ratio after each
iteration. Default: False
Returns
——-
fit_array : 4d ndarray (x, y, z, M)
fODF and GM/CSF volume fractions computed for each voxel. First M-2
components are fODF, while last two are GM and CSf respectively.
Notes
—–
TV modifies our cost function as follows:
\(J(\textbf{f}) = -\log{P(\textbf{S}|\textbf{H}, \textbf{f}, \sigma^2, n)})+
\alpha_{TV}TV(\textbf{f})\)
where the first term is the negative log likelihood described in the notes
of rumba_deconv, and the second term is the TV energy, or the sum of
gradient absolute values for the fODF across the entire brain. This results
in a new multiplicative factor in the iterative scheme, now becoming:
\(\textbf{f}^{k+1} = \textbf{f}^k \circ \frac{\textbf{H}^T\left[\textbf{S}
\circ\frac{I_n(\textbf{S}\circ\textbf{Hf}^k/\sigma^2)} {I_{n-1}(\textbf{S}
\circ\textbf{Hf}^k/\sigma^2)} \right ]} {\textbf{H}^T\textbf{Hf}^k}\circ
\textbf{R}^k\)
where \(\textbf{R}^k\) is computed voxelwise by:
\((\textbf{R}^k)_j = \frac{1}{1 - \alpha_{TV}div\left(\frac{\triangledown[
\textbf{f}^k_{3D}]_j}{\lvert\triangledown[\textbf{f}^k_{3D}]_j \rvert}
\right)\biggr\rvert_{x, y, z}}\)
Here, \(\triangledown\) is the symbol for the 3D gradient at any voxel.
The regularization strength, \(\alpha_{TV}\) is updated after each iteration
by the discrepancy principle – specifically, it is selected to match the
estimated variance after each iteration [3]_.
References
———-
.. [1] Canales-Rodríguez, E. J., Daducci, A., Sotiropoulos, S. N., Caruyer,
E., Aja-Fernández, S., Radua, J., Mendizabal, J. M. Y.,
Iturria-Medina, Y., Melie-García, L., Alemán-Gómez, Y., Thiran,
J.-P., Sarró, S., Pomarol-Clotet, E., & Salvador, R. (2015).
Spherical Deconvolution of Multichannel Diffusion MRI Data with
Non-Gaussian Noise Models and Spatial Regularization. PLOS ONE,
10(10), e0138910. https://doi.org/10.1371/journal.pone.0138910
.. [2] Rudin, L. I., Osher, S., & Fatemi, E. (1992). Nonlinear total
variation based noise removal algorithms. Physica D: Nonlinear
Phenomena, 60(1), 259–268.
https://doi.org/10.1016/0167-2789(92)90242-F
.. [3] Chambolle A. An algorithm for total variation minimization and
applications. Journal of Mathematical Imaging and Vision. 2004;
20:89–97.
A base-class for the representation of isotropic signals.
The default behavior, suitable for single b-value data is to calculate the
mean in each voxel as an estimate of the signal that does not depend on
direction.
A boolean array used to mark the coordinates in the data that
should be analyzed. Has the shape data.shape[:-1]. Default: None,
which implies that all points should be analyzed.
Predict the isotropic signal, based on a gradient table. In this case,
the prediction will be for an exponential decay with the mean
diffusivity derived from the data that was fit.
A sphere on which coefficients will be estimated. Default:
symmetric sphere with 362 points (from dipy.data).
response(3,) array-like, optional
The eigenvalues of a canonical tensor to be used as the response
function of single-fascicle signals.
Default:[0.0015, 0.0005, 0.0005]
solverstring, or initialized linear model object.
This will determine the algorithm used to solve the set of linear
equations underlying this model. If it is a string it needs to be
one of the following: {‘ElasticNet’, ‘NNLS’}. Otherwise, it can be
an object that inherits from dipy.optimize.SKLearnLinearSolver
or an object with a similar interface from Scikit Learn:
sklearn.linear_model.ElasticNet, sklearn.linear_model.Lasso or
sklearn.linear_model.Ridge and other objects that inherit from
sklearn.base.RegressorMixin.
Default: ‘ElasticNet’.
l1_ratiofloat, optional
Sets the balance between L1 and L2 regularization in ElasticNet
[Zou2005]. Default: 0.5
alphafloat, optional
Sets the balance between least-squares error and L1/L2
regularization in ElasticNet [Zou2005]. Default: 0.001
isotropicIsotropicModel class instance
This is a class that implements the function that calculates the
value of the isotropic signal. This is a value of the signal that
is independent of direction, and therefore removed from both sides
of the SFM equation. The default is an instance of IsotropicModel,
but other functions can be inherited from IsotropicModel to
implement other fits to the aspects of the data that depend on
b-value, but not on direction.
This is an implementation of the SFM, described in [Rokem2015].
[Rokem2014]
Ariel Rokem, Jason D. Yeatman, Franco Pestilli, Kendrick
N. Kay, Aviv Mezer, Stefan van der Walt, Brian A. Wandell
(2014). Evaluating the accuracy of diffusion MRI models in white
matter. PLoS ONE 10(4): e0123272. doi:10.1371/journal.pone.0123272
A boolean array used to mark the coordinates in the data that
should be analyzed. Has the shape data.shape[:-1]. Default: None,
which implies that all points should be analyzed.
num_processesint, optional
Split the fit calculation to a pool of children processes using
joblib. This only applies to 4D data arrays. Default is 1,
which does not require joblib and will run fit serially.
If < 0 the maximal number of cores minus num_processes+1
is used (enter -1 to use as many cores as possible).
0 raises an error.
parallel_backend: str, ParallelBackendBase instance or None
Specify the parallelization backend implementation.
Supported backends are:
- “loky” used by default, can induce some
communication and memory overhead when exchanging input and
output data with the worker Python processes.
“multiprocessing” previous process-based backend based on
multiprocessing.Pool. Less robust than loky.
“threading” is a very low-overhead backend but it suffers
from the Python Global Interpreter Lock if the called function
relies a lot on Python objects. “threading” is mostly useful
when the execution bottleneck is a compiled extension that
explicitly releases the GIL (for instance a Cython loop wrapped
in a “with nogil” block or an expensive call to a library such
as NumPy).
A representation of the isotropic signal, together with parameters
of the isotropic signal in each voxel, that is capable of
deriving/predicting an isotropic signal, based on a gradient-table.
Sets the rows of the matrix, if the mode is ‘signal’, this should be a
GradientTable. If mode is ‘odf’ this should be a Sphere.
sphereSphere
Sets the columns of the matrix
responselist of 3 elements
The eigenvalues of a tensor which will serve as a kernel
function.
modestr {‘signal’ | ‘odf’}, optional
Choose the (default) ‘signal’ for a design matrix containing predicted
signal in the measurements defined by the gradient table for putative
fascicles oriented along the vertices of the sphere. Otherwise, choose
‘odf’ for an odf convolution matrix, with values of the odf calculated
from a tensor with the provided response eigenvalues, evaluated at the
b-vectors in the gradient table, for the tensors with principal
diffusion directions along the vertices of the sphere.
A design matrix that can be used for one of the following operations:
when the ‘signal’ mode is used, each column contains the putative
signal in each of the bvectors of the gtab if a fascicle is oriented
in the direction encoded by the sphere vertex corresponding to this
column. This is used for deconvolution with a measured DWI signal. If
the ‘odf’ mode is chosen, each column instead contains the values of
the tensor ODF for a tensor with a principal diffusion direction
corresponding to this vertex. This is used to generate odfs from the
fits of the SFM for the purpose of tracking.
Ariel Rokem, Jason D. Yeatman, Franco Pestilli, Kendrick
N. Kay, Aviv Mezer, Stefan van der Walt, Brian A. Wandell
(2015). Evaluating the accuracy of diffusion MRI models in white
matter. PLoS ONE 10(4): e0123272. doi:10.1371/journal.pone.0123272
[Rokem2014]
Ariel Rokem, Kimberly L. Chan, Jason D. Yeatman, Franco
Pestilli, Brian A. Wandell (2014). Evaluating the accuracy of diffusion
models at multiple b-values with cross-validation. ISMRM 2014.
the maximal spherical harmonic order (l) of the model
smoothfloat between 0 and 1, optional
The regularization parameter of the model
min_signalfloat, > 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_normedbool, 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.
the maximal spherical harmonic order (l) of the model
smoothfloat between 0 and 1, optional
The regularization parameter of the model
min_signalfloat, > 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_normedbool, 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.
the maximal spherical harmonic order (l) of the model
smoothfloat between 0 and 1, optional
The regularization parameter of the model
min_signalfloat, > 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_normedbool, 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.
the maximal spherical harmonic order (l) of the model
smoothfloat between 0 and 1, optional
The regularization parameter of the model
min_signalfloat, > 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_normedbool, 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.
Returns a residual bootstrap sample of the signal_object when indexed
Wraps a signal_object, this signal object can be an interpolator. When
indexed, the the wrapper indexes the signal_object to get the signal.
There wrapper than samples the residual bootstrap distribution of signal and
returns that sample.
Given some linear model described by B, the design matrix, and a
signal_object, returns an object which can sample the residual
bootstrap distribution of the signal. We assume that the signals are
normalized so we clip the bootstrap samples to be between min_signal
and 1.
This object should return diffusion weighted signals when indexed.
Bndarray, ndim=2
The design matrix of the spherical harmonics model used to fit the
data. This is the model that will be used to compute the residuals
and sample the residual bootstrap distribution
where_dwi :
indexing object to find diffusion weighted signals from signal
Spherical harmonics (SH) to rotational harmonics (RH)
Calculate the rotational harmonic decomposition up to
harmonic phase factor m, order l 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.
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_valuesndarray (N,)
The phase factors (m) of the spherical harmonic function associated with
each coefficient.
l_valuesndarray (N,)
The orders (l) of the spherical harmonic function associated with each
coefficient.
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.
The phase factors of the spherical harmonic function associated with
each coefficient.
l_valuesndarray (N,)
The order (l) of the spherical harmonic function associated with each
coefficient.
thetafloat [0, pi]
The polar (colatitudinal) coordinate.
phifloat [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).
Compute spherical harmonics.
This may take scalar or array arguments. The inputs will be broadcast
against each other.
Parameters
———-
m_values : array of int |m|<=l
The phase factors (m) of the harmonics.
l_values : array of int l>=0
The orders (l) of the harmonics.
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_l\) 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 l>=0 and |m|<=l.
Compute real spherical harmonics.
dipy.reconst.shm.real_sph_harm is deprecated, Please use dipy.reconst.shm.real_sh_descoteaux_from_index instead
* deprecated from version: 1.3
* Will raise <class ‘dipy.utils.deprecator.ExpiredDeprecationError’> as of version: 2.0
Where the real harmonic \(Y^m_l\) is defined to be:
Imag(\(Y^m_l\)) * sqrt(2) if m > 0
\(Y^0_l\) if m = 0
Real(\(Y^|m|_l\)) * sqrt(2) if m < 0
This may take scalar or array arguments. The inputs will be broadcast
against each other.
Parameters
———-
m_values : array of int |m|<=l
The phase factors (m) of the harmonics.
l_values : array of int l>=0
The orders (l) of the harmonics.
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_l\) sampled at theta and phi.
See Also
——–
scipy.special.sph_harm
Compute real spherical harmonics as initially defined in Tournier
2007 [1]_ then updated in MRtrix3 [2]_, where the real harmonic \(Y^m_l\)
is defined to be:
Real(\(Y^m_l\)) * sqrt(2) if m > 0
\(Y^0_l\) if m = 0
Imag(\(Y^|m|_l\)) * sqrt(2) if m < 0
This may take scalar or array arguments. The inputs will be broadcast
against each other.
Parameters
———-
m_values : array of int |m|<=l
The phase factors (m) of the harmonics.
l_values : array of int l>=0
The orders (l) of the harmonics.
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_l\) 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.
Compute real spherical harmonics as in Descoteaux et al. 2007 [1]_,
where the real harmonic \(Y^m_l\) is defined to be:
Imag(\(Y^m_l\)) * sqrt(2) if m > 0
\(Y^0_l\) if m = 0
Real(\(Y^m_l\)) * sqrt(2) if m < 0
This may take scalar or array arguments. The inputs will be broadcast
against each other.
Parameters
———-
m_values : array of int |m|<=l
The phase factors (m) of the harmonics.
l_values : array of int l>=0
The orders (l) of the harmonics.
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_l\) 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.
Compute real spherical harmonics as initially defined in Tournier
2007 [1]_ then updated in MRtrix3 [2]_, where the real harmonic \(Y^m_l\)
is defined to be:
Real(\(Y^m_l\)) * sqrt(2) if m > 0
\(Y^0_l\) if m = 0
Imag(\(Y^|m|_l\)) * sqrt(2) if m < 0
This may take scalar or array arguments. The inputs will be broadcast
against each other.
Parameters
———-
sh_order_max : int
The maximum order (l) of 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_l\) sampled at theta and phi.
m_values : array of int
The phase factor (m) of the harmonics.
l_values : array of int
The order (l) 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.
Compute real spherical harmonics as in Descoteaux et al. 2007 [1]_,
where the real harmonic \(Y^m_l\) is defined to be:
Imag(\(Y^m_l\)) * sqrt(2) if m > 0
\(Y^0_l\) if m = 0
Real(\(Y^m_l\)) * sqrt(2) if m < 0
This may take scalar or array arguments. The inputs will be broadcast
against each other.
Parameters
———-
sh_order_max : int
The maximum order (l) of 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_l\) sampled at theta and phi.
m_values : array of int
The phase factor (m) of the harmonics.
l_values : array of int
The order (l) 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.
dipy.reconst.shm.real_sym_sh_mrtrix is deprecated, Please use dipy.reconst.shm.real_sh_tournier instead
* deprecated from version: 1.3
* Will raise <class ‘dipy.utils.deprecator.ExpiredDeprecationError’> as of version: 2.0
Compute real symmetric spherical harmonics as in Tournier 2007 [2]_, where
the real harmonic \(Y^m_l\) is defined to be::
Real(\(Y^m_l\)) if m > 0
\(Y^0_l\) if m = 0
Imag(\(Y^|m|_l\)) if m < 0
This may take scalar or array arguments. The inputs will be broadcast
against each other.
Parameters
———-
sh_order_max : int
The maximum order (l) of 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_l\) sampled at theta and phi as
implemented in mrtrix. Warning: the basis is Tournier et al.
2007 [2]_; 2004 [1]_ is slightly different.
m_values : array
The phase factor (m) of the harmonics.
l_values : array
The order (l) 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.
Samples a real symmetric spherical harmonic basis at point on the sphere
dipy.reconst.shm.real_sym_sh_basis is deprecated, Please use dipy.reconst.shm.real_sh_descoteaux instead
* deprecated from version: 1.3
* Will raise <class ‘dipy.utils.deprecator.ExpiredDeprecationError’> as of version: 2.0
Samples the basis functions up to order sh_order_max 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_l\)
is defined to be:
Imag(\(Y^m_l\)) * sqrt(2) if m > 0
\(Y^0_l\) if m = 0
Real(\(Y^|m|_l\)) * sqrt(2) if m < 0
This may take scalar or array arguments. The inputs will be broadcast
against each other.
Parameters
———-
sh_order_max : int
The maximum order (l) of the spherical harmonic basis. 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_l\) sampled at theta and phi
m_values : array of int
The phase factor (m) of the harmonics.
l_values : array of int
The order (l) 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.
Returns the order (l) and phase_factor (m) of all the symmetric
spherical harmonics of order less then or equal to sh_order_max.
The results, m_list and l_list are kx1 arrays, where k depends on
sh_order_max.
They can be passed to real_sh_descoteaux_from_index() and
:func:real_sh_tournier_from_index.
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.
Applies the Residual Bootstraps to the data given H and R
data must be normalized, ie 0 < data <= 1
This function, and the bootstrap_data_voxel function, calculate
residual-bootstrap samples given a Hat matrix and a Residual matrix. These
samples can be used for non-parametric statistics or for bootstrap
probabilistic tractography:
Maximum SH order (l) in the SH fit. For sh_order_max, there will be
(sh_order_max+1)*(sh_order_max+2)/2 SH coefficients for a
symmetric basis and (sh_order_max+1)*(sh_order_max+1)
coefficients for a full SH basis.
None for the default DIPY basis,
tournier07 for the Tournier 2007 [2]_[3]_ basis,
descoteaux07 for the Descoteaux 2007 [1]_ basis,
(None defaults to descoteaux07).
full_basis: bool, optional
True for using a SH basis containing even and odd order SH functions.
False for using a SH basis consisting only of even order SH functions.
legacy: bool, optional
True to use a legacy basis definition for backward compatibility
with previous tournier07 and descoteaux07 implementations.
SH coefficients representing a spherical function.
sphereSphere
The points on which to sample the spherical function.
sh_order_maxint, optional
Maximum SH order (l) in the SH fit. For sh_order_max, there will be
(sh_order_max+1)*(sh_order_max+2)/2 SH coefficients for a
symmetric basis and (sh_order_max+1)*(sh_order_max+1)
coefficients for a full SH basis.
None for the default DIPY basis,
tournier07 for the Tournier 2007 [2]_[3]_ basis,
descoteaux07 for the Descoteaux 2007 [1]_ basis,
(None defaults to descoteaux07).
full_basis: bool, optional
True to use a SH basis containing even and odd order SH functions.
Else, use a SH basis consisting only of even order SH functions.
legacy: bool, optional
True to use a legacy basis definition for backward compatibility
with previous tournier07 and descoteaux07 implementations.
The points on which to sample the spherical function.
sh_order_maxint, optional
Maximum SH order in the SH fit. For sh_order_max, there will be
(sh_order_max+1)*(sh_order_max+2)/2 SH coefficients for a
symmetric basis and (sh_order_max+1)*(sh_order_max+1)
coefficients for a full SH basis.
None for the default DIPY basis,
tournier07 for the Tournier 2007 [2]_[3]_ basis,
descoteaux07 for the Descoteaux 2007 [1]_ basis,
(None defaults to descoteaux07).
full_basis: bool, optional
If True, uses a SH basis containing even and odd order SH functions.
Else, uses a SH basis consisting only of even order SH functions.
legacy: bool, optional
True to use a legacy basis definition for backward compatibility
with previous tournier07 and descoteaux07 implementations.
return_invbool, optional
If True then the inverse of the matrix is also returned.
Calculate the maximal harmonic order (l), given that you know the
number of parameters that were estimated.
Parameters
———-
n_coeffs : int
The number of SH coefficients
full_basis: bool, optional
True if the used SH basis contains even and odd order SH functions.
False if the SH basis consists only of even order SH functions.
Returns
——-
L : int
The maximal SH order (l), given the number of coefficients
Notes
—–
The calculation in this function for the symmetric SH basis
proceeds according to the following logic:
.. math::
n = frac{1}{2} (L+1) (L+2)
rarrow 2n = L^2 + 3L + 2
rarrow L^2 + 3L + 2 - 2n = 0
rarrow L^2 + 3L + 2(1-n) = 0
rarrow L_{1,2} = frac{-3 pm sqrt{9 - 8 (1-n)}}{2}
rarrow L{1,2} = frac{-3 pm sqrt{1 + 8n}}{2}
Finally, the positive value is chosen between the two options.
For a full SH basis, the calculation consists in solving the equation
\(n = (L + 1)^2\) for \(L\), which gives \(L = sqrt(n) - 1\).
Calculate anisotropic power map with a given SH coefficient matrix.
Parameters
———-
sh_coeffs : ndarray
A ndarray where the last dimension is the
SH coefficients estimates for that voxel.
norm_factor: float, optional
The value to normalize the ap values.
power : int, optional
The degree to which power maps are calculated.
non_negative: bool, optional
Whether to rectify the resulting map to be non-negative.
Returns
——-
log_ap : ndarray
The log of the resulting power image.
Notes
—–
Calculate AP image based on a IxJxKxC SH coefficient matrix based on the
equation:
.. math::
AP = sum_{l=2,4,6,…}{frac{1}{2l+1} sum_{m=-l}^l{|a_{l,m}|^n}}
Where the last dimension, C, is made of a flattened array of \(l`x:math:`m\)
coefficients, where \(l\) are the SH orders, and \(m = 2l+1\),
So l=1 has 1 coefficient, l=2 has 5, … l=8 has 17 and so on.
A l=2 SH coefficient matrix will then be composed of a IxJxKx6 volume.
The power, \(n\) is usually set to \(n=2\).
The final AP image is then shifted by -log(norm_factor), to be strictly
non-negative. Remaining values < 0 are discarded (set to 0), per default,
and this option is controlled through the non_negative keyword argument.
References
———-
.. [1] Dell’Acqua, F., Lacerda, L., Catani, M., Simmons, A., 2014.
Anisotropic Power Maps: A diffusion contrast to reveal low
anisotropy tissues from HARDI data,
in: Proceedings of International Society for Magnetic Resonance in
Medicine. Milan, Italy.
Convert SH coefficients between legacy-descoteaux07 and tournier07.
Convert SH coefficients between the legacy descoteaux07 SH basis and
the non-legacy tournier07 SH basis. Because this conversion is equal to
its own inverse, it can be used to convert in either direction:
legacy-descoteaux to non-legacy-tournier or non-legacy-tournier to
legacy-descoteaux.
This can be used to convert SH representations between DIPY and MRtrix3.
The array of coefficients expressed in the “other” SH basis. If the
input was in the legacy-descoteaux basis then the output will be in the
non-legacy-tournier basis, and vice versa.
Descoteaux, M., Angelino, E., Fitzgibbons, S. and
Deriche, R. Regularized, Fast, and Robust Analytical Q-ball Imaging.
Magn. Reson. Med. 2007;58:497-510.
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.
Simple Harmonic Oscillator based Reconstruction and Estimation
(SHORE) [1]_ of the diffusion signal.
The main idea is to model the diffusion signal as a linear combination of
continuous functions \(\phi_i\),
..math::
:nowrap:
begin{equation}
S(mathbf{q})= sum_{i=0}^I c_{i} phi_{i}(mathbf{q}).
end{equation}
where \(\mathbf{q}\) is the wave vector which corresponds to different
gradient directions. Numerous continuous functions \(\phi_i\) can be used to
model \(S\). Some are presented in [2,3,4]_.
From the \(c_i\) coefficients, there exist analytical formulae to estimate
the ODF, the return to the origin probability (RTOP), the mean square
displacement (MSD), amongst others [5]_.
References
———-
.. [1] Ozarslan E. et al., “Simple harmonic oscillator based reconstruction
and estimation for one-dimensional q-space magnetic resonance
1D-SHORE)”, Proc Intl Soc Mag Reson Med, vol. 16, p. 35., 2008.
.. [2] Merlet S. et al., “Continuous diffusion signal, EAP and ODF
estimation via Compressive Sensing in diffusion MRI”, Medical
Image Analysis, 2013.
.. [3] Rathi Y. et al., “Sparse multi-shell diffusion imaging”, MICCAI,
2011.
.. [4] Cheng J. et al., “Theoretical Analysis and Practical Insights on
EAP Estimation via a Unified HARDI Framework”, MICCAI workshop on
Computational Diffusion MRI, 2011.
.. [5] Ozarslan E. et al., “Mean apparent propagator (MAP) MRI: A novel
diffusion imaging method for mapping tissue microstructure”,
NeuroImage, 2013.
Notes
—–
The implementation of SHORE depends on CVXPY (https://www.cvxpy.org/).
Analytical and continuous modeling of the diffusion signal with
respect to the SHORE basis [1,2]_.
This implementation is a modification of SHORE presented in [1]_.
The modification was made to obtain the same ordering of the basis
presented in [2,3]_.
The main idea is to model the diffusion signal as a linear
combination of continuous functions \(\phi_i\),
..math::
:nowrap:
begin{equation}
S(mathbf{q})= sum_{i=0}^I c_{i} phi_{i}(mathbf{q}).
end{equation}
where \(\mathbf{q}\) is the wave vector which corresponds to different
gradient directions.
From the \(c_i\) coefficients, there exists an analytical formula to
estimate the ODF.
Parameters
———-
gtab : GradientTable,
gradient directions and bvalues container class
radial_order : unsigned int,
an even integer that represent the order of the basis
zeta : unsigned int,
scale factor
lambdaN : float,
radial regularisation constant
lambdaL : float,
angular regularisation constant
tau : float,
diffusion time. By default the value that makes q equal to the
square root of the b-value.
constrain_e0 : bool,
Constrain the optimization such that E(0) = 1.
positive_constraint : bool,
Constrain the propagator to be positive.
pos_grid : int,
Grid that define the points of the EAP in which we want to enforce
positivity.
pos_radius : float,
Radius of the grid of the EAP in which enforce positivity in
millimeters. By default 20e-03 mm.
cvxpy_solver : str, optional
cvxpy solver name. Optionally optimize the positivity constraint
with a particular cvxpy solver. See https://www.cvxpy.org/ for
details.
Default: None (cvxpy chooses its own solver)
References
———-
.. [1] Merlet S. et al., “Continuous diffusion signal, EAP and
ODF estimation via Compressive Sensing in diffusion MRI”, Medical
Image Analysis, 2013.
.. [2] Cheng J. et al., “Theoretical Analysis and Practical Insights
on EAP Estimation via a Unified HARDI Framework”, MICCAI workshop on
Computational Diffusion MRI, 2011.
.. [3] Ozarslan E. et al., “Mean apparent propagator (MAP) MRI: A novel
diffusion imaging method for mapping tissue microstructure”,
NeuroImage, 2013.
Examples
——–
In this example, where the data, gradient table and sphere tessellation
used for reconstruction are provided, we model the diffusion signal
with respect to the SHORE basis and compute the real and analytical
ODF.
>>> import warnings
>>> from dipy.data import get_isbi2013_2shell_gtab, default_sphere
>>> from dipy.sims.voxel import sticks_and_ball
>>> from dipy.reconst.shm import descoteaux07_legacy_msg
>>> from dipy.reconst.shore import ShoreModel
>>> gtab = get_isbi2013_2shell_gtab()
>>> data, golden_directions = sticks_and_ball(
… gtab, d=0.0015, S0=1., angles=[(0, 0), (90, 0)],
… fractions=[50, 50], snr=None)
…
>>> radial_order = 4
>>> zeta = 700
>>> asm = ShoreModel(gtab, radial_order=radial_order, zeta=zeta,
… lambdaN=1e-8, lambdaL=1e-8)
>>> with warnings.catch_warnings():
… warnings.filterwarnings(
… “ignore”, message=descoteaux07_legacy_msg,
… category=PendingDeprecationWarning)
… asmfit = asm.fit(data)
… odf = asmfit.odf(default_sphere)
Calculates the analytical mean squared displacement (MSD) [1]_
..math::
:nowrap:
begin{equation}
MSD:{DSI}=int_{-infty}^{infty}int_{-infty}^{infty}
int_{-infty}^{infty} P(hat{mathbf{r}}) cdot
hat{mathbf{r}}^{2} dr_x dr_y dr_z
end{equation}
where \(\hat{\mathbf{r}}\) is a point in the 3D propagator space (see Wu
et al. [1]_).
References
———-
.. [1] Wu Y. et al., “Hybrid diffusion imaging”, NeuroImage, vol 36,
p. 617-629, 2007.
Diffusion propagator on a given set of real points.
if the array r_points is non writeable, then intermediate
results are cached for faster recalculation
Applies the analytical FFT on \(S\) to generate the diffusion
propagator. This is calculated on a discrete 3D grid in order to
obtain an EAP similar to that which is obtained with DSI.
Parameters
———-
gridsize : unsigned int
dimension of the propagator grid
radius_max : float
maximal radius in which to compute the propagator
Returns
——-
eap : ndarray
the ensemble average propagator in the 3D grid
Compute the SHORE matrix for modified Merlet’s 3D-SHORE [1]_
..math::
:nowrap:
begin{equation}
textbf{E}(qtextbf{u})=sum_{l=0, even}^{N_{max}}
sum_{n=l}^{(N_{max}+l)/2}
sum_{m=-l}^l c_{nlm}
phi_{nlm}(qtextbf{u})
end{equation}
where \(\phi_{nlm}\) is
..math::
:nowrap:
begin{equation}
phi_{nlm}^{SHORE}(qtextbf{u})=Biggl[dfrac{2(n-l)!}
{zeta^{3/2} Gamma(n+3/2)} Biggr]^{1/2}
Biggl(dfrac{q^2}{zeta}Biggr)^{l/2}
expBiggl(dfrac{-q^2}{2zeta}Biggr)
L^{l+1/2}_{n-l} Biggl(dfrac{q^2}{zeta}Biggr)
Y_l^m(textbf{u}).
end{equation}
Parameters
———-
radial_order : unsigned int,
an even integer that represent the order of the basis
zeta : unsigned int,
scale factor
gtab : GradientTable,
gradient directions and bvalues container class
tau : float,
diffusion time. By default the value that makes q=sqrt(b).
References
———-
.. [1] Merlet S. et al., “Continuous diffusion signal, EAP and
ODF estimation via Compressive Sensing in diffusion MRI”, Medical
Image Analysis, 2013.
Given the basis order and the index, return the shore indices n, l, m
for modified Merlet’s 3D-SHORE
..math::
:nowrap:
begin{equation}
textbf{E}(qtextbf{u})=sum_{l=0, even}^{N_{max}}
sum_{n=l}^{(N_{max}+l)/2}
sum_{m=-l}^l c_{nlm}
phi_{nlm}(qtextbf{u})
end{equation}
where \(\phi_{nlm}\) is
..math::
:nowrap:
begin{equation}
phi_{nlm}^{SHORE}(qtextbf{u})=Biggl[dfrac{2(n-l)!}
{zeta^{3/2} Gamma(n+3/2)} Biggr]^{1/2}
Biggl(dfrac{q^2}{zeta}Biggr)^{l/2}
expBiggl(dfrac{-q^2}{2zeta}Biggr)
L^{l+1/2}_{n-l} Biggl(dfrac{q^2}{zeta}Biggr)
Y_l^m(textbf{u}).
end{equation}
Parameters
———-
radial_order : unsigned int
an even integer that represent the maximal order of the basis
index : unsigned int
index of the coefficients, start from 0
Returns
——-
n : unsigned int
the index n of the modified shore basis
l : unsigned int
the index l of the modified shore basis
m : unsigned int
the index m of the modified shore basis