reconst

Module: reconst.base

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).

ReconstModel(gtab)

Abstract class for signal reconstruction models

ReconstFit(model, data)

Abstract class which holds the fit result of ReconstModel

Module: reconst.benchmarks

Module: reconst.benchmarks.bench_bounding_box

Benchmarks for bounding_box

Run all benchmarks with:

import dipy.reconst as dire
dire.bench()

With Pytest, Run this benchmark with:

pytest -svv -c bench.ini /path/to/bench_bounding_box.py

bench_bounding_box()

Module: reconst.benchmarks.bench_csd

num_grad(gtab)

bench_csdeconv([center, width])

Module: reconst.benchmarks.bench_peaks

Benchmarks for peak finding

Run all benchmarks with:

import dipy.reconst as dire
dire.bench()

With Pytest, Run this benchmark with:

pytest -svv -c bench.ini /path/to/bench_peaks.py

bench_local_maxima()

Module: reconst.benchmarks.bench_squash

Benchmarks for fast squashing

Run all benchmarks with:

import dipy.reconst as dire
dire.bench()

With Pytest, Run this benchmark with:

pytest -svv -c bench.ini /path/to/bench_squash.py

old_squash(arr[, mask, fill])

Try and make a standard array from an object array

bench_quick_squash()

Module: reconst.benchmarks.bench_vec_val_sum

Benchmarks for vec / val summation routine

Run benchmarks with:

import dipy.reconst as dire
dire.bench()

With Pytest, Run this benchmark with:

pytest -svv -c bench.ini /path/to/bench_vec_val_sum.py

bench_vec_val_vect()

Module: reconst.cache

Cache()

Cache values based on a key object (such as a sphere or gradient table).

Module: reconst.cross_validation

Cross-validation analysis of diffusion models.

coeff_of_determination(data, model[, axis])

Calculate the coefficient of determination for a model prediction,

kfold_xval(model, data, folds, *model_args, ...)

Perform k-fold cross-validation.

Module: reconst.csdeconv

AxSymShResponse(S0, dwi_response[, bvalue])

A simple wrapper for response functions represented using only axially symmetric, even spherical harmonic functions (ie, m == 0 and n even).

ConstrainedSphericalDeconvModel(gtab, response)

ConstrainedSDTModel(gtab, ratio[, ...])

auto_response(gtab, data[, roi_center, ...])

Automatic estimation of ssst response function using FA.

response_from_mask(gtab, data, mask)

Computation of single-shell single-tissue (ssst) response

estimate_response(gtab, evals, S0)

Estimate single fiber response function

forward_sdt_deconv_mat(ratio, n[, r2_term])

Build forward sharpening deconvolution transform (SDT) matrix Parameters ---------- ratio : float ratio = \(\frac{\lambda_2}{\lambda_1}\) of the single fiber response function n : ndarray (N,) The degree of spherical harmonic function associated with each row of the deconvolution matrix.

csdeconv(dwsignal, X, B_reg[, tau, ...])

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_deconv(odf_sh, R, B_reg[, lambda_, tau, ...])

ODF constrained-regularized spherical deconvolution using the Sharpening Deconvolution Transform (SDT) [1]_, [2]_. Parameters ---------- odf_sh : ndarray ((sh_order + 1)*(sh_order + 2)/2,) ndarray of SH coefficients for the ODF spherical function to be deconvolved R : ndarray ((sh_order + 1)(sh_order + 2)/2, (sh_order + 1)(sh_order + 2)/2) SDT matrix in SH basis B_reg : ndarray ((sh_order + 1)(sh_order + 2)/2, (sh_order + 1)(sh_order + 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 + 1)(sh_order + 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. .

odf_sh_to_sharp(odfs_sh, sphere[, basis, ...])

Sharpen odfs using the sharpening deconvolution transform [2]_ This function can be used to sharpen any smooth ODF spherical function.

mask_for_response_ssst(gtab, data[, ...])

Computation of mask for single-shell single-tissue (ssst) response

response_from_mask_ssst(gtab, data, mask)

Computation of single-shell single-tissue (ssst) response

auto_response_ssst(gtab, data[, roi_center, ...])

Automatic estimation of single-shell single-tissue (ssst) response

recursive_response(gtab, data[, mask, ...])

Recursive calibration of response function using peak threshold

fa_trace_to_lambdas([fa, trace])

Module: reconst.dki

Classes and functions for fitting the diffusion kurtosis model

DiffusionKurtosisModel(gtab[, fit_method])

Class for the Diffusion Kurtosis Model

DiffusionKurtosisFit(model, model_params)

Class for fitting the Diffusion Kurtosis Model

carlson_rf(x, y, z[, errtol])

Compute the Carlson's incomplete elliptic integral of the first kind

carlson_rd(x, y, z[, errtol])

Compute the Carlson's incomplete elliptic integral of the second kind

directional_diffusion(dt, V[, min_diffusivity])

Calculate the apparent diffusion coefficient (adc) in each direction of a sphere for a single voxel [1]_

directional_diffusion_variance(kt, V[, ...])

Calculate the apparent diffusion variance (adv) in each direction of a sphere for a single voxel [1]_

directional_kurtosis(dt, md, kt, V[, ...])

Calculate the apparent kurtosis coefficient (akc) in each direction of a sphere for a single voxel [1]_

apparent_kurtosis_coef(dki_params, sphere[, ...])

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.

mean_kurtosis(dki_params[, min_kurtosis, ...])

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.

radial_kurtosis(dki_params[, min_kurtosis, ...])

Compute radial kurtosis (RK) of a diffusion kurtosis tensor [1]_, [2]_

axial_kurtosis(dki_params[, min_kurtosis, ...])

Compute axial kurtosis (AK) from the kurtosis tensor [1]_, [2]_

kurtosis_maximum(dki_params[, sphere, gtol, ...])

Compute kurtosis maximum value

mean_kurtosis_tensor(dki_params[, ...])

Compute mean of the kurtosis tensor (MKT) [1]_

kurtosis_fractional_anisotropy(dki_params)

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.

dki_prediction(dki_params, gtab[, S0])

Predict a signal given diffusion kurtosis imaging parameters

params_to_dki_params(result[, min_diffusivity])

ls_fit_dki(design_matrix, data, ...[, ...])

Compute the diffusion and kurtosis tensors using an ordinary or weighted linear least squares approach [1]_

cls_fit_dki(design_matrix, data, ...[, ...])

Compute the diffusion and kurtosis tensors using a constrained ordinary or weighted linear least squares approach [1]_

Wrotate(kt, Basis)

Rotate a kurtosis tensor from the standard Cartesian coordinate system to another coordinate system basis

Wrotate_element(kt, indi, indj, indk, indl, B)

Compute the the specified index element of a kurtosis tensor rotated to the coordinate system basis B

Wcons(k_elements)

Construct the full 4D kurtosis tensors from its 15 independent elements

split_dki_param(dki_params)

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

Module: reconst.dki_micro

Classes and functions for fitting the DKI-based microstructural model

KurtosisMicrostructureModel(gtab[, fit_method])

Class for the Diffusion Kurtosis Microstructural Model

KurtosisMicrostructuralFit(model, model_params)

Class for fitting the Diffusion Kurtosis Microstructural Model

axonal_water_fraction(dki_params[, sphere, ...])

Computes the axonal water fraction from DKI [1]_.

diffusion_components(dki_params[, sphere, ...])

Extracts the restricted and hindered diffusion tensors of well aligned fibers from diffusion kurtosis imaging parameters [1]_.

dkimicro_prediction(params, gtab[, S0])

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. .

tortuosity(hindered_ad, hindered_rd)

Computes the tortuosity of the hindered diffusion compartment given its axial and radial diffusivities

Module: reconst.dsi

DiffusionSpectrumModel(gtab[, qgrid_size, ...])

DiffusionSpectrumFit(model, data)

DiffusionSpectrumDeconvModel(gtab[, ...])

DiffusionSpectrumDeconvFit(model, data)

create_qspace(gtab, origin)

create the 3D grid which holds the signal values (q-space)

create_qtable(gtab, origin)

create a normalized version of gradients

hanning_filter(gtab, filter_width, origin)

create a hanning window

pdf_interp_coords(sphere, rradius, origin)

Precompute coordinates for ODF calculation from the PDF

pdf_odf(Pr, rradius, interp_coords)

Calculates the real ODF from the diffusion propagator(PDF) Pr

half_to_full_qspace(data, gtab)

Half to full Cartesian grid mapping

project_hemisph_bvecs(gtab)

Project any near identical bvecs to the other hemisphere

threshold_propagator(P[, estimated_snr])

Applies hard threshold on the propagator to remove background noise for the deconvolution.

gen_PSF(qgrid_sampling, siz_x, siz_y, siz_z)

Generate a PSF for DSI Deconvolution by taking the ifft of the binary q-space sampling mask and truncating it to keep only the center.

LR_deconv(prop, psf[, numit, acc_factor])

Perform Lucy-Richardson deconvolution algorithm on a 3D array.

Module: reconst.dti

Classes and functions for fitting tensors

TensorModel(gtab[, fit_method, return_S0_hat])

Diffusion Tensor

TensorFit(model, model_params[, model_S0])

fractional_anisotropy(evals[, axis])

Return Fractional anisotropy (FA) of a diffusion tensor.

geodesic_anisotropy(evals[, axis])

Geodesic anisotropy (GA) of a diffusion tensor.

mean_diffusivity(evals[, axis])

Mean Diffusivity (MD) of a diffusion tensor.

axial_diffusivity(evals[, axis])

Axial Diffusivity (AD) of a diffusion tensor.

radial_diffusivity(evals[, axis])

Radial Diffusivity (RD) of a diffusion tensor.

trace(evals[, axis])

Trace of a diffusion tensor.

color_fa(fa, evecs)

Color fractional anisotropy of diffusion tensor

determinant(q_form)

The determinant of a tensor, given in quadratic form

isotropic(q_form)

Calculate the isotropic part of the tensor [1]_.

deviatoric(q_form)

Calculate the deviatoric (anisotropic) part of the tensor [1]_.

norm(q_form)

Calculate the Frobenius norm of a tensor quadratic form

mode(q_form)

Mode (MO) of a diffusion tensor [1]_.

linearity(evals[, axis])

The linearity of the tensor [1]_

planarity(evals[, axis])

The planarity of the tensor [1]_

sphericity(evals[, axis])

The sphericity of the tensor [1]_

apparent_diffusion_coef(q_form, sphere)

Calculate the apparent diffusion coefficient (ADC) in each direction of a sphere.

tensor_prediction(dti_params, gtab, S0)

Predict a signal given tensor parameters.

iter_fit_tensor([step])

Wrap a fit_tensor func and iterate over chunks of data with given length

wls_fit_tensor(design_matrix, data[, ...])

Computes weighted least squares (WLS) fit to calculate self-diffusion tensor using a linear regression model [1]_.

ols_fit_tensor(design_matrix, data[, ...])

Computes ordinary least squares (OLS) fit to calculate self-diffusion tensor using a linear regression model [1]_.

nlls_fit_tensor(design_matrix, data[, ...])

Fit the cumulant expansion params (e.g.

restore_fit_tensor(design_matrix, data[, ...])

Use the RESTORE algorithm [1]_ to calculate a robust tensor fit

_lt_indices

ndarray(shape, dtype=float, buffer=None, offset=0,

from_lower_triangular(D)

Returns a tensor given the six unique tensor elements

_lt_rows

ndarray(shape, dtype=float, buffer=None, offset=0,

_lt_cols

ndarray(shape, dtype=float, buffer=None, offset=0,

lower_triangular(tensor[, b0])

Returns the six lower triangular values of the tensor ordered as (Dxx, Dxy, Dyy, Dxz, Dyz, Dzz) and a dummy variable if b0 is not None.

decompose_tensor(tensor[, min_diffusivity])

Returns eigenvalues and eigenvectors given a diffusion tensor

design_matrix(gtab[, dtype])

Constructs design matrix for DTI weighted least squares or least squares fitting.

quantize_evecs(evecs[, odf_vertices])

Find the closest orientation of an evenly distributed sphere

eig_from_lo_tri(data[, min_diffusivity])

Calculates tensor eigenvalues/eigenvectors from an array containing the lower diagonal form of the six unique tensor elements.

Module: reconst.forecast

ForecastModel(gtab[, sh_order, lambda_lb, ...])

Fiber ORientation Estimated using Continuous Axially Symmetric Tensors (FORECAST) [1,2,3]_.

ForecastFit(model, data, sh_coef, d_par, d_perp)

find_signal_means(b_unique, data_norm, ...)

Calculate the mean signal for each shell.

forecast_error_func(x, b_unique, E)

Calculates the difference between the mean signal calculated using the parameter vector x and the average signal E using FORECAST and SMT

psi_l(l, b)

forecast_matrix(sh_order, d_par, d_perp, bvals)

Compute the FORECAST radial matrix

rho_matrix(sh_order, vecs)

Compute the SH matrix \(\rho\)

lb_forecast(sh_order)

Returns the Laplace-Beltrami regularization matrix for FORECAST

Module: reconst.fwdti

Classes and functions for fitting tensors without free water contamination

FreeWaterTensorModel(gtab[, fit_method])

Class for the Free Water Elimination Diffusion Tensor Model

FreeWaterTensorFit(model, model_params)

Class for fitting the Free Water Tensor Model

fwdti_prediction(params, gtab[, S0, Diso])

Signal prediction given the free water DTI model parameters.

wls_iter(design_matrix, sig, S0[, Diso, ...])

Applies weighted linear least squares fit of the water free elimination model to single voxel signals.

wls_fit_tensor(gtab, data[, Diso, mask, ...])

Computes weighted least squares (WLS) fit to calculate self-diffusion tensor using a linear regression model [1]_.

nls_iter(design_matrix, sig, S0[, Diso, ...])

Applies non linear least squares fit of the water free elimination model to single voxel signals.

nls_fit_tensor(gtab, data[, mask, Diso, ...])

Fit the water elimination tensor model using the non-linear least-squares.

lower_triangular_to_cholesky(tensor_elements)

Performs Cholesky decomposition of the diffusion tensor

cholesky_to_lower_triangular(R)

Convert Cholesky decomposition elements to the diffusion tensor elements

Module: reconst.gqi

Classes and functions for generalized q-sampling

GeneralizedQSamplingModel(gtab[, method, ...])

GeneralizedQSamplingFit(model, data)

normalize_qa(qa[, max_qa])

Normalize quantitative anisotropy.

squared_radial_component(x[, tol])

Part of the GQI2 integral

npa(self, odf[, width])

non-parametric anisotropy

equatorial_zone_vertices(vertices, pole[, width])

finds the 'vertices' in the equatorial zone conjugate to 'pole' with width half 'width' degrees

polar_zone_vertices(vertices, pole[, width])

finds the 'vertices' in the equatorial band around the 'pole' of radius 'width' degrees

upper_hemi_map(v)

maps a 3-vector into the z-upper hemisphere

equatorial_maximum(vertices, odf, pole, width)

patch_vertices(vertices, pole, width)

find 'vertices' within the cone of 'width' degrees around 'pole'

patch_maximum(vertices, odf, pole, width)

odf_sum(odf)

patch_sum(vertices, odf, pole, width)

triple_odf_maxima(vertices, odf, width)

Module: reconst.ivim

Classes and functions for fitting ivim model

IvimModelTRR(gtab[, split_b_D, split_b_S0, ...])

Ivim model

IvimModelVP(gtab[, bounds, maxiter, xtol])

IvimFit(model, model_params)

ivim_prediction(params, gtab)

The Intravoxel incoherent motion (IVIM) model function.

f_D_star_prediction(params, gtab, S0, D)

Function used to predict IVIM signal when S0 and D are known by considering f and D_star as the unknown parameters.

f_D_star_error(params, gtab, signal, S0, D)

Error function used to fit f and D_star keeping S0 and D fixed

ivim_model_selector(gtab[, fit_method])

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.

Module: reconst.mapmri

MapmriModel(gtab[, radial_order, ...])

Mean Apparent Propagator MRI (MAPMRI) [1]_ of the diffusion signal.

MapmriFit(model, mapmri_coef, mu, R, lopt[, ...])

isotropic_scale_factor(mu_squared)

Estimated isotropic scaling factor _[1] Eq.

mapmri_index_matrix(radial_order)

Calculates the indices for the MAPMRI [1]_ basis in x, y and z.

b_mat(index_matrix)

Calculates the B coefficients from [1]_ Eq.

b_mat_isotropic(index_matrix)

Calculates the isotropic B coefficients from [1]_ Fig 8.

mapmri_phi_1d(n, q, mu)

One dimensional MAPMRI basis function from [1]_ Eq.

mapmri_phi_matrix(radial_order, mu, q_gradients)

Compute the MAPMRI phi matrix for the signal [1]_ eq.

mapmri_psi_1d(n, x, mu)

One dimensional MAPMRI propagator basis function from [1]_ Eq.

mapmri_psi_matrix(radial_order, mu, rgrad)

Compute the MAPMRI psi matrix for the propagator [1]_ eq.

mapmri_odf_matrix(radial_order, mu, s, vertices)

Compute the MAPMRI ODF matrix [1]_ Eq.

mapmri_isotropic_phi_matrix(radial_order, mu, q)

Three dimensional isotropic MAPMRI signal basis function from [1]_ Eq.

mapmri_isotropic_radial_signal_basis(j, l, ...)

Radial part of the isotropic 1D-SHORE signal basis [1]_ eq.

mapmri_isotropic_M_mu_independent(...)

Computed the mu independent part of the signal design matrix.

mapmri_isotropic_M_mu_dependent(...)

Computed the mu dependent part of the signal design matrix.

mapmri_isotropic_psi_matrix(radial_order, ...)

Three dimensional isotropic MAPMRI propagator basis function from [1]_ Eq.

mapmri_isotropic_radial_pdf_basis(j, l, mu, r)

Radial part of the isotropic 1D-SHORE propagator basis [1]_ eq.

mapmri_isotropic_K_mu_independent(...)

Computes mu independent part of K.

mapmri_isotropic_K_mu_dependent(...)

Computes mu dependent part of M.

binomialfloat(n, k)

Custom Binomial function

mapmri_isotropic_odf_matrix(radial_order, ...)

Compute the isotropic MAPMRI ODF matrix [1]_ Eq.

mapmri_isotropic_odf_sh_matrix(radial_order, ...)

Compute the isotropic MAPMRI ODF matrix [1]_ Eq.

mapmri_isotropic_laplacian_reg_matrix(...)

Computes the Laplacian regularization matrix for MAP-MRI's isotropic implementation [1]_ eq.

mapmri_isotropic_laplacian_reg_matrix_from_index_matrix(...)

Computes the Laplacian regularization matrix for MAP-MRI's isotropic implementation [1]_ eq.

mapmri_isotropic_index_matrix(radial_order)

Calculates the indices for the isotropic MAPMRI basis [1]_ Fig 8.

create_rspace(gridsize, radius_max)

Create the real space table, that contains the points in which to compute the pdf.

delta(n, m)

map_laplace_u(n, m)

S(n, m) static matrix for Laplacian regularization [1]_ eq.

map_laplace_t(n, m)

L(m, n) static matrix for Laplacian regularization [1]_ eq.

map_laplace_s(n, m)

R(m,n) static matrix for Laplacian regularization [1]_ eq.

mapmri_STU_reg_matrices(radial_order)

Generate the static portions of the Laplacian regularization matrix according to [1]_ eq.

mapmri_laplacian_reg_matrix(ind_mat, mu, ...)

Put the Laplacian regularization matrix together [1]_ eq.

generalized_crossvalidation_array(data, M, LR)

Generalized Cross Validation Function [1]_ eq.

generalized_crossvalidation(data, M, LR[, ...])

Generalized Cross Validation Function [1]_ eq.

gcv_cost_function(weight, args)

The GCV cost function that is iterated [4].

Module: reconst.mcsd

MultiShellResponse(response, sh_order, shells)

MultiShellDeconvModel(gtab, response[, ...])

MSDeconvFit(model, coeff, mask)

QpFitter(X, reg)

multi_tissue_basis(gtab, sh_order, iso_comp)

Builds a basis for multi-shell multi-tissue CSD model.

solve_qp(P, Q, G, H)

Helper function to set up and solve the Quadratic Program (QP) in CVXPY.

multi_shell_fiber_response(sh_order, bvals, ...)

Fiber response function estimation for multi-shell data.

mask_for_response_msmt(gtab, data[, ...])

Computation of masks for multi-shell multi-tissue (msmt) response

response_from_mask_msmt(gtab, data, mask_wm, ...)

Computation of multi-shell multi-tissue (msmt) response

auto_response_msmt(gtab, data[, tol, ...])

Automatic estimation of multi-shell multi-tissue (msmt) response

Module: reconst.msdki

Classes and functions for fitting the mean signal diffusion kurtosis model

MeanDiffusionKurtosisModel(gtab[, bmag, ...])

Mean signal Diffusion Kurtosis Model

MeanDiffusionKurtosisFit(model, model_params)

mean_signal_bvalue(data, gtab[, bmag])

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.

msk_from_awf(f)

Computes mean signal kurtosis from axonal water fraction estimates of the SMT2 model

awf_from_msk(msk[, mask])

Computes the axonal water fraction from the mean signal kurtosis assuming the 2-compartmental spherical mean technique model [1]_, [2]_

msdki_prediction(msdki_params, gtab[, S0])

Predict the mean signal given the parameters of the mean signal DKI, an GradientTable object and S0 signal.

wls_fit_msdki(design_matrix, msignal, ng[, ...])

Fits the mean signal diffusion kurtosis imaging based on a weighted least square solution [1]_.

design_matrix(ubvals)

Constructs design matrix for the mean signal diffusion kurtosis model

Module: reconst.multi_voxel

Tools to easily make multi voxel models

MultiVoxelFit(model, fit_array, mask)

Holds an array of fits and allows access to their attributes and methods

CallableArray

An array which can be called like a function

multi_voxel_fit(single_voxel_fit)

Method decorator to turn a single voxel model fit definition into a multi voxel model fit definition

Module: reconst.odf

OdfModel(gtab)

An abstract class to be sub-classed by specific odf models

OdfFit(model, data)

gfa(samples)

The general fractional anisotropy of a function evaluated on the unit sphere Parameters ---------- samples : ndarray Values of data on the unit sphere.

minmax_normalize(samples[, out])

Min-max normalization of a function evaluated on the unit sphere

Module: reconst.qtdmri

QtdmriModel(gtab[, radial_order, ...])

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\).

QtdmriFit(model, qtdmri_coef, us, ut, ...)

qtdmri_to_mapmri_matrix(radial_order, ...)

Generates the matrix that maps the qtdmri coefficients to MAP-MRI coefficients.

qtdmri_isotropic_to_mapmri_matrix(...)

Generates the matrix that maps the spherical qtdmri coefficients to MAP-MRI coefficients.

qtdmri_temporal_normalization(ut)

Normalization factor for the temporal basis

qtdmri_mapmri_normalization(mu)

Normalization factor for Cartesian MAP-MRI basis.

qtdmri_mapmri_isotropic_normalization(j, l, u0)

Normalization factor for Spherical MAP-MRI basis.

qtdmri_signal_matrix_(radial_order, ...[, ...])

Function to generate the qtdmri signal basis.

qtdmri_signal_matrix(radial_order, ...)

Constructs the design matrix as a product of 3 separated radial, angular and temporal design matrices.

qtdmri_eap_matrix(radial_order, time_order, ...)

Constructs the design matrix as a product of 3 separated radial, angular and temporal design matrices.

qtdmri_isotropic_signal_matrix_(...[, ...])

qtdmri_isotropic_signal_matrix(radial_order, ...)

qtdmri_eap_matrix_(radial_order, time_order, ...)

qtdmri_isotropic_eap_matrix_(radial_order, ...)

qtdmri_isotropic_eap_matrix(radial_order, ...)

Constructs the design matrix as a product of 3 separated radial, angular and temporal design matrices.

radial_basis_opt(j, l, us, q)

Spatial basis dependent on spatial scaling factor us

angular_basis_opt(l, m, q, theta, phi)

Angular basis independent of spatial scaling factor us.

radial_basis_EAP_opt(j, l, us, r)

angular_basis_EAP_opt(j, l, m, r, theta, phi)

temporal_basis(o, ut, tau)

Temporal basis dependent on temporal scaling factor ut

qtdmri_index_matrix(radial_order, time_order)

Computes the SHORE basis order indices according to [1].

qtdmri_isotropic_index_matrix(radial_order, ...)

Computes the SHORE basis order indices according to [1].

qtdmri_laplacian_reg_matrix(ind_mat, us, ut)

Computes the cartesian qt-dMRI Laplacian regularization matrix.

qtdmri_isotropic_laplacian_reg_matrix(...[, ...])

Computes the spherical qt-dMRI Laplacian regularization matrix.

part23_reg_matrix_q(ind_mat, U_mat, T_mat, us)

Partial cartesian spatial Laplacian regularization matrix following second line of Eq.

part23_iso_reg_matrix_q(ind_mat, us)

Partial spherical spatial Laplacian regularization matrix following the equation below Eq.

part4_reg_matrix_q(ind_mat, U_mat, us)

Partial cartesian spatial Laplacian regularization matrix following equation Eq.

part4_iso_reg_matrix_q(ind_mat, us)

Partial spherical spatial Laplacian regularization matrix following the equation below Eq.

part1_reg_matrix_tau(ind_mat, ut)

Partial temporal Laplacian regularization matrix following Appendix B in [1].

part23_reg_matrix_tau(ind_mat, ut)

Partial temporal Laplacian regularization matrix following Appendix B in [1].

part4_reg_matrix_tau(ind_mat, ut)

Partial temporal Laplacian regularization matrix following Appendix B in [1].

H(value)

Step function of H(x)=1 if x>=0 and zero otherwise.

generalized_crossvalidation(data, M, LR[, ...])

Generalized Cross Validation Function [1].

GCV_cost_function(weight, arguments)

Generalized Cross Validation Function that is iterated [1].

qtdmri_isotropic_scaling(data, q, tau)

Constructs design matrix for fitting an exponential to the diffusion time points.

qtdmri_anisotropic_scaling(data, q, bvecs, tau)

Constructs design matrix for fitting an exponential to the diffusion time points.

design_matrix_spatial(bvecs, qvals)

Constructs design matrix for DTI weighted least squares or least squares fitting.

create_rt_space_grid(grid_size_r, ...)

Generates EAP grid (for potential positivity constraint).

qtdmri_number_of_coefficients(radial_order, ...)

Computes the total number of coefficients of the qtdmri basis given a radial and temporal order.

l1_crossvalidation(b0s_mask, E, M[, ...])

cross-validation function to find the optimal weight of alpha for sparsity regularization

elastic_crossvalidation(b0s_mask, E, M, L, lopt)

cross-validation function to find the optimal weight of alpha for sparsity regularization when also Laplacian regularization is used.

visualise_gradient_table_G_Delta_rainbow(gtab)

This function visualizes a q-tau acquisition scheme as a function of gradient strength and pulse separation (big_delta).

Module: reconst.qti

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

QtiModel(gtab[, fit_method, cvxpy_solver])

QtiFit(params)

from_3x3_to_6x1(T)

Convert symmetric 3 x 3 matrices into 6 x 1 vectors.

from_6x1_to_3x3(V)

Convert 6 x 1 vectors into symmetric 3 x 3 matrices.

from_6x6_to_21x1(T)

Convert symmetric 6 x 6 matrices into 21 x 1 vectors.

from_21x1_to_6x6(V)

Convert 21 x 1 vectors into symmetric 6 x 6 matrices.

cvxpy_1x6_to_3x3(V)

Convert a 1 x 6 vector into a symmetric 3 x 3 matrix.

cvxpy_1x21_to_6x6(V)

Convert 1 x 21 vector into a symmetric 6 x 6 matrix.

dtd_covariance(DTD)

Calculate covariance of a diffusion tensor distribution (DTD).

qti_signal(gtab, D, C[, S0])

Generate signals using the covariance tensor signal representation.

design_matrix(btens)

Calculate the design matrix from the b-tensors.

Module: reconst.rumba

Robust and Unbiased Model-BAsed Spherical Deconvolution (RUMBA-SD)

RumbaSDModel(gtab[, wm_response, ...])

RumbaFit(model, model_params)

logger

Instances of the Logger class represent a single logging channel.

rumba_deconv(data, kernel[, n_iter, ...])

Fit fODF and GM/CSF volume fractions for a voxel using RUMBA-SD [1]_.

mbessel_ratio(n, x)

Fast computation of modified Bessel function ratio (first kind).

generate_kernel(gtab, sphere, wm_response, ...)

Generate deconvolution kernel

rumba_deconv_global(data, kernel, mask[, ...])

Fit fODF for all voxels simultaneously using RUMBA-SD.

Module: reconst.sfm

The Sparse Fascicle Model.

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.

IsotropicModel(gtab)

A base-class for the representation of isotropic signals.

IsotropicFit(model, params)

A fit object for representing the isotropic signal as the mean of the diffusion-weighted signal.

ExponentialIsotropicModel(gtab)

Representing the isotropic signal as a fit to an exponential decay function with b-values

ExponentialIsotropicFit(model, params)

A fit to the ExponentialIsotropicModel object, based on data.

SparseFascicleModel(gtab[, sphere, ...])

SparseFascicleFit(model, beta, S0, iso)

sfm_design_matrix(gtab, sphere, response[, mode])

Construct the SFM design matrix

Module: reconst.shm

Tools for using spherical harmonic models to fit diffusion data.

References

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.

SphHarmModel(gtab)

To be subclassed by all models that return a SphHarmFit when fit.

QballBaseModel(gtab, sh_order[, smooth, ...])

To be subclassed by Qball type models.

SphHarmFit(model, shm_coef, mask)

Diffusion data fit to a spherical harmonic model

CsaOdfModel(gtab, sh_order[, smooth, ...])

Implementation of Constant Solid Angle reconstruction method.

OpdtModel(gtab, sh_order[, smooth, ...])

Implementation of Orientation Probability Density Transform reconstruction method.

QballModel(gtab, sh_order[, smooth, ...])

Implementation of regularized Qball reconstruction method.

ResidualBootstrapWrapper(signal_object, B, ...)

Returns a residual bootstrap sample of the signal_object when indexed

forward_sdeconv_mat(r_rh, n)

Build forward spherical deconvolution matrix

sh_to_rh(r_sh, m, n)

Spherical harmonics (SH) to rotational harmonics (RH)

gen_dirac(m, n, theta, phi[, legacy])

Generate Dirac delta function orientated in (theta, phi) on the sphere

spherical_harmonics(m, n, theta, phi[, ...])

Compute spherical harmonics.

real_sph_harm(m, n, theta, phi)

Compute real spherical harmonics.

real_sh_tournier_from_index(m, n, theta, phi)

Compute real spherical harmonics as initially defined in Tournier 2007 [1]_ then updated in MRtrix3 [2]_, where the real harmonic \(Y^m_n\) is defined to be: Real(\(Y^m_n\)) * sqrt(2) if m > 0 \(Y^0_n\) if m = 0 Imag(\(Y^|m|_n\)) * sqrt(2) if m < 0 This may take scalar or array arguments.

real_sh_descoteaux_from_index(m, n, theta, phi)

Compute real spherical harmonics as in Descoteaux et al. 2007 [1]_, where the real harmonic \(Y^m_n\) is defined to be: Imag(\(Y^m_n\)) * sqrt(2) if m > 0 \(Y^0_n\) if m = 0 Real(\(Y^m_n\)) * sqrt(2) if m < 0 This may take scalar or array arguments.

real_sh_tournier(sh_order, theta, phi[, ...])

Compute real spherical harmonics as initially defined in Tournier 2007 [1]_ then updated in MRtrix3 [2]_, where the real harmonic \(Y^m_n\) is defined to be: Real(\(Y^m_n\)) * sqrt(2) if m > 0 \(Y^0_n\) if m = 0 Imag(\(Y^|m|_n\)) * sqrt(2) if m < 0 This may take scalar or array arguments.

real_sh_descoteaux(sh_order, theta, phi[, ...])

Compute real spherical harmonics as in Descoteaux et al. 2007 [1]_, where the real harmonic \(Y^m_n\) is defined to be: Imag(\(Y^m_n\)) * sqrt(2) if m > 0 \(Y^0_n\) if m = 0 Real(\(Y^m_n\)) * sqrt(2) if m < 0 This may take scalar or array arguments.

real_sym_sh_mrtrix(sh_order, theta, phi)

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_n\) is defined to be:: Real(\(Y^m_n\)) if m > 0 \(Y^0_n\) if m = 0 Imag(\(Y^|m|_n\)) if m < 0 This may take scalar or array arguments.

real_sym_sh_basis(sh_order, theta, phi)

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 at points on the sphere given by theta and phi.

sph_harm_ind_list(sh_order[, full_basis])

Returns the degree (m) and order (n) of all the symmetric spherical harmonics of degree less then or equal to sh_order.

order_from_ncoef(ncoef[, full_basis])

Given a number n of coefficients, calculate back the sh_order

smooth_pinv(B, L)

Regularized pseudo-inverse Computes a regularized least square inverse of B Parameters ---------- B : array_like (n, m) Matrix to be inverted L : array_like (n,) 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}\).

lazy_index(index)

Produces a lazy index

normalize_data(data, where_b0[, min_signal, out])

Normalizes the data with respect to the mean b0

hat(B)

Returns the hat matrix for the design matrix B

lcr_matrix(H)

Returns a matrix for computing leveraged, centered residuals from data

bootstrap_data_array(data, H, R[, permute])

Applies the Residual Bootstraps to the data given H and R

bootstrap_data_voxel(data, H, R[, permute])

Like bootstrap_data_array but faster when for a single voxel

sf_to_sh(sf, sphere[, sh_order, basis_type, ...])

Spherical function to spherical harmonics (SH).

sh_to_sf(sh, sphere[, sh_order, basis_type, ...])

Spherical harmonics (SH) to spherical function (SF).

sh_to_sf_matrix(sphere[, sh_order, ...])

Matrix that transforms Spherical harmonics (SH) to spherical function (SF).

calculate_max_order(n_coeffs[, full_basis])

Calculate the maximal harmonic order, given that you know the number of parameters that were estimated.

anisotropic_power(sh_coeffs[, norm_factor, ...])

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_to_full_basis(sh_coeffs)

Given an array of SH coeffs from a symmetric basis, returns the coefficients for the full SH basis by filling odd order SH coefficients with zeros

convert_sh_from_legacy(sh_coeffs, sh_basis)

Convert SH coefficients in legacy SH basis to SH coefficients of the new SH basis for descoteaux07 [1]_ or tournier07 [2]_[3]_ bases.

convert_sh_to_legacy(sh_coeffs, sh_basis[, ...])

Convert SH coefficients in new SH basis to SH coefficients for the legacy SH basis for descoteaux07 [1]_ or tournier07 [2]_[3]_ bases.

Module: reconst.shore

ShoreModel(gtab[, radial_order, zeta, ...])

Simple Harmonic Oscillator based Reconstruction and Estimation (SHORE) [1]_ of the diffusion signal.

ShoreFit(model, shore_coef)

shore_matrix(radial_order, zeta, gtab[, tau])

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}).

shore_matrix_pdf(radial_order, zeta, rtab)

Compute the SHORE propagator matrix [1]_"

shore_matrix_odf(radial_order, zeta, ...)

Compute the SHORE ODF matrix [1]_"

l_shore(radial_order)

Returns the angular regularisation matrix for SHORE basis

n_shore(radial_order)

Returns the angular regularisation matrix for SHORE basis

create_rspace(gridsize, radius_max)

Create the real space table, that contains the points in which

shore_indices(radial_order, index)

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}).

shore_order(n, l, m)

Given the indices (n,l,m) of the basis, return the minimum order for those indices and their index for modified Merlet's 3D-SHORE.

Module: reconst.utils

dki_design_matrix(gtab)

Construct B design matrix for DKI.

ReconstModel

class dipy.reconst.base.ReconstModel(gtab)

Bases: object

Abstract class for signal reconstruction models

__init__(gtab)

Initialization of the abstract class for signal reconstruction models

Parameters

gtab : GradientTable class instance

fit(data, mask=None, **kwargs)

ReconstFit

class dipy.reconst.base.ReconstFit(model, data)

Bases: object

Abstract class which holds the fit result of ReconstModel

For example that could be holding FA or GFA etc.

__init__(model, data)

bench_bounding_box

dipy.reconst.benchmarks.bench_bounding_box.bench_bounding_box()

num_grad

dipy.reconst.benchmarks.bench_csd.num_grad(gtab)

bench_csdeconv

dipy.reconst.benchmarks.bench_csd.bench_csdeconv(center=(50, 40, 40), width=12)

bench_local_maxima

dipy.reconst.benchmarks.bench_peaks.bench_local_maxima()

old_squash

dipy.reconst.benchmarks.bench_squash.old_squash(arr, mask=None, fill=0)

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:

  1. arr is an array of scalars of type T. Returns an array like arr.astype(T)

  2. arr is an array of arrays. All items in arr have the same shape S. Returns an array with shape arr.shape + S.

  3. arr is an array of arrays of different shapes. Returns arr.

  4. Items in arr are not ndarrys or scalars. Returns arr.

Parameters

arrarray, dtype=object

The array to be converted.

maskarray, dtype=bool, optional

Where arr has Nones.

fillnumber, optional

Nones are replaced by fill.

Returns

result : array

Examples

>>> arr = np.empty(3, dtype=object)
>>> arr.fill(2)
>>> old_squash(arr)
array([2, 2, 2])
>>> arr[0] = None
>>> old_squash(arr)
array([0, 2, 2])
>>> arr.fill(np.ones(2))
>>> r = old_squash(arr)
>>> r.shape == (3, 2)
True
>>> r.dtype
dtype('float64')

bench_quick_squash

dipy.reconst.benchmarks.bench_squash.bench_quick_squash()

bench_vec_val_vect

dipy.reconst.benchmarks.bench_vec_val_sum.bench_vec_val_vect()

Cache

class dipy.reconst.cache.Cache

Bases: object

Cache values based on a key object (such as a sphere or gradient table).

Notes

This class is meant to be used as a mix-in:

class MyModel(Model, Cache):
    pass

class MyModelFit(Fit):
    pass

Inside a method on the fit, typical usage would be:

def odf(sphere):
    M = self.model.cache_get('odf_basis_matrix', key=sphere)

    if M is None:
        M = self._compute_basis_matrix(sphere)
        self.model.cache_set('odf_basis_matrix', key=sphere, value=M)
__init__()
cache_clear()

Clear the cache.

cache_get(tag, key, default=None)

Retrieve a value from the cache.

Parameters
tagstr

Description of the cached value.

keyobject

Key object used to look up the cached value.

defaultobject

Value to be returned if no cached entry is found.

Returns
vobject

Value from the cache associated with (tag, key). Returns default if no cached entry is found.

cache_set(tag, key, value)

Store a value in the cache.

Parameters
tagstr

Description of the cached value.

keyobject

Key object used to look up the cached value.

valueobject

Value stored in the cache for each unique combination of (tag, key).

Examples
>>> def compute_expensive_matrix(parameters):
...     # Imagine the following computation is very expensive
...     return (p**2 for p in parameters)
>>> c = Cache()
>>> parameters = (1, 2, 3)
>>> X1 = compute_expensive_matrix(parameters)
>>> c.cache_set('expensive_matrix', parameters, X1)
>>> X2 = c.cache_get('expensive_matrix', parameters)
>>> X1 is X2
True

coeff_of_determination

dipy.reconst.cross_validation.coeff_of_determination(data, model, axis=-1)
Calculate the coefficient of determination for a model prediction,

relative to data.

datandarray

The data

modelndarray

The predictions of a model for this data. Same shape as the data.

axis: int, optional

The axis along which different samples are laid out (default: -1).

CODndarray

The coefficient of determination. This has shape data.shape[:-1]

See: http://en.wikipedia.org/wiki/Coefficient_of_determination

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).

kfold_xval

dipy.reconst.cross_validation.kfold_xval(model, data, folds, *model_args, **model_kwargs)

Perform k-fold cross-validation.

It generate out-of-sample predictions for each measurement.

Parameters

modelModel class instance

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

Notes

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.

References

AxSymShResponse

class dipy.reconst.csdeconv.AxSymShResponse(S0, dwi_response, bvalue=None)

Bases: object

A simple wrapper for response functions represented using only axially symmetric, even spherical harmonic functions (ie, m == 0 and n even).

Parameters

S0float

Signal with no diffusion weighting.

dwi_responsearray

Response function signal as coefficients to axially symmetric, even spherical harmonic.

__init__(S0, dwi_response, bvalue=None)
basis(sphere)

A basis that maps the response coefficients onto a sphere.

on_sphere(sphere)

Evaluates the response function on sphere.

ConstrainedSphericalDeconvModel

class dipy.reconst.csdeconv.ConstrainedSphericalDeconvModel(gtab, response, reg_sphere=None, sh_order=8, lambda_=1, tau=0.1, convergence=50)

Bases: SphHarmModel

__init__(gtab, response, reg_sphere=None, sh_order=8, lambda_=1, tau=0.1, convergence=50)

Constrained Spherical Deconvolution (CSD) [1]_.

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]_.

Parameters

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’.

sh_orderint (optional)

maximal spherical harmonics order. Default: 8

lambda_float (optional)

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.

References

fit(data, mask=None)

Fit method for every voxel in data

predict(sh_coeff, gtab=None, S0=1.0)

Compute a signal prediction given spherical harmonic coefficients for the provided GradientTable class instance.

Parameters

sh_coeffndarray

The spherical harmonic representation of the FOD from which to make the signal prediction.

gtabGradientTable

The gradients for which the signal will be predicted. Uses the model’s gradient table by default.

S0ndarray or float

The non diffusion-weighted signal value.

Returns

pred_signdarray

The predicted signal.

ConstrainedSDTModel

class dipy.reconst.csdeconv.ConstrainedSDTModel(gtab, ratio, reg_sphere=None, sh_order=8, lambda_=1.0, tau=0.1)

Bases: SphHarmModel

__init__(gtab, ratio, reg_sphere=None, sh_order=8, lambda_=1.0, tau=0.1)

Spherical Deconvolution Transform (SDT) [1]_.

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.

Parameters

gtab : GradientTable ratio : float

ratio of the smallest vs the largest eigenvalue of the single prolate tensor response function

reg_sphereSphere

sphere used to build the regularization B matrix

sh_orderint

maximal spherical harmonics order

lambda_float

weight given to the constrained-positivity regularization part of the deconvolution equation

taufloat

threshold (tau *mean(fODF)) controlling the amplitude below which the corresponding fODF is assumed to be zero.

References

fit(data, mask=None)

Fit method for every voxel in data

auto_response

dipy.reconst.csdeconv.auto_response(gtab, data, roi_center=None, roi_radius=10, fa_thr=0.7, fa_callable=None, return_number_of_voxels=None)

Automatic estimation of ssst response function using FA.

dipy.reconst.csdeconv.auto_response is deprecated, Please use dipy.reconst.csdeconv.auto_response_ssst instead

  • deprecated from version: 1.2

  • Raises <class ‘dipy.utils.deprecator.ExpiredDeprecationError’> as of version: 1.4

Parameters

gtab : GradientTable data : ndarray

diffusion data

roi_centerarray-like, (3,)

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

Returns

responsetuple, (2,)

(evals, S0)

ratiofloat

The ratio between smallest versus largest eigenvalue of the response.

Notes

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).

response_from_mask

dipy.reconst.csdeconv.response_from_mask(gtab, data, mask)
Computation of single-shell single-tissue (ssst) response

function from a given mask.

dipy.reconst.csdeconv.response_from_mask is deprecated, Please use dipy.reconst.csdeconv.response_from_mask_ssst instead

  • deprecated from version: 1.2

  • Raises <class ‘dipy.utils.deprecator.ExpiredDeprecationError’> as of version: 1.4

Parameters

gtab : GradientTable data : ndarray

diffusion data

maskndarray

mask from where to compute the response function

Returns

responsetuple, (2,)

(evals, S0)

ratiofloat

The ratio between smallest versus largest eigenvalue of the response.

Notes

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.

References

fiber orientation density function from diffusion-weighted MRI data using spherical deconvolution

estimate_response

dipy.reconst.csdeconv.estimate_response(gtab, evals, S0)

Estimate single fiber response function

Parameters

gtab : GradientTable evals : ndarray S0 : float

non diffusion weighted

Returns

S : estimated signal

forward_sdt_deconv_mat

dipy.reconst.csdeconv.forward_sdt_deconv_mat(ratio, n, r2_term=False)

Build forward sharpening deconvolution transform (SDT) matrix Parameters ———- ratio : float ratio = \(\frac{\lambda_2}{\lambda_1}\) of the single fiber response function n : ndarray (N,) The degree of spherical harmonic function associated with each row of the deconvolution matrix. Only even degrees 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.

csdeconv

dipy.reconst.csdeconv.csdeconv(dwsignal, X, B_reg, tau=0.1, convergence=50, P=None)

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 + 1)*(sh_order + 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_deconv

dipy.reconst.csdeconv.odf_deconv(odf_sh, R, B_reg, lambda_=1.0, tau=0.1, r2_term=False)

ODF constrained-regularized spherical deconvolution using the Sharpening Deconvolution Transform (SDT) [1]_, [2]_. Parameters ———- odf_sh : ndarray ((sh_order + 1)*(sh_order + 2)/2,) ndarray of SH coefficients for the ODF spherical function to be deconvolved R : ndarray ((sh_order + 1)(sh_order + 2)/2, (sh_order + 1)(sh_order + 2)/2) SDT matrix in SH basis B_reg : ndarray ((sh_order + 1)(sh_order + 2)/2, (sh_order + 1)(sh_order + 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 + 1)(sh_order + 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.

odf_sh_to_sharp

dipy.reconst.csdeconv.odf_sh_to_sharp(odfs_sh, sphere, basis=None, ratio=0.2, sh_order=8, lambda_=1.0, tau=0.1, r2_term=False)

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 + 1)*(sh_order + 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 : int maximal SH order 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.

mask_for_response_ssst

dipy.reconst.csdeconv.mask_for_response_ssst(gtab, data, roi_center=None, roi_radii=10, fa_thr=0.7)
Computation of mask for single-shell single-tissue (ssst) response

function using FA.

Parameters

gtab : GradientTable data : ndarray

diffusion data (4D)

roi_centerarray-like, (3,)

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_radiiint or array-like, (3,)

radii of cuboid ROI

fa_thrfloat

FA threshold

Returns

maskndarray

Mask of voxels within the ROI and with FA above the FA threshold.

Notes

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]_).

References

fiber orientation density function from diffusion-weighted MRI data using spherical deconvolution

response_from_mask_ssst

dipy.reconst.csdeconv.response_from_mask_ssst(gtab, data, mask)
Computation of single-shell single-tissue (ssst) response

function from a given mask.

Parameters

gtab : GradientTable data : ndarray

diffusion data

maskndarray

mask from where to compute the response function

Returns

responsetuple, (2,)

(evals, S0)

ratiofloat

The ratio between smallest versus largest eigenvalue of the response.

Notes

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.

References

fiber orientation density function from diffusion-weighted MRI data using spherical deconvolution

auto_response_ssst

dipy.reconst.csdeconv.auto_response_ssst(gtab, data, roi_center=None, roi_radii=10, fa_thr=0.7)
Automatic estimation of single-shell single-tissue (ssst) response

function using FA.

Parameters

gtab : GradientTable data : ndarray

diffusion data

roi_centerarray-like, (3,)

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_radiiint or array-like, (3,)

radii of cuboid ROI

fa_thrfloat

FA threshold

Returns

responsetuple, (2,)

(evals, S0)

ratiofloat

The ratio between smallest versus largest eigenvalue of the response.

Notes

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).

recursive_response

dipy.reconst.csdeconv.recursive_response(gtab, data, mask=None, sh_order=8, peak_thr=0.01, init_fa=0.08, init_trace=0.0021, iter=8, convergence=0.001, parallel=False, num_processes=None, sphere=<dipy.core.sphere.HemiSphere object>)

Recursive calibration of response function using peak threshold

Parameters

gtab : GradientTable data : ndarray

diffusion data

maskndarray, optional

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_orderint, optional

maximal spherical harmonics order. 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.

Returns

responsendarray

response function in SH coefficients

Notes

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].

References

fa_trace_to_lambdas

dipy.reconst.csdeconv.fa_trace_to_lambdas(fa=0.08, trace=0.0021)

DiffusionKurtosisModel

class dipy.reconst.dki.DiffusionKurtosisModel(gtab, fit_method='WLS', *args, **kwargs)

Bases: ReconstModel

Class for the Diffusion Kurtosis Model

__init__(gtab, fit_method='WLS', *args, **kwargs)

Diffusion Kurtosis Tensor Model [1]

Parameters

gtabGradientTable instance

The gradient table for the data set.

fit_methodstr or callable, optional
str be one of the following:

‘OLS’ or ‘ULLS’ for ordinary least squares. ‘WLS’, ‘WLLS’ or ‘UWLLS’ for weighted ordinary least squares.

See dki.ls_fit_dki.

‘CLS’ for LMI constrained ordinary least squares [2]. ‘CWLS’ for LMI constrained weighted least squares [2].

See dki.cls_fit_dki.

callable has to have the signature:

fit_method(design_matrix, data, *args, **kwargs).

Default: “WLS”

args, kwargs :

arguments and key-word arguments passed to the fit_method.

References

fit(data, mask=None)
multi_fit(data, mask=None)

Fit method for every voxel in data

predict(dki_params, S0=1.0)

Predict a signal for this DKI model class instance given parameters

Parameters

dki_paramsndarray (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

S0float or ndarray (optional)

The non diffusion-weighted signal in every voxel, or across all voxels. Default: 1

DiffusionKurtosisFit

class dipy.reconst.dki.DiffusionKurtosisFit(model, model_params)

Bases: TensorFit

Class for fitting the Diffusion Kurtosis Model

__init__(model, model_params)

Initialize a DiffusionKurtosisFit class instance

Since DKI is an extension of DTI, class instance is defined as subclass of the TensorFit from dti.py

Parameters

modelDiffusionKurtosisModel Class instance

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. 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

ak(min_kurtosis=-0.42857142857142855, max_kurtosis=10, analytical=True)

Compute axial kurtosis (AK) of a diffusion kurtosis tensor [1]_

Parameters

min_kurtosisfloat (optional)

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.

Returns

akarray

Calculated AK.

Notes

AK is defined as the directional kurtosis parallel to the fiber’s main direction e1 [1]_, [2]_. You can compute AK using to approaches:

  1. AK is calculated from rotated diffusion kurtosis tensor [2]_, i.e.:

\[AK = \hat{W}_{1111} \frac{(\lambda_{1}+\lambda_{2}+\lambda_{3})^2}{(9 \lambda_{1}^2)}\]
  1. 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.

References

akc(sphere)

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.

property kfa

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

kmax(sphere='repulsion100', gtol=1e-05, mask=None)

Compute the maximum value of a single voxel kurtosis tensor

Parameters

sphereSphere class instance, optional

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

Returns

max_valuefloat

kurtosis tensor maximum value

property kt

Return the 15 independent elements of the kurtosis tensor as an array

mk(min_kurtosis=-0.42857142857142855, max_kurtosis=10, analytical=True)

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

mkt(min_kurtosis=-0.42857142857142855, max_kurtosis=10)

Compute mean of the kurtosis tensor (MKT) [1]_

Parameters

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

Returns

mktarray

Calculated mean kurtosis tensor.

Notes

The MKT is defined as [1]_:

\[MKT \equiv \frac{1}{4\pi} \int d \Omega_{\mathnbf{n}} n_i n_j n_k n_l W_{ijkl}\]

which can be directly computed from the trace of the kurtosis tensor:

\[\]

MKT = frac{1}{5} Tr(mathbf{W}) = frac{1}{5} (W_{1111} + W_{2222} + W_{3333} + 2W_{1122} + 2W_{1133} + 2W_{2233})

References

predict(gtab, S0=1.0)

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.

rk(min_kurtosis=-0.42857142857142855, max_kurtosis=10, analytical=True)

Compute radial kurtosis (RK) of a diffusion kurtosis tensor [1]_

Parameters

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

Returns

rkarray

Calculated RK.

Notes

RK is defined as the average of the directional kurtosis perpendicular to the fiber’s main direction e1 [1]_, [2]_:

\[\]
RK equiv frac{1}{2pi} int dOmega _mathbf{theta}

K(mathbf{theta}) delta (mathbf{theta}cdot mathbf{e}_1)

This equation can be numerically computed by averaging apparent directional kurtosis samples for directions perpendicular to e1.

Otherwise, RK can be calculated from its analytical solution [2]_:

\[K_{\bot} = G_1(\lambda_1,\lambda_2,\lambda_3)\hat{W}_{2222} + G_1(\lambda_1,\lambda_3,\lambda_2)\hat{W}_{3333} + G_2(\lambda_1,\lambda_2,\lambda_3)\hat{W}_{2233}\]

where:

\[G_1(\lambda_1,\lambda_2,\lambda_3)= \frac{(\lambda_1+\lambda_2+\lambda_3)^2}{18\lambda_2(\lambda_2- \lambda_3)} \left (2\lambda_2 + \frac{\lambda_3^2-3\lambda_2\lambda_3}{\sqrt{\lambda_2\lambda_3}} \right)\]

and

\[ G_2(\lambda_1,\lambda_2,\lambda_3)= \frac{(\lambda_1+\lambda_2+\lambda_3)^2}{(\lambda_2-\lambda_3)^2} \left ( \frac{\lambda_2+\lambda_3}{\sqrt{\lambda_2\lambda_3}}- 2\right )\]

References

carlson_rf

dipy.reconst.dki.carlson_rf(x, y, z, errtol=0.0003)

Compute the Carlson’s incomplete elliptic integral of the first kind

Carlson’s incomplete elliptic integral of the first kind is defined as:

\[R_F = \frac{1}{2} \int_{0}^{\infty} \left [(t+x)(t+y)(t+z) \right ] ^{-\frac{1}{2}}dt\]

Parameters

xndarray

First independent variable of the integral.

yndarray

Second independent variable of the integral.

zndarray

Third independent variable of the integral.

errtolfloat

Error tolerance. Integral is computed with relative error less in magnitude than the defined value

Returns

RFndarray

Value of the incomplete first order elliptic integral

Notes

x, y, and z have to be nonnegative and at most one of them is zero.

References

carlson_rd

dipy.reconst.dki.carlson_rd(x, y, z, errtol=0.0001)

Compute the Carlson’s incomplete elliptic integral of the second kind

Carlson’s incomplete elliptic integral of the second kind is defined as:

\[R_D = \frac{3}{2} \int_{0}^{\infty} (t+x)^{-\frac{1}{2}} (t+y)^{-\frac{1}{2}}(t+z) ^{-\frac{3}{2}}\]

Parameters

xndarray

First independent variable of the integral.

yndarray

Second independent variable of the integral.

zndarray

Third independent variable of the integral.

errtolfloat

Error tolerance. Integral is computed with relative error less in magnitude than the defined value

Returns

RDndarray

Value of the incomplete second order elliptic integral

Notes

x, y, and z have to be nonnegative and at most x or y is zero.

directional_diffusion

dipy.reconst.dki.directional_diffusion(dt, V, min_diffusivity=0)

Calculate the apparent diffusion coefficient (adc) in each direction of a sphere for a single voxel [1]_

Parameters

dtarray (6,)

elements of the diffusion tensor of the voxel.

Varray (g, 3)

g directions of a Sphere in Cartesian coordinates

min_diffusivityfloat (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

Returns

adcndarray (g,)

Apparent diffusion coefficient (adc) in all g directions of a sphere for a single voxel.

References

directional_diffusion_variance

dipy.reconst.dki.directional_diffusion_variance(kt, V, min_kurtosis=-0.42857142857142855)

Calculate the apparent diffusion variance (adv) in each direction of a sphere for a single voxel [1]_

Parameters

dtarray (6,)

elements of the diffusion tensor of the voxel.

ktarray (15,)

elements of the kurtosis tensor of the voxel.

Varray (g, 3)

g directions of a Sphere in Cartesian coordinates

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 coefficient (advc) in all g directions of a sphere for a single voxel.

Returns

advndarray (g,)

Apparent diffusion variance (adv) in all g directions of a sphere for a single voxel.

References

directional_kurtosis

dipy.reconst.dki.directional_kurtosis(dt, md, kt, V, min_diffusivity=0, min_kurtosis=-0.42857142857142855, adc=None, adv=None)

Calculate the apparent kurtosis coefficient (akc) in each direction of a sphere for a single voxel [1]_

Parameters

dtarray (6,)

elements of the diffusion tensor of the voxel.

mdfloat

mean diffusivity of the voxel

ktarray (15,)

elements of the kurtosis tensor of the voxel.

Varray (g, 3)

g directions of a Sphere in Cartesian coordinates

min_diffusivityfloat (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_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.

Returns

akcndarray (g,)

Apparent kurtosis coefficient (AKC) in all g directions of a sphere for a single voxel.

References

apparent_kurtosis_coef

dipy.reconst.dki.apparent_kurtosis_coef(dki_params, sphere, min_diffusivity=0, min_kurtosis=-0.42857142857142855)

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

mean_kurtosis

dipy.reconst.dki.mean_kurtosis(dki_params, min_kurtosis=-0.42857142857142855, max_kurtosis=3, analytical=True)

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

radial_kurtosis

dipy.reconst.dki.radial_kurtosis(dki_params, min_kurtosis=-0.42857142857142855, max_kurtosis=10, analytical=True)

Compute radial kurtosis (RK) of a diffusion kurtosis tensor [1]_, [2]_

Parameters

dki_paramsndarray (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_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.

Returns

rkarray

Calculated RK.

Notes

RK is defined as the average of the directional kurtosis perpendicular to the fiber’s main direction e1 [1]_, [2]_:

\[\]
RK equiv frac{1}{2pi} int dOmega _mathbf{theta} K(mathbf{theta})

delta (mathbf{theta}cdot mathbf{e}_1)

This equation can be numerically computed by averaging apparent directional kurtosis samples for directions perpendicular to e1.

Otherwise, RK can be calculated from its analytical solution [2]_:

\[K_{\bot} = G_1(\lambda_1,\lambda_2,\lambda_3)\hat{W}_{2222} + G_1(\lambda_1,\lambda_3,\lambda_2)\hat{W}_{3333} + G_2(\lambda_1,\lambda_2,\lambda_3)\hat{W}_{2233}\]

where:

\[G_1(\lambda_1,\lambda_2,\lambda_3)= \frac{(\lambda_1+\lambda_2+\lambda_3)^2}{18\lambda_2(\lambda_2- \lambda_3)} \left (2\lambda_2 + \frac{\lambda_3^2-3\lambda_2\lambda_3}{\sqrt{\lambda_2\lambda_3}} \right)\]

and

\[G_2(\lambda_1,\lambda_2,\lambda_3)= \frac{(\lambda_1+\lambda_2+\lambda_3)^2}{(\lambda_2-\lambda_3)^2} \left ( \frac{\lambda_2+\lambda_3}{\sqrt{\lambda_2\lambda_3}}-2\right )\]

References

axial_kurtosis

dipy.reconst.dki.axial_kurtosis(dki_params, min_kurtosis=-0.42857142857142855, max_kurtosis=10, analytical=True)

Compute axial kurtosis (AK) from the kurtosis tensor [1]_, [2]_

Parameters

dki_paramsndarray (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_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.

Returns

akarray

Calculated AK.

Notes

AK is defined as the directional kurtosis parallel to the fiber’s main direction e1 [1]_, [2]_. You can compute AK using to approaches:

  1. AK is calculated from rotated diffusion kurtosis tensor [2]_, i.e.:

\[AK = \hat{W}_{1111} \frac{(\lambda_{1}+\lambda_{2}+\lambda_{3})^2}{(9 \lambda_{1}^2)}\]
  1. 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.

References

kurtosis_maximum

dipy.reconst.dki.kurtosis_maximum(dki_params, sphere='repulsion100', gtol=0.01, mask=None)

Compute kurtosis maximum value

Parameters

dki_paramsndarray (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 eingenvalues

  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

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]

Returns

max_valuefloat

kurtosis tensor maximum value

max_dirarray (3,)

Cartesian coordinates of the direction of the maximal kurtosis value

mean_kurtosis_tensor

dipy.reconst.dki.mean_kurtosis_tensor(dki_params, min_kurtosis=-0.42857142857142855, max_kurtosis=10)

Compute mean of the kurtosis tensor (MKT) [1]_

Parameters

dki_paramsndarray (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_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

Returns

mktarray

Calculated mean kurtosis tensor.

Notes

The MKT is defined as [1]_:

\[MKT \equiv \frac{1}{4\pi} \int d \Omega_{\mathnbf{n}} n_i n_j n_k n_l W_{ijkl}\]

which can be directly computed from the trace of the kurtosis tensor:

\[\]

MKT = frac{1}{5} Tr(mathbf{W}) = frac{1}{5} (W_{1111} + W_{2222} + W_{3333} + 2W_{1122} + 2W_{1133} + 2W_{2233})

References

kurtosis_fractional_anisotropy

dipy.reconst.dki.kurtosis_fractional_anisotropy(dki_params)

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

dki_prediction

dipy.reconst.dki.dki_prediction(dki_params, gtab, S0=1.0)

Predict a signal given diffusion kurtosis imaging parameters

dki_paramsndarray (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

gtaba GradientTable class instance

The gradient table for this prediction

S0float or ndarray (optional)

The non diffusion-weighted signal in every voxel, or across all voxels. Default: 1

S(…, N) ndarray

Simulated signal based on the DKI model:

\[S=S_{0}e^{-bD+\]

rac{1}{6}b^{2}D^{2}K}

params_to_dki_params

dipy.reconst.dki.params_to_dki_params(result, min_diffusivity=0)

ls_fit_dki

dipy.reconst.dki.ls_fit_dki(design_matrix, data, inverse_design_matrix, weights=True, min_diffusivity=0)

Compute the diffusion and kurtosis tensors using an ordinary or weighted linear least squares approach [1]_

Parameters

design_matrixarray (g, 22)

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.

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.

Returns

dki_paramsarray (27)

All parameters estimated from the diffusion kurtosis model for all N voxels. Parameters are ordered as follows:

  1. Three diffusion tensor eigenvalues.

  2. Three blocks of three elements, containing the first second and third coordinates of the diffusion tensor eigenvectors.

  3. Fifteen elements of the kurtosis tensor.

References

[1] Veraart, J., Sijbers, J., Sunaert, S., Leemans, A., Jeurissen, B.,

2013. Weighted linear least squares estimation of diffusion MRI parameters: Strengths, limitations, and pitfalls. Magn Reson Med 81, 335-346.

cls_fit_dki

dipy.reconst.dki.cls_fit_dki(design_matrix, data, inverse_design_matrix, sdp, weights=True, min_diffusivity=0, cvxpy_solver=None)

Compute the diffusion and kurtosis tensors using a constrained ordinary or weighted linear least squares approach [1]_

Parameters

design_matrixarray (g, 22)

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.

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 http://www.cvxpy.org/ for details. Default: None (cvxpy chooses its own solver).

Returns

dki_paramsarray (27)

All parameters estimated from the diffusion kurtosis model for all N voxels. Parameters are ordered as follows:

  1. Three diffusion tensor eigenvalues.

  2. Three blocks of three elements, containing the first second and third coordinates of the diffusion tensor eigenvectors.

  3. Fifteen elements of the kurtosis tensor.

References

Wrotate

dipy.reconst.dki.Wrotate(kt, Basis)

Rotate a kurtosis tensor from the standard Cartesian coordinate system to another coordinate system basis

Parameters

kt(15,)

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.

Returns

Wrotarray (m,) or (15,)

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.

Notes

KT elements are assumed to be ordered as follows:

\[\]
begin{matrix} ( & W_{xxxx} & W_{yyyy} & W_{zzzz} & W_{xxxy} & W_{xxxz}

& … \ & W_{xyyy} & W_{yyyz} & W_{xzzz} & W_{yzzz} & W_{xxyy} & … \ & W_{xxzz} & W_{yyzz} & W_{xxyz} & W_{xyyz} & W_{xyzz} & & )end{matrix}

References

[1] Hui ES, Cheung MM, Qi L, Wu EX, 2008. Towards better MR characterization of neural tissues using directional diffusion kurtosis analysis. Neuroimage 42(1): 122-34

Wrotate_element

dipy.reconst.dki.Wrotate_element(kt, indi, indj, indk, indl, B)

Compute the the specified index element of a kurtosis tensor rotated to the coordinate system basis B

Parameters

ktndarray (x, y, z, 15) or (n, 15)

Array containing the 15 independent elements of the kurtosis tensor

indiint

Rotated kurtosis tensor element index i (0 for x, 1 for y, 2 for z)

indjint

Rotated kurtosis tensor element index j (0 for x, 1 for y, 2 for z)

indkint

Rotated kurtosis tensor element index k (0 for x, 1 for y, 2 for z)

indl: int

Rotated kurtosis tensor element index l (0 for x, 1 for y, 2 for z)

B: array (x, y, z, 3, 3) or (n, 15)

Vectors of the basis column-wise oriented

Returns

Wrefloat

rotated kurtosis tensor element of index ind_i, ind_j, ind_k, ind_l

Notes

It is assumed that initial kurtosis tensor elementes are defined on the Cartesian coordinate system.

References

[1] Hui ES, Cheung MM, Qi L, Wu EX, 2008. Towards better MR characterization of neural tissues using directional diffusion kurtosis analysis. Neuroimage 42(1): 122-34

Wcons

dipy.reconst.dki.Wcons(k_elements)

Construct the full 4D kurtosis tensors from its 15 independent elements

Parameters

k_elements(15,)

elements of the kurtosis tensor in the following order:

\[\]
begin{matrix} ( & W_{xxxx} & W_{yyyy} & W_{zzzz} & W_{xxxy} & W_{xxxz}

& … \ & W_{xyyy} & W_{yyyz} & W_{xzzz} & W_{yzzz} & W_{xxyy} & … \ & W_{xxzz} & W_{yyzz} & W_{xxyz} & W_{xyyz} & W_{xyzz} & & )end{matrix}

Returns

Warray(3, 3, 3, 3)

Full 4D kurtosis tensor

split_dki_param

dipy.reconst.dki.split_dki_param(dki_params)

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

Parameters

dki_paramsndarray (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

eigvalsarray (x, y, z, 3) or (n, 3)

Eigenvalues from eigen decomposition of the tensor.

eigvecsarray (x, y, z, 3, 3) or (n, 3, 3)

Associated eigenvectors from eigen decomposition of the tensor. Eigenvectors are columnar (e.g. eigvecs[:,j] is associated with eigvals[j])

ktarray (x, y, z, 15) or (n, 15)

Fifteen elements of the kurtosis tensor

KurtosisMicrostructureModel

class dipy.reconst.dki_micro.KurtosisMicrostructureModel(gtab, fit_method='WLS', *args, **kwargs)

Bases: DiffusionKurtosisModel

Class for the Diffusion Kurtosis Microstructural Model

__init__(gtab, fit_method='WLS', *args, **kwargs)

Initialize a KurtosisMicrostrutureModel class instance [1]_.

Parameters

gtab : GradientTable class instance

fit_methodstr or callable

str can be one of the following: ‘OLS’ or ‘ULLS’ to fit the diffusion tensor and kurtosis tensor using the ordinary linear least squares solution

dki.ols_fit_dki

‘WLS’ or ‘UWLLS’ to fit the diffusion tensor and kurtosis tensor using the ordinary linear least squares solution

dki.wls_fit_dki

callable has to have the signature:

fit_method(design_matrix, data, *args, **kwargs)

args, kwargsarguments and key-word arguments passed to the

fit_method. See dki.ols_fit_dki, dki.wls_fit_dki for details

References

fit(data, mask=None, sphere='repulsion100', gtol=0.01, awf_only=False)

Fit method of the Diffusion Kurtosis Microstructural Model

Parameters

dataarray

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

predict(params, S0=1.0)

Predict a signal for the DKI microstructural model class instance given parameters.

Parameters

paramsndarray (x, y, z, 40) or (n, 40)

All parameters estimated from the diffusion kurtosis microstructural 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

S0float or ndarray (optional)

The non diffusion-weighted signal in every voxel, or across all voxels. Default: 1

Notes

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.

References

KurtosisMicrostructuralFit

class dipy.reconst.dki_micro.KurtosisMicrostructuralFit(model, model_params)

Bases: DiffusionKurtosisFit

Class for fitting the Diffusion Kurtosis Microstructural Model

__init__(model, model_params)

Initialize a KurtosisMicrostructural Fit class instance.

Parameters

modelDiffusionKurtosisModel Class instance

Class instance containing the Diffusion Kurtosis Model for the fit

model_paramsndarray (x, y, z, 40) or (n, 40)

All parameters estimated from the diffusion kurtosis microstructural 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

Notes

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.

References

property awf

Returns the volume fraction of the restricted diffusion compartment also known as axonal water fraction.

Notes

The volume fraction of the restricted diffusion compartment can be seem as the volume fraction of the intra-cellular compartment [1]_.

References

property axonal_diffusivity

Returns the axonal diffusivity defined as the restricted diffusion tensor trace [1]_.

References

property hindered_ad

Returns the axial diffusivity of the hindered compartment.

Notes

The hindered diffusion tensor can be seem as the tissue’s extra-cellular diffusion compartment [1]_.

References

property hindered_evals

Returns the eigenvalues of the hindered diffusion compartment.

Notes

The hindered diffusion tensor can be seem as the tissue’s extra-cellular diffusion compartment [1]_.

References

property hindered_rd

Returns the radial diffusivity of the hindered compartment.

Notes

The hindered diffusion tensor can be seem as the tissue’s extra-cellular diffusion compartment [1]_.

References

predict(gtab, S0=1.0)

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).

property restricted_evals

Returns the eigenvalues of the restricted diffusion compartment.

Notes

The restricted diffusion tensor can be seem as the tissue’s intra-cellular diffusion compartment [1]_.

References

property tortuosity

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]_.

Notes

The hindered diffusion tensor can be seem as the tissue’s extra-cellular diffusion compartment [1]_.

References

axonal_water_fraction

dipy.reconst.dki_micro.axonal_water_fraction(dki_params, sphere='repulsion100', gtol=0.01, mask=None)

Computes the axonal water fraction from DKI [1]_.

Parameters

dki_paramsndarray (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

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]

Returns

awfndarray (x, y, z) or (n)

Axonal Water Fraction

References

diffusion_components

dipy.reconst.dki_micro.diffusion_components(dki_params, sphere='repulsion100', awf=None, mask=None)

Extracts the restricted and hindered diffusion tensors of well aligned fibers from diffusion kurtosis imaging parameters [1]_.

Parameters

dki_paramsndarray (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

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]

Returns

edtndarray (x, y, z, 6) or (n, 6)

Parameters of the hindered diffusion tensor.

idtndarray (x, y, z, 6) or (n, 6)

Parameters of the restricted diffusion tensor.

Notes

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.

References

dkimicro_prediction

dipy.reconst.dki_micro.dkimicro_prediction(params, gtab, S0=1)

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.

tortuosity

dipy.reconst.dki_micro.tortuosity(hindered_ad, hindered_rd)

Computes the tortuosity of the hindered diffusion compartment given its axial and radial diffusivities

Parameters

hindered_ad: ndarray

Array containing the values of the hindered axial diffusivity.

hindered_rd: ndarray

Array containing the values of the hindered radial diffusivity.

Returns

Tortuosity of the hindered diffusion compartment

DiffusionSpectrumModel

class dipy.reconst.dsi.DiffusionSpectrumModel(gtab, qgrid_size=17, r_start=2.1, r_end=6.0, r_step=0.2, filter_width=32, normalize_peaks=False)

Bases: OdfModel, Cache

__init__(gtab, qgrid_size=17, r_start=2.1, r_end=6.0, r_step=0.2, filter_width=32, normalize_peaks=False)

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

fit(data, mask=None)

Fit method for every voxel in data

DiffusionSpectrumFit

class dipy.reconst.dsi.DiffusionSpectrumFit(model, data)

Bases: OdfFit

__init__(model, data)

Calculates PDF and ODF and other properties for a single voxel

Parameters

modelobject,

DiffusionSpectrumModel

data1d ndarray,

signal values

msd_discrete(normalized=True)

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.

odf(sphere)

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.

pdf(normalized=True)

Applies the 3D FFT in the q-space grid to generate the diffusion propagator

rtop_pdf(normalized=True)

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)

Parameters

normalizedboolean, optional

Whether to normalize the propagator by its sum in order to obtain a pdf. Default: True.

Returns

rtopfloat

the return to origin probability

References

imaging”, Medical Image Analysis, vol 15, No. 4, p. 603-621, 2011.

in q -Space Using Magnetic Resonance Hybrid Diffusion Imaging”, IEEE TRANSACTIONS ON MEDICAL IMAGING, vol. 27, No. 6, p. 858-865, 2008

rtop_signal(filtering=True)

Calculates the return to origin probability (rtop) from the signal rtop equals to the sum of all signal values

Parameters

filteringboolean, optional

Whether to perform Hanning filtering. Default: True

Returns

rtopfloat

the return to origin probability

DiffusionSpectrumDeconvModel

class dipy.reconst.dsi.DiffusionSpectrumDeconvModel(gtab, qgrid_size=35, r_start=4.1, r_end=13.0, r_step=0.4, filter_width=inf, normalize_peaks=False)

Bases: DiffusionSpectrumModel

__init__(gtab, qgrid_size=35, r_start=4.1, r_end=13.0, r_step=0.4, filter_width=inf, normalize_peaks=False)

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.

fit(data, mask=None)

Fit method for every voxel in data

DiffusionSpectrumDeconvFit

class dipy.reconst.dsi.DiffusionSpectrumDeconvFit(model, data)

Bases: DiffusionSpectrumFit

__init__(model, data)

Calculates PDF and ODF and other properties for a single voxel

Parameters

modelobject,

DiffusionSpectrumModel

data1d ndarray,

signal values

pdf()

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

create_qspace

dipy.reconst.dsi.create_qspace(gtab, origin)

create the 3D grid which holds the signal values (q-space)

Parameters

gtab : GradientTable origin : (3,) ndarray

center of qspace

Returns

qgridndarray

qspace coordinates

create_qtable

dipy.reconst.dsi.create_qtable(gtab, origin)

create a normalized version of gradients

Parameters

gtab : GradientTable origin : (3,) ndarray

center of qspace

Returns

qtable : ndarray

hanning_filter

dipy.reconst.dsi.hanning_filter(gtab, filter_width, origin)

create a hanning window

The signal is premultiplied by a Hanning window before Fourier transform in order to ensure a smooth attenuation of the signal at high q values.

Parameters

gtab : GradientTable filter_width : int origin : (3,) ndarray

center of qspace

Returns

filter(N,) ndarray

where N is the number of non-b0 gradient directions

pdf_interp_coords

dipy.reconst.dsi.pdf_interp_coords(sphere, rradius, origin)

Precompute coordinates for ODF calculation from the PDF

Parameters

sphereobject,

Sphere

rradiusarray, shape (N,)

line interpolation points

originarray, shape (3,)

center of the grid

pdf_odf

dipy.reconst.dsi.pdf_odf(Pr, rradius, interp_coords)

Calculates the real ODF from the diffusion propagator(PDF) Pr

Parameters

Prarray, shape (X, X, X)

probability density function

rradiusarray, shape (N,)

interpolation range on the radius

interp_coordsarray, shape (3, M, N)

coordinates in the pdf for interpolating the odf

half_to_full_qspace

dipy.reconst.dsi.half_to_full_qspace(data, gtab)

Half to full Cartesian grid mapping

Useful when dMRI data are provided in one qspace hemisphere as DiffusionSpectrum expects data to be in full qspace.

Parameters

dataarray, shape (X, Y, Z, W)

where (X, Y, Z) volume size and W number of gradient directions

gtabGradientTable

container for b-values and b-vectors (gradient directions)

Returns

new_data : array, shape (X, Y, Z, 2 * W -1) new_gtab : GradientTable

Notes

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.

project_hemisph_bvecs

dipy.reconst.dsi.project_hemisph_bvecs(gtab)

Project any near identical bvecs to the other hemisphere

Parameters

gtabobject,

GradientTable

Notes

Useful only when working with some types of dsi data.

threshold_propagator

dipy.reconst.dsi.threshold_propagator(P, estimated_snr=15.0)

Applies hard threshold on the propagator to remove background noise for the deconvolution.

gen_PSF

dipy.reconst.dsi.gen_PSF(qgrid_sampling, siz_x, siz_y, siz_z)

Generate a PSF for DSI Deconvolution by taking the ifft of the binary q-space sampling mask and truncating it to keep only the center.

LR_deconv

dipy.reconst.dsi.LR_deconv(prop, psf, numit=5, acc_factor=1)

Perform Lucy-Richardson deconvolution algorithm on a 3D array.

Parameters

prop3-D ndarray of dtype float

The 3D volume to be deconvolve

psf3-D ndarray of dtype float

The filter that will be used for the deconvolution.

numitint

Number of Lucy-Richardson iteration to perform.

acc_factorfloat

Exponential acceleration factor as in [1]_.

References

TensorModel

class dipy.reconst.dti.TensorModel(gtab, fit_method='WLS', return_S0_hat=False, *args, **kwargs)

Bases: ReconstModel

Diffusion Tensor

__init__(gtab, fit_method='WLS', return_S0_hat=False, *args, **kwargs)

A Diffusion Tensor Model [1]_, [2]_.

Parameters

gtab : GradientTable class instance

fit_methodstr or callable

str can be one of the following:

‘WLS’ for weighted least squares

dti.wls_fit_tensor()

‘LS’ or ‘OLS’ for ordinary least squares

dti.ols_fit_tensor()

‘NLLS’ for non-linear least-squares

dti.nlls_fit_tensor()

‘RT’ or ‘restore’ or ‘RESTORE’ for RESTORE robust tensor

fitting [3]_ dti.restore_fit_tensor()

callable has to have the signature:

fit_method(design_matrix, data, *args, **kwargs)

return_S0_hatbool

Boolean to return (True) or not (False) the S0 values for the fit.

args, kwargsarguments and key-word arguments passed to the

fit_method. See dti.wls_fit_tensor, dti.ols_fit_tensor for details

min_signalfloat

The minimum signal value. Needs to be a strictly positive number. Default: minimal signal in the data provided to fit.

Notes

In order to increase speed of processing, tensor fitting is done simultaneously over many voxels. Many fit_methods use the ‘step’ parameter to set the number of voxels that will be fit at once in each iteration. This is the chunk size as a number of voxels. A larger step value should speed things up, but it will also take up more memory. It is advisable to keep an eye on memory consumption as this value is increased.

E.g., in iter_fit_tensor() we have a default step value of 1e4

References

fit(data, mask=None)

Fit method of the DTI model class

Parameters

dataarray

The measured signal from one voxel.

maskarray

A boolean array used to mark the coordinates in the data that should be analyzed that has the shape data.shape[:-1]

predict(dti_params, S0=1.0)

Predict a signal for this TensorModel class instance given parameters.

Parameters

dti_paramsndarray

The last dimension should have 12 tensor parameters: 3 eigenvalues, followed by the 3 eigenvectors

S0float or ndarray

The non diffusion-weighted signal in every voxel, or across all voxels. Default: 1

TensorFit

class dipy.reconst.dti.TensorFit(model, model_params, model_S0=None)

Bases: object

__init__(model, model_params, model_S0=None)

Initialize a TensorFit class instance.

property S0_hat
ad()

Axial diffusivity (AD) calculated from cached eigenvalues.

Returns

adarray (V, 1)

Calculated AD.

Notes

RD is calculated with the following equation:

\[AD = \lambda_1\]
adc(sphere)

Calculate the apparent diffusion coefficient (ADC) in each direction on the sphere for each voxel in the data

sphere : Sphere class instance

adcndarray

The estimates of the apparent diffusion coefficient in every direction on the input sphere

The calculation of ADC, relies on the following relationship:

\[ADC = \]

ec{b} Q ec{b}^T

Where Q is the quadratic form of the tensor.

color_fa()

Color fractional anisotropy of diffusion tensor

property directions

For tracking - return the primary direction in each voxel

property evals

Returns the eigenvalues of the tensor as an array

property evecs

Returns the eigenvectors of the tensor as an array, columnwise

fa()

Fractional anisotropy (FA) calculated from cached eigenvalues.

ga()

Geodesic anisotropy (GA) calculated from cached eigenvalues.

linearity()

Returns

linearityarray

Calculated linearity of the diffusion tensor [1]_.

Notes

Linearity is calculated with the following equation:

\[Linearity = \frac{\lambda_1-\lambda_2}{\lambda_1+\lambda_2+\lambda_3}\]

References

lower_triangular(b0=None)
md()

Mean diffusivity (MD) calculated from cached eigenvalues.

Returns

mdarray (V, 1)

Calculated MD.

Notes

MD is calculated with the following equation:

\[MD = \frac{\lambda_1+\lambda_2+\lambda_3}{3}\]
mode()

Tensor mode calculated from cached eigenvalues.

odf(sphere)

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

planarity()

Returns

sphericityarray

Calculated sphericity of the diffusion tensor [1]_.

Notes

Sphericity is calculated with the following equation:

\[Sphericity = \frac{2 (\lambda_2 - \lambda_3)}{\lambda_1+\lambda_2+\lambda_3}\]

References

predict(gtab, S0=None, step=None)

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

property quadratic_form

Calculates the 3x3 diffusion tensor for each voxel

rd()

Radial diffusivity (RD) calculated from cached eigenvalues.

Returns

rdarray (V, 1)

Calculated RD.

Notes

RD is calculated with the following equation:

\[RD = \frac{\lambda_2 + \lambda_3}{2}\]
property shape
sphericity()

Returns

sphericityarray

Calculated sphericity of the diffusion tensor [1]_.

Notes

Sphericity is calculated with the following equation:

\[Sphericity = \frac{3 \lambda_3}{\lambda_1+\lambda_2+\lambda_3}\]

References

trace()

Trace of the tensor calculated from cached eigenvalues.

Returns

tracearray (V, 1)

Calculated trace.

Notes

The trace is calculated with the following equation:

\[trace = \lambda_1 + \lambda_2 + \lambda_3\]

fractional_anisotropy

dipy.reconst.dti.fractional_anisotropy(evals, axis=-1)

Return Fractional anisotropy (FA) of a diffusion tensor.

Parameters

evalsarray-like

Eigenvalues of a diffusion tensor.

axisint

Axis of evals which contains 3 eigenvalues.

Returns

faarray

Calculated FA. Range is 0 <= FA <= 1.

Notes

FA is calculated using the following equation:

\[FA = \sqrt{\frac{1}{2}\frac{(\lambda_1-\lambda_2)^2+(\lambda_1- \lambda_3)^2+(\lambda_2-\lambda_3)^2}{\lambda_1^2+ \lambda_2^2+\lambda_3^2}}\]

geodesic_anisotropy

dipy.reconst.dti.geodesic_anisotropy(evals, axis=-1)

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.

mean_diffusivity

dipy.reconst.dti.mean_diffusivity(evals, axis=-1)

Mean Diffusivity (MD) of a diffusion tensor.

Parameters

evalsarray-like

Eigenvalues of a diffusion tensor.

axisint

Axis of evals which contains 3 eigenvalues.

Returns

mdarray

Calculated MD.

Notes

MD is calculated with the following equation:

\[MD = \frac{\lambda_1 + \lambda_2 + \lambda_3}{3}\]

axial_diffusivity

dipy.reconst.dti.axial_diffusivity(evals, axis=-1)

Axial Diffusivity (AD) of a diffusion tensor. Also called parallel diffusivity.

Parameters

evalsarray-like

Eigenvalues of a diffusion tensor, must be sorted in descending order along axis.

axisint

Axis of evals which contains 3 eigenvalues.

Returns

adarray

Calculated AD.

Notes

AD is calculated with the following equation:

\[AD = \lambda_1\]

radial_diffusivity

dipy.reconst.dti.radial_diffusivity(evals, axis=-1)

Radial Diffusivity (RD) of a diffusion tensor. Also called perpendicular diffusivity.

Parameters

evalsarray-like

Eigenvalues of a diffusion tensor, must be sorted in descending order along axis.

axisint

Axis of evals which contains 3 eigenvalues.

Returns

rdarray

Calculated RD.

Notes

RD is calculated with the following equation:

\[RD = \frac{\lambda_2 + \lambda_3}{2}\]

trace

dipy.reconst.dti.trace(evals, axis=-1)

Trace of a diffusion tensor.

Parameters

evalsarray-like

Eigenvalues of a diffusion tensor.

axisint

Axis of evals which contains 3 eigenvalues.

Returns

tracearray

Calculated trace of the diffusion tensor.

Notes

Trace is calculated with the following equation:

\[Trace = \lambda_1 + \lambda_2 + \lambda_3\]

color_fa

dipy.reconst.dti.color_fa(fa, evecs)

Color fractional anisotropy of diffusion tensor

Parameters

faarray-like

Array of the fractional anisotropy (can be 1D, 2D or 3D)

evecsarray-like

eigen vectors from the tensor model

Returns

rgbArray with 3 channels for each color as the last dimension.

Colormap of the FA with red for the x value, y for the green value and z for the blue value.

Notes

It is computed from the clipped FA between 0 and 1 using the following formula

\[rgb = abs(max(\vec{e})) \times fa\]

determinant

dipy.reconst.dti.determinant(q_form)

The determinant of a tensor, given in quadratic form

Parameters

q_formndarray

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

detarray

The determinant of the tensor in each spatial coordinate

isotropic

dipy.reconst.dti.isotropic(q_form)

Calculate the isotropic part of the tensor [1]_.

Parameters

q_formndarray

The quadratic form of a tensor, or an array with quadratic forms of tensors. Should be of shape (x,y,z,3,3) or (n, 3, 3) or (3,3).

Returns

A_hat: ndarray

The isotropic part of the tensor in each spatial coordinate

Notes

The isotropic part of a tensor is defined as (equations 3-5 of [1]_):

\[\bar{A} = \frac{1}{2} tr(A) I\]

References

deviatoric

dipy.reconst.dti.deviatoric(q_form)

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.

norm

dipy.reconst.dti.norm(q_form)

Calculate the Frobenius norm of a tensor quadratic form

Parameters

q_form: ndarray

The quadratic form of a tensor, or an array with quadratic forms of tensors. Should be of shape (x,y,z,3,3) or (n, 3, 3) or (3,3).

Returns

normndarray

The Frobenius norm of the 3,3 tensor q_form in each spatial coordinate.

Notes

The Frobenius norm is defined as:

math:

||A||_F = [sum_{i,j} abs(a_{i,j})^2]^{1/2}

See Also

np.linalg.norm

mode

dipy.reconst.dti.mode(q_form)

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.

linearity

dipy.reconst.dti.linearity(evals, axis=-1)

The linearity of the tensor [1]_

Parameters

evalsarray-like

Eigenvalues of a diffusion tensor.

axisint

Axis of evals which contains 3 eigenvalues.

Returns

linearityarray

Calculated linearity of the diffusion tensor.

Notes

Linearity is calculated with the following equation:

\[Linearity = \frac{\lambda_1-\lambda_2}{\lambda_1+\lambda_2+\lambda_3}\]

References

planarity

dipy.reconst.dti.planarity(evals, axis=-1)

The planarity of the tensor [1]_

Parameters

evalsarray-like

Eigenvalues of a diffusion tensor.

axisint

Axis of evals which contains 3 eigenvalues.

Returns

linearityarray

Calculated linearity of the diffusion tensor.

Notes

Planarity is calculated with the following equation:

\[Planarity = \frac{2 (\lambda_2-\lambda_3)}{\lambda_1+\lambda_2+\lambda_3}\]

References

sphericity

dipy.reconst.dti.sphericity(evals, axis=-1)

The sphericity of the tensor [1]_

Parameters

evalsarray-like

Eigenvalues of a diffusion tensor.

axisint

Axis of evals which contains 3 eigenvalues.

Returns

sphericityarray

Calculated sphericity of the diffusion tensor.

Notes

Sphericity is calculated with the following equation:

\[Sphericity = \frac{3 \lambda_3)}{\lambda_1+\lambda_2+\lambda_3}\]

References

apparent_diffusion_coef

dipy.reconst.dti.apparent_diffusion_coef(q_form, sphere)

Calculate the apparent diffusion coefficient (ADC) in each direction of a sphere.

Parameters

q_formndarray

The quadratic form of a tensor, or an array with quadratic forms of tensors. Should be of shape (…, 3, 3)

spherea Sphere class instance

The ADC will be calculated for each of the vertices in the sphere

Notes

The calculation of ADC, relies on the following relationship:

\[ADC = \vec{b} Q \vec{b}^T\]

Where Q is the quadratic form of the tensor.

tensor_prediction

dipy.reconst.dti.tensor_prediction(dti_params, gtab, S0)

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.

iter_fit_tensor

dipy.reconst.dti.iter_fit_tensor(step=10000.0)

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.

Parameters

stepint

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.

wls_fit_tensor

dipy.reconst.dti.wls_fit_tensor(design_matrix, data, return_S0_hat=False)

Computes weighted least squares (WLS) fit to calculate self-diffusion tensor using a linear regression model [1]_.

Parameters

design_matrixarray (g, 7)

Design matrix holding the covariants used to solve for the regression coefficients.

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.

return_S0_hatbool

Boolean to return (True) or not (False) the S0 values for the fit.

Returns

eigvalsarray (…, 3)

Eigenvalues from eigen decomposition of the tensor.

eigvecsarray (…, 3, 3)

Associated eigenvectors from eigen decomposition of the tensor. Eigenvectors are columnar (e.g. eigvecs[:,j] is associated with eigvals[j])

See Also

decompose_tensor

Notes

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:

  1. calculate OLS estimates of the data

  2. 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}\]

References

ols_fit_tensor

dipy.reconst.dti.ols_fit_tensor(design_matrix, data, return_S0_hat=False, return_lower_triangular=False)

Computes ordinary least squares (OLS) fit to calculate self-diffusion tensor using a linear regression model [1]_.

Parameters

design_matrixarray (g, 7)

Design matrix holding the covariants used to solve for the regression coefficients.

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.

return_S0_hatbool

Boolean to return (True) or not (False) the S0 values for the fit.

return_lower_triangularbool

Boolean to return (True) or not (False) the coefficients of the fit.

Returns

eigvalsarray (…, 3)

Eigenvalues from eigen decomposition of the tensor.

eigvecsarray (…, 3, 3)

Associated eigenvectors from eigen decomposition of the tensor. Eigenvectors are columnar (e.g. eigvecs[:,j] is associated with eigvals[j])

See Also

WLS_fit_tensor, decompose_tensor, design_matrix

Notes

\[ \begin{align}\begin{aligned}\begin{split}y = \mathrm{data} \\ X = \mathrm{design matrix} \\\end{split}\\\hat{\beta}_\mathrm{OLS} = (X^T X)^{-1} X^T y\end{aligned}\end{align} \]

References

nlls_fit_tensor

dipy.reconst.dti.nlls_fit_tensor(design_matrix, data, weighting=None, sigma=None, jac=True, return_S0_hat=False, fail_is_nan=False)

Fit the cumulant expansion params (e.g. DTI, DKI) using non-linear least-squares.

Parameters

design_matrixarray (g, Npar)

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’

sigma: float

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).

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).

Returns

nlls_params: the eigen-values and eigen-vectors of the tensor in each

voxel.

restore_fit_tensor

dipy.reconst.dti.restore_fit_tensor(design_matrix, data, sigma=None, jac=True, return_S0_hat=False, fail_is_nan=False)

Use the RESTORE algorithm [1]_ to calculate a robust tensor fit

Parameters

design_matrixarray of shape (g, 7)

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).

Returns

restore_params : an estimate of the tensor parameters in each voxel.

References

estimation of tensors by outlier rejection. MRM, 53: 1088-95.

_lt_indices

dipy.reconst.dti._lt_indices()
ndarray(shape, dtype=float, buffer=None, offset=0,

strides=None, order=None)

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.

Parameters

(for the __new__ method; see Notes below)

shapetuple of ints

Shape of created array.

dtypedata-type, optional

Any object that can be interpreted as a numpy data type.

bufferobject exposing buffer interface, optional

Used to fill the array with data.

offsetint, optional

Offset of array data in buffer.

stridestuple of ints, optional

Strides of data in memory.

order{‘C’, ‘F’}, optional

Row-major (C-style) or column-major (Fortran-style) order.

Attributes

Tndarray

Transpose of the array.

databuffer

The array’s elements, in memory.

dtypedtype object

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.

See Also

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

w.r.t. its dtype.type <numpy.dtype.type>.

Notes

There are two modes of creating an array using __new__:

  1. If buffer is None, then only shape, dtype, and order are used.

  2. If buffer is an object exposing the buffer interface, then all keywords are interpreted.

No __init__ method is needed because the array is fully initialized after the __new__ method.

Examples

These examples illustrate the low-level ndarray constructor. Refer to the See Also section above for easier ways of constructing an ndarray.

First mode, buffer is None:

>>> np.ndarray(shape=(2,2), dtype=float, order='F')
array([[0.0e+000, 0.0e+000], # random
       [     nan, 2.5e-323]])

Second mode:

>>> np.ndarray((2,), buffer=np.array([1,2,3]),
...            offset=np.int_().itemsize,
...            dtype=int) # offset = 1*itemsize, i.e. skip first element
array([2, 3])

from_lower_triangular

dipy.reconst.dti.from_lower_triangular(D)

Returns a tensor given the six unique tensor elements

Given the six unique tensor elements (in the order: Dxx, Dxy, Dyy, Dxz, Dyz, Dzz) returns a 3 by 3 tensor. All elements after the sixth are ignored.

Parameters

Darray_like, (…, >6)

Unique elements of the tensors

Returns

tensorndarray (…, 3, 3)

3 by 3 tensors

_lt_rows

dipy.reconst.dti._lt_rows()
ndarray(shape, dtype=float, buffer=None, offset=0,

strides=None, order=None)

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.

Parameters

(for the __new__ method; see Notes below)

shapetuple of ints

Shape of created array.

dtypedata-type, optional

Any object that can be interpreted as a numpy data type.

bufferobject exposing buffer interface, optional

Used to fill the array with data.

offsetint, optional

Offset of array data in buffer.

stridestuple of ints, optional

Strides of data in memory.

order{‘C’, ‘F’}, optional

Row-major (C-style) or column-major (Fortran-style) order.

Attributes

Tndarray

Transpose of the array.

databuffer

The array’s elements, in memory.

dtypedtype object

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.

See Also

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

w.r.t. its dtype.type <numpy.dtype.type>.

Notes

There are two modes of creating an array using __new__:

  1. If buffer is None, then only shape, dtype, and order are used.

  2. If buffer is an object exposing the buffer interface, then all keywords are interpreted.

No __init__ method is needed because the array is fully initialized after the __new__ method.

Examples

These examples illustrate the low-level ndarray constructor. Refer to the See Also section above for easier ways of constructing an ndarray.

First mode, buffer is None:

>>> np.ndarray(shape=(2,2), dtype=float, order='F')
array([[0.0e+000, 0.0e+000], # random
       [     nan, 2.5e-323]])

Second mode:

>>> np.ndarray((2,), buffer=np.array([1,2,3]),
...            offset=np.int_().itemsize,
...            dtype=int) # offset = 1*itemsize, i.e. skip first element
array([2, 3])

_lt_cols

dipy.reconst.dti._lt_cols()
ndarray(shape, dtype=float, buffer=None, offset=0,

strides=None, order=None)

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.

Parameters

(for the __new__ method; see Notes below)

shapetuple of ints

Shape of created array.

dtypedata-type, optional

Any object that can be interpreted as a numpy data type.

bufferobject exposing buffer interface, optional

Used to fill the array with data.

offsetint, optional

Offset of array data in buffer.

stridestuple of ints, optional

Strides of data in memory.

order{‘C’, ‘F’}, optional

Row-major (C-style) or column-major (Fortran-style) order.

Attributes

Tndarray

Transpose of the array.

databuffer

The array’s elements, in memory.

dtypedtype object

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.

See Also

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

w.r.t. its dtype.type <numpy.dtype.type>.

Notes

There are two modes of creating an array using __new__:

  1. If buffer is None, then only shape, dtype, and order are used.

  2. If buffer is an object exposing the buffer interface, then all keywords are interpreted.

No __init__ method is needed because the array is fully initialized after the __new__ method.

Examples

These examples illustrate the low-level ndarray constructor. Refer to the See Also section above for easier ways of constructing an ndarray.

First mode, buffer is None:

>>> np.ndarray(shape=(2,2), dtype=float, order='F')
array([[0.0e+000, 0.0e+000], # random
       [     nan, 2.5e-323]])

Second mode:

>>> np.ndarray((2,), buffer=np.array([1,2,3]),
...            offset=np.int_().itemsize,
...            dtype=int) # offset = 1*itemsize, i.e. skip first element
array([2, 3])

lower_triangular

dipy.reconst.dti.lower_triangular(tensor, b0=None)

Returns the six lower triangular values of the tensor ordered as (Dxx, Dxy, Dyy, Dxz, Dyz, Dzz) and a dummy variable if b0 is not None.

Parameters

tensorarray_like (…, 3, 3)

a collection of 3, 3 diffusion tensors

b0float

if b0 is not none log(b0) is returned as the dummy variable

Returns

Dndarray

If b0 is none, then the shape will be (…, 6) otherwise (…, 7)

decompose_tensor

dipy.reconst.dti.decompose_tensor(tensor, min_diffusivity=0)

Returns eigenvalues and eigenvectors given a diffusion tensor

Computes tensor eigen decomposition to calculate eigenvalues and eigenvectors (Basser et al., 1994a).

Parameters

tensorarray (…, 3, 3)

Hermitian matrix representing a diffusion tensor.

min_diffusivityfloat

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.

Returns

eigvalsarray (…, 3)

Eigenvalues from eigen decomposition of the tensor. Negative eigenvalues are replaced by zero. Sorted from largest to smallest.

eigvecsarray (…, 3, 3)

Associated eigenvectors from eigen decomposition of the tensor. Eigenvectors are columnar (e.g. eigvecs[…, :, j] is associated with eigvals[…, j])

design_matrix

dipy.reconst.dti.design_matrix(gtab, dtype=None)

Constructs design matrix for DTI weighted least squares or least squares fitting. (Basser et al., 1994a)

Parameters

gtab : A GradientTable class instance

dtypestring

Parameter to control the dtype of returned designed matrix

Returns

design_matrixarray (g,7)

Design matrix or B matrix assuming Gaussian distributed tensor model design_matrix[j, :] = (Bxx, Byy, Bzz, Bxy, Bxz, Byz, dummy)

quantize_evecs

dipy.reconst.dti.quantize_evecs(evecs, odf_vertices=None)

Find the closest orientation of an evenly distributed sphere

Parameters

evecs : ndarray odf_vertices : None or ndarray

If None, then set vertices from symmetric362 sphere. Otherwise use passed ndarray as vertices

Returns

IN : ndarray

eig_from_lo_tri

dipy.reconst.dti.eig_from_lo_tri(data, min_diffusivity=0)

Calculates tensor eigenvalues/eigenvectors from an array containing the lower diagonal form of the six unique tensor elements.

Parameters

dataarray_like (…, 6)

diffusion tensors elements stored in lower triangular order

min_diffusivityfloat

See decompose_tensor()

Returns

dti_paramsarray (…, 12)

Eigen-values and eigen-vectors of the same array.

ForecastModel

class dipy.reconst.forecast.ForecastModel(gtab, sh_order=8, lambda_lb=0.001, dec_alg='CSD', sphere=None, lambda_csd=1.0)

Bases: OdfModel, Cache

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]_

References

Notes

The implementation of FORECAST may require CVXPY (http://www.cvxpy.org/).

__init__(gtab, sh_order=8, lambda_lb=0.001, dec_alg='CSD', sphere=None, lambda_csd=1.0)

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 : unsigned int, an even integer that represent the SH order 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=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)

fit(data, mask=None)

Fit method for every voxel in data

ForecastFit

class dipy.reconst.forecast.ForecastFit(model, data, sh_coef, d_par, d_perp)

Bases: OdfFit

__init__(model, data, sh_coef, d_par, d_perp)

Calculates diffusion properties for a single voxel

Parameters

modelobject,

AnalyticalModel

data1d ndarray,

fitted data

sh_coef1d ndarray,

forecast sh coefficients

d_parfloat,

parallel diffusivity

d_perpfloat,

perpendicular diffusivity

property dpar

The parallel diffusivity

property dperp

The perpendicular diffusivity

fractional_anisotropy()

Calculates the fractional anisotropy.

mean_diffusivity()

Calculates the mean diffusivity.

odf(sphere, clip_negative=True)

Calculates the fODF for a given discrete sphere.

Parameters

sphereSphere,

the odf sphere

clip_negativeboolean, optional

if True clip the negative odf values to 0, default True

predict(gtab=None, S0=1.0)

Calculates the fODF for a given discrete sphere.

Parameters

gtabGradientTable, optional

gradient directions and bvalues container class.

S0float, optional

the signal at b-value=0

property sh_coeff

The FORECAST SH coefficients

find_signal_means

dipy.reconst.forecast.find_signal_means(b_unique, data_norm, bvals, rho, lb_matrix, w=0.001)

Calculate the mean signal for each shell.

Parameters

b_unique1d ndarray,

unique b-values in a vector excluding zero

data_norm1d ndarray,

normalized diffusion signal

bvals1d ndarray,

the b-values

rho2d ndarray,

SH basis matrix for fitting the signal on each shell

lb_matrix2d ndarray,

Laplace-Beltrami regularization matrix

wfloat,

weight for the Laplace-Beltrami regularization

Returns

means1d ndarray

the average of the signal for each b-values

forecast_error_func

dipy.reconst.forecast.forecast_error_func(x, b_unique, E)

Calculates the difference between the mean signal calculated using the parameter vector x and the average signal E using FORECAST and SMT

psi_l

dipy.reconst.forecast.psi_l(l, b)

forecast_matrix

dipy.reconst.forecast.forecast_matrix(sh_order, d_par, d_perp, bvals)

Compute the FORECAST radial matrix

rho_matrix

dipy.reconst.forecast.rho_matrix(sh_order, vecs)

Compute the SH matrix \(\rho\)

lb_forecast

dipy.reconst.forecast.lb_forecast(sh_order)

Returns the Laplace-Beltrami regularization matrix for FORECAST

FreeWaterTensorModel

class dipy.reconst.fwdti.FreeWaterTensorModel(gtab, fit_method='NLS', *args, **kwargs)

Bases: ReconstModel

Class for the Free Water Elimination Diffusion Tensor Model

__init__(gtab, fit_method='NLS', *args, **kwargs)

Free Water Diffusion Tensor Model [1]_.

Parameters

gtab : GradientTable class instance fit_method : str or callable

str can be one of the following:

‘WLS’ for weighted linear least square fit according to [1]_

fwdti.wls_iter()

‘NLS’ for non-linear least square fit according to [1]_

fwdti.nls_iter()

callable has to have the signature:

fit_method(design_matrix, data, *args, **kwargs)

args, kwargsarguments and key-word arguments passed to the

fit_method. See fwdti.wls_iter, fwdti.nls_iter for details

References

fit(data, mask=None)

Fit method for every voxel in data

predict(fwdti_params, S0=1)

Predict a signal for this TensorModel class instance given parameters.

Parameters

fwdti_params(…, 13) ndarray

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

Returns

S(…, N) ndarray

Simulated signal based on the free water DTI model

FreeWaterTensorFit

class dipy.reconst.fwdti.FreeWaterTensorFit(model, model_params)

Bases: TensorFit

Class for fitting the Free Water Tensor Model

__init__(model, model_params)

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

Parameters

modelFreeWaterTensorModel Class instance

Class instance containing the free water tensor model for the fit

model_paramsndarray (x, y, z, 13) or (n, 13)

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

References

property f

Returns the free water diffusion volume fraction f

predict(gtab, S0=1)

Given a free water tensor model fit, predict the signal on the vertices of a gradient table

Parameters

gtaba GradientTable class instance

The gradient table for this prediction

S0float array

The mean non-diffusion weighted signal in each voxel. Default: 1 in all voxels.

Returns

S(…, N) ndarray

Simulated signal based on the free water DTI model

fwdti_prediction

dipy.reconst.fwdti.fwdti_prediction(params, gtab, S0=1, Diso=0.003)

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

wls_iter

dipy.reconst.fwdti.wls_iter(design_matrix, sig, S0, Diso=0.003, mdreg=0.0027, min_signal=1e-06, piterations=3)

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

wls_fit_tensor

dipy.reconst.fwdti.wls_fit_tensor(gtab, data, Diso=0.003, mask=None, min_signal=1e-06, piterations=3, mdreg=0.0027)

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

nls_iter

dipy.reconst.fwdti.nls_iter(design_matrix, sig, S0, Diso=0.003, mdreg=0.0027, min_signal=1e-06, cholesky=False, f_transform=True, jac=False, weighting=None, sigma=None)

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.

nls_fit_tensor

dipy.reconst.fwdti.nls_fit_tensor(gtab, data, mask=None, Diso=0.003, mdreg=0.0027, min_signal=1e-06, f_transform=True, cholesky=False, jac=False, weighting=None, sigma=None)

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

lower_triangular_to_cholesky

dipy.reconst.fwdti.lower_triangular_to_cholesky(tensor_elements)

Performs Cholesky decomposition of the diffusion tensor

Parameters

tensor_elementsarray (6,)

Array containing the six elements of diffusion tensor’s lower triangular.

Returns

cholesky_elementsarray (6,)

Array containing the six Cholesky’s decomposition elements (R0, R1, R2, R3, R4, R5) [1]_.

References

cholesky_to_lower_triangular

dipy.reconst.fwdti.cholesky_to_lower_triangular(R)

Convert Cholesky decomposition elements to the diffusion tensor elements

Parameters

Rarray (6,)

Array containing the six Cholesky’s decomposition elements (R0, R1, R2, R3, R4, R5) [1]_.

Returns

tensor_elementsarray (6,)

Array containing the six elements of diffusion tensor’s lower triangular.

References

GeneralizedQSamplingModel

class dipy.reconst.gqi.GeneralizedQSamplingModel(gtab, method='gqi2', sampling_length=1.2, normalize_peaks=False)

Bases: OdfModel, Cache

__init__(gtab, method='gqi2', sampling_length=1.2, normalize_peaks=False)

Generalized Q-Sampling Imaging [1]_

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.

Parameters

gtabobject,

GradientTable

methodstr,

‘standard’ or ‘gqi2’

sampling_lengthfloat,

diffusion sampling length (lambda in eq. 2.14 and 2.16)

References

thesis, University of Cambridge, 2012.

Notes

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).

Examples

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.

>>> from dipy.data import dsi_voxels
>>> data, gtab = dsi_voxels()
>>> from dipy.core.subdivide_octahedron import create_unit_sphere
>>> sphere = create_unit_sphere(5)
>>> from dipy.reconst.gqi import GeneralizedQSamplingModel
>>> gq = GeneralizedQSamplingModel(gtab, 'gqi2', 1.1)
>>> voxel_signal = data[0, 0, 0]
>>> odf = gq.fit(voxel_signal).odf(sphere)

See Also

dipy.reconst.dsi.DiffusionSpectrumModel

fit(data, mask=None)

Fit method for every voxel in data

GeneralizedQSamplingFit

class dipy.reconst.gqi.GeneralizedQSamplingFit(model, data)

Bases: OdfFit

__init__(model, data)

Calculates PDF and ODF for a single voxel

Parameters

modelobject,

DiffusionSpectrumModel

data1d ndarray,

signal values

odf(sphere)

Calculates the discrete ODF for a given discrete sphere.

normalize_qa

dipy.reconst.gqi.normalize_qa(qa, max_qa=None)

Normalize quantitative anisotropy.

Used mostly with GQI rather than GQI2.

Parameters

qaarray, shape (X, Y, Z, N)

where N is the maximum number of peaks stored

max_qafloat,

maximum qa value. Usually found in the CSF (corticospinal fluid).

Returns

nqaarray, shape (x, Y, Z, N)

normalized quantitative anisotropy

Notes

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.

squared_radial_component

dipy.reconst.gqi.squared_radial_component(x, tol=0.01)

Part of the GQI2 integral

Eq.8 in the referenced paper by Yeh et al. 2010

npa

dipy.reconst.gqi.npa(self, odf, width=5)

non-parametric anisotropy

Nimmo-Smith et al. ISMRM 2011

equatorial_zone_vertices

dipy.reconst.gqi.equatorial_zone_vertices(vertices, pole, width=5)

finds the ‘vertices’ in the equatorial zone conjugate to ‘pole’ with width half ‘width’ degrees

polar_zone_vertices

dipy.reconst.gqi.polar_zone_vertices(vertices, pole, width=5)

finds the ‘vertices’ in the equatorial band around the ‘pole’ of radius ‘width’ degrees

upper_hemi_map

dipy.reconst.gqi.upper_hemi_map(v)

maps a 3-vector into the z-upper hemisphere

equatorial_maximum

dipy.reconst.gqi.equatorial_maximum(vertices, odf, pole, width)

patch_vertices

dipy.reconst.gqi.patch_vertices(vertices, pole, width)

find ‘vertices’ within the cone of ‘width’ degrees around ‘pole’

patch_maximum

dipy.reconst.gqi.patch_maximum(vertices, odf, pole, width)

odf_sum

dipy.reconst.gqi.odf_sum(odf)

patch_sum

dipy.reconst.gqi.patch_sum(vertices, odf, pole, width)

triple_odf_maxima

dipy.reconst.gqi.triple_odf_maxima(vertices, odf, width)

IvimModelTRR

class dipy.reconst.ivim.IvimModelTRR(gtab, split_b_D=400.0, split_b_S0=200.0, bounds=None, two_stage=True, tol=1e-15, x_scale=(1000.0, 0.1, 0.001, 0.0001), gtol=1e-15, ftol=1e-15, eps=1e-15, maxiter=1000)

Bases: ReconstModel

Ivim model

__init__(gtab, split_b_D=400.0, split_b_S0=200.0, bounds=None, two_stage=True, tol=1e-15, x_scale=(1000.0, 0.1, 0.001, 0.0001), gtol=1e-15, ftol=1e-15, eps=1e-15, maxiter=1000)

Initialize an IVIM model.

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

\[\]

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.

Parameters

gtabGradientTable class instance

Gradient directions and bvalues

split_b_Dfloat, optional

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

References

estimate_f_D_star(params_f_D_star, data, S0, D)

Estimate f and D_star using the values of all the other parameters obtained from a linear fit.

Parameters

params_f_D_star: array

An array containing the value of f and D_star.

dataarray

Array containing the actual signal values.

S0float

The parameters S0 obtained from a linear fit.

Dfloat

The parameters D obtained from a linear fit.

Returns

ffloat

Perfusion fraction estimated from the fit.

D_star :

The value of D_star estimated from the fit.

estimate_linear_fit(data, split_b, less_than=True)

Estimate a linear fit by taking log of data.

Parameters

dataarray

An array containing the data to be fit

split_bfloat

The b value to split the data

less_thanbool

If True, splitting occurs for bvalues less than split_b

Returns

S0float

The estimated S0 value. (intercept)

Dfloat

The estimated value of D.

fit(data, mask=None)

Fit method for every voxel in data

predict(ivim_params, gtab, S0=1.0)

Predict a signal for this IvimModel class instance given parameters.

Parameters

ivim_paramsarray

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.

Returns

ivim_signalarray

The predicted IVIM signal using given parameters.

IvimModelVP

class dipy.reconst.ivim.IvimModelVP(gtab, bounds=None, maxiter=10, xtol=1e-08)

Bases: ReconstModel

__init__(gtab, bounds=None, maxiter=10, xtol=1e-08)

Initialize an IvimModelVP class.

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

References

cvx_fit(signal, phi)

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.

Parameters

phiarray

Returns an array calculated from :func: phi.

signalarray

The signal values measured for this model.

Returns

f1, f2 (volume fractions)

Notes

cost function for differential evolution algorithm:

\[minimize(norm((signal)- (phi*f)))\]
fit(data, mask=None)

Fit method for every voxel in data

ivim_mix_cost_one(phi, signal)

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).

Parameters

phiarray

Returns an array calculated from :func: Phi.

signalarray

The signal values measured for this model.

Returns

(signal - S)^T(signal - S)

Notes

to make cost function for Differential Evolution algorithm: .. math:

(signal -  S)^T(signal -  S)

References

nlls_cost(x_f, signal)

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.

Parameters

x_farray

Contains the parameters ‘x’ and ‘f’ combines in the same array.

signalarray

The signal values measured for this model.

Returns

sum{(signal - phi*f)^2}

Notes

cost function for the least square problem.

\[sum{(signal - phi*f)^2}\]
phi(x)

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.

Parameters

xarray

input from the Differential Evolution optimizer.

Returns

exp_phi1array

Combined array of parameters perfusion/pseudo-diffusion and diffusion parameters.

stoc_search_cost(x, signal)

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.

Parameters

xarray

input from the Differential Evolution optimizer.

signalarray

The signal values measured for this model.

Returns

func:

ivim_mix_cost_one

x_and_f_to_x_f(x, f)

Combines the array of parameters ‘x’ and ‘f’ into x_f for performing NLLS on the final stage of optimization.

Parameters

x, farray

Split parameters into two separate arrays

Returns

x_farray

Combined array of parameters ‘x’ and ‘f’ parameters.

x_f_to_x_and_f(x_f)

Splits the array of parameters in x_f to ‘x’ and ‘f’ for performing a search on the both of them independently using the Trust Region Method.

Parameters

x_farray

Combined array of parameters ‘x’ and ‘f’ parameters.

Returns

x, farray

Split parameters into two separate arrays

IvimFit

class dipy.reconst.ivim.IvimFit(model, model_params)

Bases: object

__init__(model, model_params)

Initialize a IvimFit class instance.

Parameters

model : Model class

model_paramsarray

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.

property D
property D_star
property S0_predicted
property perfusion_fraction
predict(gtab, S0=1.0)

Given a model fit, predict the signal.

Parameters

gtabGradientTable class instance

Gradient directions and bvalues

S0float

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.

Returns

signalarray

The signal values predicted for this model using its parameters.

property shape

ivim_prediction

dipy.reconst.ivim.ivim_prediction(params, gtab)

The Intravoxel incoherent motion (IVIM) model function.

Parameters

paramsarray

An array of IVIM parameters - [S0, f, D_star, 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.

Returns

Sarray

An array containing the IVIM signal estimated using given parameters.

f_D_star_prediction

dipy.reconst.ivim.f_D_star_prediction(params, gtab, S0, D)

Function used to predict IVIM signal when S0 and D are known by considering f and D_star as the unknown parameters.

Parameters

paramsarray

The value of f and D_star.

gtabGradientTable class instance

Gradient directions and bvalues.

S0float

The parameters S0 obtained from a linear fit.

Dfloat

The parameters D obtained from a linear fit.

Returns

Sarray

An array containing the IVIM signal estimated using given parameters.

f_D_star_error

dipy.reconst.ivim.f_D_star_error(params, gtab, signal, S0, D)

Error function used to fit f and D_star keeping S0 and D fixed

Parameters

paramsarray

The value of f and D_star.

gtabGradientTable class instance

Gradient directions and bvalues.

signalarray

Array containing the actual signal values.

S0float

The parameters S0 obtained from a linear fit.

Dfloat

The parameters D obtained from a linear fit.

Returns

residualarray

An array containing the difference of actual and estimated signal.

ivim_model_selector

dipy.reconst.ivim.ivim_model_selector(gtab, fit_method='trr', **kwargs)

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.

Parameters

fit_methodstring, optional

The value fit_method can either be ‘trr’ or ‘varpro’. default : trr

MapmriModel

class dipy.reconst.mapmri.MapmriModel(gtab, radial_order=6, laplacian_regularization=True, laplacian_weighting=0.2, positivity_constraint=False, global_constraints=False, pos_grid=15, pos_radius='adaptive', anisotropic_scaling=True, eigenvalue_threshold=0.0001, bval_threshold=inf, dti_scale_estimation=True, static_diffusivity=0.0007, cvxpy_solver=None)

Bases: ReconstModel, Cache

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.

References

__init__(gtab, radial_order=6, laplacian_regularization=True, laplacian_weighting=0.2, positivity_constraint=False, global_constraints=False, pos_grid=15, pos_radius='adaptive', anisotropic_scaling=True, eigenvalue_threshold=0.0001, bval_threshold=inf, dti_scale_estimation=True, static_diffusivity=0.0007, cvxpy_solver=None)

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.

Parameters
gtabGradientTable,

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 http://www.cvxpy.org/ for details. Default: None (cvxpy chooses its own solver)

References
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.

>>> from dipy.data import dsi_voxels, default_sphere
>>> from dipy.core.gradients import gradient_table
>>> _, gtab_ = dsi_voxels()
>>> gtab = gradient_table(gtab_.bvals, gtab_.bvecs,
...                       b0_threshold=gtab_.bvals.min())
>>> from dipy.sims.voxel import sticks_and_ball
>>> data, golden_directions = sticks_and_ball(gtab, d=0.0015, S0=1,
...                                           angles=[(0, 0),
...                                                   (90, 0)],
...                                           fractions=[50, 50],
...                                           snr=None)
>>> from dipy.reconst.mapmri import MapmriModel
>>> radial_order = 4
>>> map_model = MapmriModel(gtab, radial_order=radial_order)
>>> mapfit = map_model.fit(data)
>>> odf = mapfit.odf(default_sphere)
fit(data, mask=None)

Fit method for every voxel in data

MapmriFit

class dipy.reconst.mapmri.MapmriFit(model, mapmri_coef, mu, R, lopt, errorcode=0)

Bases: ReconstFit

__init__(model, mapmri_coef, mu, R, lopt, errorcode=0)

Calculates diffusion properties for a single voxel

Parameters

modelobject,

AnalyticalModel

mapmri_coef1d ndarray,

mapmri coefficients

muarray, shape (3,)

scale parameters vector for x, y and z

Rarray, shape (3,3)

rotation matrix

loptfloat,

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.

fitted_signal(gtab=None)

Recovers the fitted signal for the given gradient table. If no gradient table is given it recovers the signal for the gtab of the model object.

property mapmri_R

The MAPMRI rotation matrix

property mapmri_coeff

The MAPMRI coefficients

property mapmri_mu

The MAPMRI scale factors

msd()

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).

References

Propagator and Its Features in Diffusion MRI. Ph.D. Thesis.

using Laplacian-regularized MAP-MRI and its application to HCP data.” NeuroImage (2016).

ng()

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]_.

References

diffusion imaging method for mapping tissue microstructure”, NeuroImage, 2013.

propagator (MAP) MRI to characterize brain tissue microstructure”. NeuroImage 2015, in press.

ng_parallel()

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]_.

References

diffusion imaging method for mapping tissue microstructure”, NeuroImage, 2013.

propagator (MAP) MRI to characterize brain tissue microstructure”. NeuroImage 2015, in press.

ng_perpendicular()

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]_.

References

diffusion imaging method for mapping tissue microstructure”, NeuroImage, 2013.

propagator (MAP) MRI to characterize brain tissue microstructure”. NeuroImage 2015, in press.

norm_of_laplacian_signal()

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).

References

using Laplacian-regularized MAP-MRI and its application to HCP data.” NeuroImage (2016).

odf(sphere, s=2)

Calculates the analytical Orientation Distribution Function (ODF) from the signal [1]_ Eq. (32).

Parameters

sphereSphere

A Sphere instance with vertices, edges and faces attributes.

sunsigned int

radial moment of the ODF

References

diffusion imaging method for mapping tissue microstructure”, NeuroImage, 2013.

odf_sh(s=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).

References

diffusion imaging method for mapping tissue microstructure”, NeuroImage, 2013.

using Laplacian-regularized MAP-MRI and its application to HCP data.” NeuroImage (2016).

pdf(r_points)

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

predict(qvals_or_gtab, S0=100.0)

Recovers the reconstructed signal for any qvalue array or gradient table.

qiv()

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).

References

(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).

rtap()

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).

References

diffusion imaging method for mapping tissue microstructure”, NeuroImage, 2013.

using Laplacian-regularized MAP-MRI and its application to HCP data.” NeuroImage (2016).

rtop()

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).

References

diffusion imaging method for mapping tissue microstructure”, NeuroImage, 2013.

using Laplacian-regularized MAP-MRI and its application to HCP data.” NeuroImage (2016).

rtpp()

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).

References

diffusion imaging method for mapping tissue microstructure”, NeuroImage, 2013.

using Laplacian-regularized MAP-MRI and its application to HCP data.” NeuroImage (2016).

isotropic_scale_factor

dipy.reconst.mapmri.isotropic_scale_factor(mu_squared)

Estimated isotropic scaling factor _[1] Eq. (49).

Parameters

mu_squaredarray, shape (N,3)

squared scale factors of mapmri basis in x, y, z

Returns

u0float

closest isotropic scale factor for the isotropic basis

References

diffusion imaging method for mapping tissue microstructure”, NeuroImage, 2013.

mapmri_index_matrix

dipy.reconst.mapmri.mapmri_index_matrix(radial_order)

Calculates the indices for the MAPMRI [1]_ basis in x, y and z.

Parameters

radial_orderunsigned int

radial order of MAPMRI basis

Returns

index_matrixarray, shape (N,3)

ordering of the basis in x, y, z

References

diffusion imaging method for mapping tissue microstructure”, NeuroImage, 2013.

b_mat

dipy.reconst.mapmri.b_mat(index_matrix)

Calculates the B coefficients from [1]_ Eq. (27).

Parameters

index_matrixarray, shape (N,3)

ordering of the basis in x, y, z

Returns

Barray, shape (N,)

B coefficients for the basis

References

diffusion imaging method for mapping tissue microstructure”, NeuroImage, 2013.

b_mat_isotropic

dipy.reconst.mapmri.b_mat_isotropic(index_matrix)

Calculates the isotropic B coefficients from [1]_ Fig 8.

Parameters

index_matrixarray, shape (N,3)

ordering of the isotropic basis in j, l, m

Returns

Barray, shape (N,)

B coefficients for the isotropic basis

References

diffusion imaging method for mapping tissue microstructure”, NeuroImage, 2013.

mapmri_phi_1d

dipy.reconst.mapmri.mapmri_phi_1d(n, q, mu)

One dimensional MAPMRI basis function from [1]_ Eq. (4).

Parameters

nunsigned int

order of the basis

qarray, shape (N,)

points in the q-space in which evaluate the basis

mufloat

scale factor of the basis

References

diffusion imaging method for mapping tissue microstructure”, NeuroImage, 2013.

mapmri_phi_matrix

dipy.reconst.mapmri.mapmri_phi_matrix(radial_order, mu, q_gradients)

Compute the MAPMRI phi matrix for the signal [1]_ eq. (23).

Parameters

radial_orderunsigned int,

an even integer that represent the order of the basis

muarray, shape (3,)

scale factors of the basis for x, y, z

q_gradientsarray, shape (N,3)

points in the q-space in which evaluate the basis

References

diffusion imaging method for mapping tissue microstructure”, NeuroImage, 2013.

mapmri_psi_1d

dipy.reconst.mapmri.mapmri_psi_1d(n, x, mu)

One dimensional MAPMRI propagator basis function from [1]_ Eq. (10).

Parameters

nunsigned int

order of the basis

xarray, shape (N,)

points in the r-space in which evaluate the basis

mufloat

scale factor of the basis

References

diffusion imaging method for mapping tissue microstructure”, NeuroImage, 2013.

mapmri_psi_matrix

dipy.reconst.mapmri.mapmri_psi_matrix(radial_order, mu, rgrad)

Compute the MAPMRI psi matrix for the propagator [1]_ eq. (22).

Parameters

radial_orderunsigned int,

an even integer that represent the order of the basis

muarray, shape (3,)

scale factors of the basis for x, y, z

rgradarray, shape (N,3)

points in the r-space in which evaluate the EAP

References

diffusion imaging method for mapping tissue microstructure”, NeuroImage, 2013.

mapmri_odf_matrix

dipy.reconst.mapmri.mapmri_odf_matrix(radial_order, mu, s, vertices)

Compute the MAPMRI ODF matrix [1]_ Eq. (33).

Parameters

radial_orderunsigned int,

an even integer that represent the order of the basis

muarray, shape (3,)

scale factors of the basis for x, y, z

sunsigned int

radial moment of the ODF

verticesarray, shape (N,3)

points of the sphere shell in the r-space in which evaluate the ODF

References

diffusion imaging method for mapping tissue microstructure”, NeuroImage, 2013.

mapmri_isotropic_phi_matrix

dipy.reconst.mapmri.mapmri_isotropic_phi_matrix(radial_order, mu, q)

Three dimensional isotropic MAPMRI signal basis function from [1]_ Eq. (61).

Parameters

radial_orderunsigned int,

radial order of the mapmri basis.

mufloat,

positive isotropic scale factor of the basis

qarray, shape (N,3)

points in the q-space in which evaluate the basis

References

diffusion imaging method for mapping tissue microstructure”, NeuroImage, 2013.

mapmri_isotropic_radial_signal_basis

dipy.reconst.mapmri.mapmri_isotropic_radial_signal_basis(j, l, mu, qval)

Radial part of the isotropic 1D-SHORE signal basis [1]_ eq. (61).

Parameters

junsigned int,

a positive integer related to the radial order

lunsigned int,

the spherical harmonic order

mufloat,

isotropic scale factor of the basis

qvalfloat,

points in the q-space in which evaluate the basis

References

diffusion imaging method for mapping tissue microstructure”, NeuroImage, 2013.

mapmri_isotropic_M_mu_independent

dipy.reconst.mapmri.mapmri_isotropic_M_mu_independent(radial_order, q)

Computed the mu independent part of the signal design matrix.

mapmri_isotropic_M_mu_dependent

dipy.reconst.mapmri.mapmri_isotropic_M_mu_dependent(radial_order, mu, qval)

Computed the mu dependent part of the signal design matrix.

mapmri_isotropic_psi_matrix

dipy.reconst.mapmri.mapmri_isotropic_psi_matrix(radial_order, mu, rgrad)

Three dimensional isotropic MAPMRI propagator basis function from [1]_ Eq. (61).

Parameters

radial_orderunsigned int,

radial order of the mapmri basis.

mufloat,

positive isotropic scale factor of the basis

rgradarray, shape (N,3)

points in the r-space in which evaluate the basis

References

diffusion imaging method for mapping tissue microstructure”, NeuroImage, 2013.

mapmri_isotropic_radial_pdf_basis

dipy.reconst.mapmri.mapmri_isotropic_radial_pdf_basis(j, l, mu, r)

Radial part of the isotropic 1D-SHORE propagator basis [1]_ eq. (61).

Parameters

junsigned int,

a positive integer related to the radial order

lunsigned int,

the spherical harmonic order

mufloat,

isotropic scale factor of the basis

rfloat,

points in the r-space in which evaluate the basis

References

diffusion imaging method for mapping tissue microstructure”, NeuroImage, 2013.

mapmri_isotropic_K_mu_independent

dipy.reconst.mapmri.mapmri_isotropic_K_mu_independent(radial_order, rgrad)

Computes mu independent part of K. Same trick as with M.

mapmri_isotropic_K_mu_dependent

dipy.reconst.mapmri.mapmri_isotropic_K_mu_dependent(radial_order, mu, rgrad)

Computes mu dependent part of M. Same trick as with M.

binomialfloat

dipy.reconst.mapmri.binomialfloat(n, k)

Custom Binomial function

mapmri_isotropic_odf_matrix

dipy.reconst.mapmri.mapmri_isotropic_odf_matrix(radial_order, mu, s, vertices)

Compute the isotropic MAPMRI ODF matrix [1]_ Eq. 32 but for the isotropic propagator in [1]_ eq. (60). Analytical derivation in [2]_ eq. (C8).

Parameters

radial_orderunsigned int,

an even integer that represent the order of the basis

mufloat,

isotropic scale factor of the isotropic MAP-MRI basis

sunsigned int

radial moment of the ODF

verticesarray, shape (N,3)

points of the sphere shell in the r-space in which evaluate the ODF

Returns

odf_matMatrix, shape (N_vertices, N_mapmri_coef)

ODF design matrix to discrete sphere function

References

diffusion imaging method for mapping tissue microstructure”, NeuroImage, 2013.

using Laplacian-regularized MAP-MRI and its application to HCP data.” NeuroImage (2016).

mapmri_isotropic_odf_sh_matrix

dipy.reconst.mapmri.mapmri_isotropic_odf_sh_matrix(radial_order, mu, s)

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).

Parameters

radial_orderunsigned int,

an even integer that represent the order of the basis

mufloat,

isotropic scale factor of the isotropic MAP-MRI basis

sunsigned int

radial moment of the ODF

Returns

odf_sh_matMatrix, shape (N_sh_coef, N_mapmri_coef)

ODF design matrix to spherical harmonics

References

diffusion imaging method for mapping tissue microstructure”, NeuroImage, 2013.

using Laplacian-regularized MAP-MRI and its application to HCP data.” NeuroImage (2016).

mapmri_isotropic_laplacian_reg_matrix

dipy.reconst.mapmri.mapmri_isotropic_laplacian_reg_matrix(radial_order, mu)

Computes the Laplacian regularization matrix for MAP-MRI’s isotropic implementation [1]_ eq. (C7).

Parameters

radial_orderunsigned int,

an even integer that represent the order of the basis

mufloat,

isotropic scale factor of the isotropic MAP-MRI basis

Returns

LRMatrix, shape (N_coef, N_coef)

Laplacian regularization matrix

References

using Laplacian-regularized MAP-MRI and its application to HCP data.” NeuroImage (2016).

mapmri_isotropic_laplacian_reg_matrix_from_index_matrix

dipy.reconst.mapmri.mapmri_isotropic_laplacian_reg_matrix_from_index_matrix(ind_mat, mu)

Computes the Laplacian regularization matrix for MAP-MRI’s isotropic implementation [1]_ eq. (C7).

Parameters

ind_matmatrix (N_coef, 3),

Basis order matrix

mufloat,

isotropic scale factor of the isotropic MAP-MRI basis

Returns

LRMatrix, shape (N_coef, N_coef)

Laplacian regularization matrix

References

using Laplacian-regularized MAP-MRI and its application to HCP data.” NeuroImage (2016).

mapmri_isotropic_index_matrix

dipy.reconst.mapmri.mapmri_isotropic_index_matrix(radial_order)

Calculates the indices for the isotropic MAPMRI basis [1]_ Fig 8.

Parameters

radial_orderunsigned int

radial order of isotropic MAPMRI basis

Returns

index_matrixarray, shape (N,3)

ordering of the basis in x, y, z

References

diffusion imaging method for mapping tissue microstructure”, NeuroImage, 2013.

create_rspace

dipy.reconst.mapmri.create_rspace(gridsize, radius_max)

Create the real space table, that contains the points in which to compute the pdf.

Parameters

gridsizeunsigned int

dimension of the propagator grid

radius_maxfloat

maximal radius in which compute the propagator

Returns

tabarray, shape (N,3)

real space points in which calculates the pdf

delta

dipy.reconst.mapmri.delta(n, m)

map_laplace_u

dipy.reconst.mapmri.map_laplace_u(n, m)

S(n, m) static matrix for Laplacian regularization [1]_ eq. (13).

Parameters

n, munsigned int

basis order of the MAP-MRI basis in different directions

Returns

Ufloat,

Analytical integral of \(\phi_n(q) * \phi_m(q)\)

References

using Laplacian-regularized MAP-MRI and its application to HCP data.” NeuroImage (2016).

map_laplace_t

dipy.reconst.mapmri.map_laplace_t(n, m)

L(m, n) static matrix for Laplacian regularization [1]_ eq. (12).

Parameters

n, munsigned int

basis order of the MAP-MRI basis in different directions

Returns

Tfloat

Analytical integral of \(\phi_n(q) * \phi_m''(q)\)

References

using Laplacian-regularized MAP-MRI and its application to HCP data.” NeuroImage (2016).

map_laplace_s

dipy.reconst.mapmri.map_laplace_s(n, m)

R(m,n) static matrix for Laplacian regularization [1]_ eq. (11).

Parameters

n, munsigned int

basis order of the MAP-MRI basis in different directions

Returns

Sfloat

Analytical integral of \(\phi_n''(q) * \phi_m''(q)\)

References

using Laplacian-regularized MAP-MRI and its application to HCP data.” NeuroImage (2016).

mapmri_STU_reg_matrices

dipy.reconst.mapmri.mapmri_STU_reg_matrices(radial_order)

Generate the static portions of the Laplacian regularization matrix according to [1]_ eq. (11, 12, 13).

Parameters

radial_orderunsigned int,

an even integer that represent the order of the basis

Returns

S, T, UMatrices, shape (N_coef,N_coef)

Regularization submatrices

References

using Laplacian-regularized MAP-MRI and its application to HCP data.” NeuroImage (2016).

mapmri_laplacian_reg_matrix

dipy.reconst.mapmri.mapmri_laplacian_reg_matrix(ind_mat, mu, S_mat, T_mat, U_mat)

Put the Laplacian regularization matrix together [1]_ eq. (10).

The static parts in S, T and U are multiplied and divided by the voxel-specific scale factors.

Parameters

ind_matmatrix (N_coef, 3),

Basis order matrix

muarray, shape (3,)

scale factors of the basis for x, y, z

S, T, Umatrices, shape (N_coef,N_coef)

Regularization submatrices

Returns

LRmatrix (N_coef, N_coef),

Voxel-specific Laplacian regularization matrix

References

using Laplacian-regularized MAP-MRI and its application to HCP data.” NeuroImage (2016).

generalized_crossvalidation_array

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.

Parameters

dataarray (N),

Basis order matrix

Mmatrix, shape (N, Ncoef)

mapmri observation matrix

LRmatrix, shape (N_coef, N_coef)

regularization matrix

weights_arrayarray (N_of_weights)

array of optional regularization weights

generalized_crossvalidation

dipy.reconst.mapmri.generalized_crossvalidation(data, M, LR, gcv_startpoint=0.05)

Generalized Cross Validation Function [1]_ eq. (15).

Finds optimal regularization weight based on generalized cross-validation.

Parameters

dataarray (N),

data array

Mmatrix, shape (N, Ncoef)

mapmri observation matrix

LRmatrix, shape (N_coef, N_coef)

regularization matrix

gcv_startpointfloat

startpoint for the gcv optimization

Returns

optimal_lambdafloat,

optimal regularization weight

References

gcv_cost_function

dipy.reconst.mapmri.gcv_cost_function(weight, args)

The GCV cost function that is iterated [4].

MultiShellResponse

class dipy.reconst.mcsd.MultiShellResponse(response, sh_order, shells, S0=None)

Bases: object

__init__(response, sh_order, shells, S0=None)

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.

Parameters

responsendarray

Multi-shell fiber response. The ordering of the responses should follow the same logic as S0.

sh_orderint

Maximal spherical harmonics order.

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.

property iso

MultiShellDeconvModel

class dipy.reconst.mcsd.MultiShellDeconvModel(gtab, response, reg_sphere=<dipy.core.sphere.HemiSphere object>, sh_order=8, iso=2)

Bases: SphHarmModel

__init__(gtab, response, reg_sphere=<dipy.core.sphere.HemiSphere object>, sh_order=8, iso=2)

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]_.

Parameters

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_orderint (optional)

maximal spherical harmonics order. Default: 8

iso: int (optional)

Number of tissue compartments for running the MSMT-CSD. Minimum number of compartments required is 2. Default: 2

References

fit(data, mask=None)

Fit method for every voxel in data

predict(params, gtab=None, S0=None)

Compute a signal prediction given spherical harmonic coefficients for the provided GradientTable class instance.

Parameters

paramsndarray

The spherical harmonic representation of the FOD from which to make the signal prediction.

gtabGradientTable

The gradients for which the signal will be predicted. Use the model’s gradient table by default.

S0ndarray or float

The non diffusion-weighted signal value.

MSDeconvFit

class dipy.reconst.mcsd.MSDeconvFit(model, coeff, mask)

Bases: SphHarmFit

__init__(model, coeff, mask)

Abstract class which holds the fit result of MultiShellDeconvModel. Inherits the SphHarmFit which fits the diffusion data to a spherical harmonic model.

Parameters

model: object

MultiShellDeconvModel

coeffarray

Spherical harmonic coefficients for the ODF.

mask: ndarray

Mask for fitting

property all_shm_coeff
property shm_coeff

The spherical harmonic coefficients of the odf

Make this a property for now, if there is a use case for modifying the coefficients we can add a setter or expose the coefficients more directly

property volume_fractions

QpFitter

class dipy.reconst.mcsd.QpFitter(X, reg)

Bases: object

__init__(X, reg)

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.

Parameters

Xndarray

Matrix to be fit by the QP solver calculated in MultiShellDeconvModel

regndarray

the regularization B matrix calculated in MultiShellDeconvModel

multi_tissue_basis

dipy.reconst.mcsd.multi_tissue_basis(gtab, sh_order, iso_comp)

Builds a basis for multi-shell multi-tissue CSD model.

Parameters

gtab : GradientTable sh_order : int iso_comp: int

Number of tissue compartments for running the MSMT-CSD. Minimum number of compartments required is 2.

Returns

Bndarray

Matrix of the spherical harmonics model used to fit the data

mint |m| <= n

The order of the harmonic.

nint >= 0

The degree of the harmonic.

solve_qp

dipy.reconst.mcsd.solve_qp(P, Q, G, H)

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.

Parameters

Pndarray

n x n matrix for the primal QP objective function.

Qndarray

n x 1 matrix for the primal QP objective function.

Gndarray

m x n matrix for the inequality constraint.

Hndarray

m x 1 matrix for the inequality constraint.

Returns

xarray

Optimal solution to the QP problem.

multi_shell_fiber_response

dipy.reconst.mcsd.multi_shell_fiber_response(sh_order, bvals, wm_rf, gm_rf, csf_rf, sphere=None, tol=20)

Fiber response function estimation for multi-shell data.

Parameters

sh_orderint

Maximum spherical harmonics order.

bvalsndarray

Array containing the b-values. Must be unique b-values, like outputted by dipy.core.gradients.unique_bvals_tolerance.

wm_rf(4, len(bvals)) ndarray

Response function of the WM tissue, for each bvals.

gm_rf(4, len(bvals)) ndarray

Response function of the GM tissue, for each bvals.

csf_rf(4, len(bvals)) ndarray

Response function of the CSF tissue, for each bvals.

spheredipy.core.Sphere instance, optional

Sphere where the signal will be evaluated.

Returns

MultiShellResponse

MultiShellResponse object.

mask_for_response_msmt

dipy.reconst.mcsd.mask_for_response_msmt(gtab, data, roi_center=None, roi_radii=10, wm_fa_thr=0.7, gm_fa_thr=0.2, csf_fa_thr=0.1, gm_md_thr=0.0007, csf_md_thr=0.002)
Computation of masks for multi-shell multi-tissue (msmt) response

function using FA and MD.

Parameters

gtab : GradientTable data : ndarray

diffusion data (4D)

roi_centerarray-like, (3,)

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_radiiint or array-like, (3,)

radii of cuboid ROI

wm_fa_thrfloat

FA threshold for WM.

gm_fa_thrfloat

FA threshold for GM.

csf_fa_thrfloat

FA threshold for CSF.

gm_md_thrfloat

MD threshold for GM.

csf_md_thrfloat

MD threshold for CSF.

Returns

mask_wmndarray

Mask of voxels within the ROI and with FA above the FA threshold for WM.

mask_gmndarray

Mask of voxels within the ROI and with FA below the FA threshold for GM and with MD below the MD threshold for GM.

mask_csfndarray

Mask of voxels within the ROI and with FA below the FA threshold for CSF and with MD below the MD threshold for CSF.

Notes

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.

response_from_mask_msmt

dipy.reconst.mcsd.response_from_mask_msmt(gtab, data, mask_wm, mask_gm, mask_csf, tol=20)
Computation of multi-shell multi-tissue (msmt) response

functions from given tissues masks.

Parameters

gtab : GradientTable data : ndarray

diffusion data

mask_wmndarray

mask from where to compute the WM response function.

mask_gmndarray

mask from where to compute the GM response function.

mask_csfndarray

mask from where to compute the CSF response function.

tolint

tolerance gap for b-values clustering. (Default = 20)

Returns

response_wmndarray, (len(unique_bvals_tolerance(gtab.bvals))-1, 4)

(evals, S0) for WM for each unique bvalues (except b0).

response_gmndarray, (len(unique_bvals_tolerance(gtab.bvals))-1, 4)

(evals, S0) for GM for each unique bvalues (except b0).

response_csfndarray, (len(unique_bvals_tolerance(gtab.bvals))-1, 4)

(evals, S0) for CSF for each unique bvalues (except b0).

Notes

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.

auto_response_msmt

dipy.reconst.mcsd.auto_response_msmt(gtab, data, tol=20, roi_center=None, roi_radii=10, wm_fa_thr=0.7, gm_fa_thr=0.3, csf_fa_thr=0.15, gm_md_thr=0.001, csf_md_thr=0.0032)
Automatic estimation of multi-shell multi-tissue (msmt) response

functions using FA and MD.

Parameters

gtab : GradientTable data : ndarray

diffusion data

roi_centerarray-like, (3,)

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_radiiint or array-like, (3,)

radii of cuboid ROI

wm_fa_thrfloat

FA threshold for WM.

gm_fa_thrfloat

FA threshold for GM.

csf_fa_thrfloat

FA threshold for CSF.

gm_md_thrfloat

MD threshold for GM.

csf_md_thrfloat

MD threshold for CSF.

Returns

response_wmndarray, (len(unique_bvals_tolerance(gtab.bvals))-1, 4)

(evals, S0) for WM for each unique bvalues (except b0).

response_gmndarray, (len(unique_bvals_tolerance(gtab.bvals))-1, 4)

(evals, S0) for GM for each unique bvalues (except b0).

response_csfndarray, (len(unique_bvals_tolerance(gtab.bvals))-1, 4)

(evals, S0) for CSF for each unique bvalues (except b0).

Notes

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).

MeanDiffusionKurtosisModel

class dipy.reconst.msdki.MeanDiffusionKurtosisModel(gtab, bmag=None, return_S0_hat=False, *args, **kwargs)

Bases: ReconstModel

Mean signal Diffusion Kurtosis Model

__init__(gtab, bmag=None, return_S0_hat=False, *args, **kwargs)

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

fit(data, mask=None)

Fit method of the MSDKI model class

Parameters

datandarray ([X, Y, Z, …], g)

ndarray containing the data signals in its last dimension.

maskarray

A boolean array used to mark the coordinates in the data that should be analyzed that has the shape data.shape[:-1]

predict(msdki_params, S0=1.0)

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

MeanDiffusionKurtosisFit

class dipy.reconst.msdki.MeanDiffusionKurtosisFit(model, model_params, model_S0=None)

Bases: object

__init__(model, model_params, model_S0=None)

Initialize a MeanDiffusionKurtosisFit class instance.

property S0_hat
msd()

Mean signal diffusitivity (MSD) calculated from the mean signal Diffusion Kurtosis Model.

Returns

msdndarray

Calculated signal mean diffusitivity.

References

msk()

Mean signal kurtosis (MSK) calculated from the mean signal Diffusion Kurtosis Model.

Returns

mskndarray

Calculated signal mean kurtosis.

References

predict(gtab, S0=1.0)

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

smt2di()

Computes the intrisic diffusivity from the mean signal diffusional kurtosis parameters assuming the 2-compartmental spherical mean technique model [1]_, [2]_

Returns

smt2dindarray

Intrinsic diffusivity computed by converting MSDKI to SMT2.

Notes

Computes the intrinsic diffusivity using equation 16 of [1]_

References

smt2f()

Computes the axonal water fraction from the mean signal kurtosis assuming the 2-compartmental spherical mean technique model [1]_, [2]_

Returns

smt2fndarray

Axonal volume fraction calculated from MSK.

Notes

Computes the axonal water fraction from the mean signal kurtosis MSK using equation 17 of [1]_

References

smt2uFA()

Computes the microscopic fractional anisotropy from the mean signal diffusional kurtosis parameters assuming the 2-compartmental spherical mean technique model [1]_, [2]_

Returns

smt2uFAndarray

Microscopic fractional anisotropy computed by converting MSDKI to SMT2.

Notes

Computes the intrinsic diffusivity using equation 10 of [1]_

References

mean_signal_bvalue

dipy.reconst.msdki.mean_signal_bvalue(data, gtab, bmag=None)

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

msk_from_awf

dipy.reconst.msdki.msk_from_awf(f)

Computes mean signal kurtosis from axonal water fraction estimates of the SMT2 model

Parameters

fndarray ([X, Y, Z, …])

ndarray containing the axonal volume fraction estimate.

Returns

mskndarray(nub)

Mean signal kurtosis (msk)

Notes

Computes mean signal kurtosis using equations 17 of [1]_

References

awf_from_msk

dipy.reconst.msdki.awf_from_msk(msk, mask=None)

Computes the axonal water fraction from the mean signal kurtosis assuming the 2-compartmental spherical mean technique model [1]_, [2]_

Parameters

mskndarray ([X, Y, Z, …])

Mean signal kurtosis (msk)

maskndarray, optional

A boolean array used to mark the coordinates in the data that should be analyzed that has the same shape of the msdki parameters

Returns

smt2fndarray ([X, Y, Z, …])

ndarray containing the axonal volume fraction estimate.

Notes

Computes the axonal water fraction from the mean signal kurtosis MSK using equation 17 of [1]_

References

msdki_prediction

dipy.reconst.msdki.msdki_prediction(msdki_params, gtab, S0=1.0)

Predict the mean signal given the parameters of the mean signal DKI, an GradientTable object and S0 signal. Parameters ———- 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

wls_fit_msdki

dipy.reconst.msdki.wls_fit_msdki(design_matrix, msignal, ng, mask=None, min_signal=0.0001, return_S0_hat=False)

Fits the mean signal diffusion kurtosis imaging based on a weighted least square solution [1]_.

Parameters

design_matrixarray (nub, 3)

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

return_S0_hatbool

If True, also return S0 values for the fit.

Returns

paramsarray (…, 2)

Containing the mean signal diffusivity and mean signal kurtosis

References

design_matrix

dipy.reconst.msdki.design_matrix(ubvals)

Constructs design matrix for the mean signal diffusion kurtosis model

Parameters

ubvalsarray

Containing the unique b-values of the data.

Returns

design_matrixarray (nb, 3)

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)

MultiVoxelFit

class dipy.reconst.multi_voxel.MultiVoxelFit(model, fit_array, mask)

Bases: ReconstFit

Holds an array of fits and allows access to their attributes and methods

__init__(model, fit_array, mask)
predict(*args, **kwargs)

Predict for the multi-voxel object using each single-object’s prediction API, with S0 provided from an array.

property shape

CallableArray

class dipy.reconst.multi_voxel.CallableArray

Bases: ndarray

An array which can be called like a function

__init__()

multi_voxel_fit

dipy.reconst.multi_voxel.multi_voxel_fit(single_voxel_fit)

Method decorator to turn a single voxel model fit definition into a multi voxel model fit definition

OdfModel

class dipy.reconst.odf.OdfModel(gtab)

Bases: ReconstModel

An abstract class to be sub-classed by specific odf models

All odf models should provide a fit method which may take data as it’s first and only argument.

__init__(gtab)

Initialization of the abstract class for signal reconstruction models

Parameters

gtab : GradientTable class instance

fit(data)

To be implemented by specific odf models

OdfFit

class dipy.reconst.odf.OdfFit(model, data)

Bases: ReconstFit

__init__(model, data)
odf(sphere)

To be implemented but specific odf models

gfa

dipy.reconst.odf.gfa(samples)

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.

minmax_normalize

dipy.reconst.odf.minmax_normalize(samples, out=None)

Min-max normalization of a function evaluated on the unit sphere

Normalizes samples to (samples - min(samples)) / (max(samples) - min(samples)) for each unit sphere.

Parameters

samplesndarray (…, N)

N samples on a unit sphere for each point, stored along the last axis of the array.

outndrray (…, N), optional

An array to store the normalized samples.

Returns

outndarray, (…, N)

Normalized samples.

QtdmriModel

class dipy.reconst.qtdmri.QtdmriModel(gtab, radial_order=6, time_order=2, laplacian_regularization=False, laplacian_weighting=0.2, l1_regularization=False, l1_weighting=0.1, cartesian=True, anisotropic_scaling=True, normalization=False, constrain_q0=True, bval_threshold=10000000000.0, eigenvalue_threshold=0.0001, cvxpy_solver='ECOS')

Bases: Cache

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