reconst

bench([label, verbose, extra_argv])

Run benchmarks for module using nose.

test([label, verbose, extra_argv, doctests, ...])

Run tests for module using nose.

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 whenver fitting a particular set of data (different voxels, for example).

ReconstFit(model, data)

Abstract class which holds the fit result of ReconstModel

ReconstModel(gtab)

Abstract class for signal reconstruction models

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

measure(code_str[, times, label])

Return elapsed time for executing code in the namespace of the caller.

Module: reconst.benchmarks.bench_csd

ConstrainedSphericalDeconvModel(gtab, response)

Methods

GradientTable(gradients[, big_delta, ...])

Diffusion gradient information

bench_csdeconv([center, width])

load_nifti_data(fname[, as_ndarray])

Load only the data array from a nifti file.

num_grad(gtab)

read_stanford_labels()

Read stanford hardi data and label map.

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

measure(code_str[, times, label])

Return elapsed time for executing code in the namespace of the caller.

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

bench_quick_squash()

measure(code_str[, times, label])

Return elapsed time for executing code in the namespace of the caller.

ndindex(shape)

An N-dimensional iterator object to index arrays.

old_squash(arr[, mask, fill])

Try and make a standard array from an object array

reduce(function, sequence[, initial])

Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value.

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

measure(code_str[, times, label])

Return elapsed time for executing code in the namespace of the caller.

Module: reconst.cache

Cache()

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

auto_attr(func)

Decorator to create OneTimeProperty attributes.

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

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

Methods

ConstrainedSphericalDeconvModel(gtab, response)

Methods

SphHarmFit(model, shm_coef, mask)

Diffusion data fit to a spherical harmonic model

SphHarmModel(gtab)

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

TensorModel(gtab[, fit_method, return_S0_hat])

Diffusion Tensor

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

Automatic estimation of ssst response function using FA.

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

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

cart2sphere(x, y, z)

Return angles for Cartesian 3D coordinates x, y, and z

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

Constrained-regularized spherical deconvolution (CSD) [1]

deprecate_with_version(message[, since, ...])

Return decorator function function for deprecation warning / error.

deprecated_params(old_name[, new_name, ...])

Deprecate a renamed or removed function argument.

estimate_response(gtab, evals, S0)

Estimate single fiber response function

fa_trace_to_lambdas([fa, trace])

forward_sdeconv_mat(r_rh, n)

Build forward spherical deconvolution matrix

forward_sdt_deconv_mat(ratio, n[, r2_term])

Build forward sharpening deconvolution transform (SDT) matrix

fractional_anisotropy(evals[, axis])

Return Fractional anisotropy (FA) of a diffusion tensor.

get_sphere([name])

provide triangulated spheres

lazy_index(index)

Produces a lazy index

lpn(n, z)

Legendre function of the first kind.

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

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

multi_voxel_fit(single_voxel_fit)

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

ndindex(shape)

An N-dimensional iterator object to index arrays.

odf_deconv(odf_sh, R, B_reg[, lambda_, tau, ...])

ODF constrained-regularized spherical deconvolution using the Sharpening Deconvolution Transform (SDT) [1], [2].

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

Sharpen odfs using the sharpening deconvolution transform [2]

peaks_from_model(model, data, sphere, ...[, ...])

Fit the model to data and computes peaks and metrics

quad(func, a, b[, args, full_output, ...])

Compute a definite integral.

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

Compute real spherical harmonics as in Descoteaux et al. 2007 [Ra6d8f6cd2652-1], where the real harmonic \(Y^m_n\) is defined to be:.

real_sh_descoteaux_from_index(m, n, theta, phi)

Compute real spherical harmonics as in Descoteaux et al. 2007 [R2763a8caef3c-1], where the real harmonic \(Y^m_n\) is defined to be:.

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

Recursive calibration of response function using peak threshold

response_from_mask(gtab, data, mask)

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

response_from_mask_ssst(gtab, data, mask)

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

sh_to_rh(r_sh, m, n)

Spherical harmonics (SH) to rotational harmonics (RH)

single_tensor(gtab[, S0, evals, evecs, snr])

Simulate diffusion-weighted signals with a single tensor.

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.

vec2vec_rotmat(u, v)

rotation matrix from 2 unit vectors

Module: reconst.dki

Classes and functions for fitting the diffusion kurtosis model

DiffusionKurtosisFit(model, model_params)

Class for fitting the Diffusion Kurtosis Model

DiffusionKurtosisModel(gtab[, fit_method])

Class for the Diffusion Kurtosis Model

ReconstModel(gtab)

Abstract class for signal reconstruction models

TensorFit(model, model_params[, model_S0])

Attributes

Wcons(k_elements)

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

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)

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

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

Calculates the apparent kurtosis coefficient (AKC) in each direction of a sphere [1].

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

Computes axial Kurtosis (AK) from the kurtosis tensor [1], [2].

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

Computes the Carlson's incomplete elliptic integral of the second kind defined as:

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

Computes the Carlson's incomplete elliptic integral of the first kind defined as:

cart2sphere(x, y, z)

Return angles for Cartesian 3D coordinates x, y, and z

check_multi_b(gtab, n_bvals[, non_zero, bmag])

Check if you have enough different b-values in your gradient table

decompose_tensor(tensor[, min_diffusivity])

Returns eigenvalues and eigenvectors given a diffusion tensor

design_matrix(gtab)

Construct B design matrix for DKI.

directional_diffusion(dt, V[, min_diffusivity])

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

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

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

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

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

dki_prediction(dki_params, gtab[, S0])

Predict a signal given diffusion kurtosis imaging parameters.

from_lower_triangular(D)

Returns a tensor given the six unique tensor elements

get_fnames([name])

Provide full paths to example or test datasets.

get_sphere([name])

provide triangulated spheres

kurtosis_fractional_anisotropy(dki_params)

Computes the anisotropy of the kurtosis tensor (KFA) [1].

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

Computes kurtosis maximum value

local_maxima

Local maxima of a function evaluated on a discrete set of points.

lower_triangular(tensor[, b0])

Returns the six lower triangular values of the tensor and a dummy variable if b0 is not None

mean_diffusivity(evals[, axis])

Mean Diffusivity (MD) of a diffusion tensor.

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

Computes mean Kurtosis (MK) from the kurtosis tensor.

mean_kurtosis_tensor(dki_params[, ...])

Computes mean of the kurtosis tensor (MKT) [1].

ndindex(shape)

An N-dimensional iterator object to index arrays.

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

Fit the cumulant expansion params (e.g.

ols_fit_dki(design_matrix, data)

Computes the diffusion and kurtosis tensors using an ordinary linear least squares (OLS) approach 1.

perpendicular_directions(v[, num, half])

Computes n evenly spaced perpendicular directions relative to a given vector v

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

Radial Kurtosis (RK) of a diffusion kurtosis tensor [1], [2].

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

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

sphere2cart(r, theta, phi)

Spherical to Cartesian coordinates

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

vec_val_vect

Vectorize vecs.diag(vals).`vecs`.T for last 2 dimensions of vecs

wls_fit_dki(design_matrix, data)

Computes the diffusion and kurtosis tensors using a weighted linear least squares (WLS) approach 1.

Module: reconst.dki_micro

Classes and functions for fitting the DKI-based microstructural model

DiffusionKurtosisFit(model, model_params)

Class for fitting the Diffusion Kurtosis Model

DiffusionKurtosisModel(gtab[, fit_method])

Class for the Diffusion Kurtosis Model

KurtosisMicrostructuralFit(model, model_params)

Class for fitting the Diffusion Kurtosis Microstructural Model

KurtosisMicrostructureModel(gtab[, fit_method])

Class for the Diffusion Kurtosis Microstructural Model

axial_diffusivity(evals[, axis])

Axial Diffusivity (AD) of a diffusion tensor.

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

Computes the axonal water fraction from DKI [1].

decompose_tensor(tensor[, min_diffusivity])

Returns eigenvalues and eigenvectors given a diffusion tensor

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

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

directional_diffusion(dt, V[, min_diffusivity])

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

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

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

dkimicro_prediction(params, gtab[, S0])

Signal prediction given the DKI microstructure model parameters.

dti_design_matrix(gtab[, dtype])

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

from_lower_triangular(D)

Returns a tensor given the six unique tensor elements

get_sphere([name])

provide triangulated spheres

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

Computes kurtosis maximum value

lower_triangular(tensor[, b0])

Returns the six lower triangular values of the tensor and a dummy variable if b0 is not None

mean_diffusivity(evals[, axis])

Mean Diffusivity (MD) of a diffusion tensor.

ndindex(shape)

An N-dimensional iterator object to index arrays.

radial_diffusivity(evals[, axis])

Radial Diffusivity (RD) of a diffusion tensor.

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

tortuosity(hindered_ad, hindered_rd)

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

trace(evals[, axis])

Trace of a diffusion tensor.

vec_val_vect

Vectorize vecs.diag(vals).`vecs`.T for last 2 dimensions of vecs

Module: reconst.dsi

Cache()

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

DiffusionSpectrumDeconvFit(model, data)

Methods

DiffusionSpectrumDeconvModel(gtab[, ...])

Methods

DiffusionSpectrumFit(model, data)

Methods

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

Methods

OdfFit(model, data)

Methods

OdfModel(gtab)

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

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

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

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

fftn(x[, shape, axes, overwrite_x])

Return multidimensional discrete Fourier transform.

fftshift(x[, axes])

Shift the zero-frequency component to the center of the spectrum.

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.

half_to_full_qspace(data, gtab)

Half to full Cartesian grid mapping

hanning_filter(gtab, filter_width, origin)

create a hanning window

ifftshift(x[, axes])

The inverse of fftshift.

map_coordinates(input, coordinates[, ...])

Map the input array to new coordinates by interpolation.

multi_voxel_fit(single_voxel_fit)

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

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

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.

Module: reconst.dti

Classes and functions for fitting tensors

ReconstModel(gtab)

Abstract class for signal reconstruction models

TensorFit(model, model_params[, model_S0])

Attributes

TensorModel(gtab[, fit_method, return_S0_hat])

Diffusion Tensor

apparent_diffusion_coef(q_form, sphere)

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

auto_attr(func)

Decorator to create OneTimeProperty attributes.

axial_diffusivity(evals[, axis])

Axial Diffusivity (AD) of a diffusion tensor.

color_fa(fa, evecs)

Color fractional anisotropy of diffusion tensor

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.

determinant(q_form)

The determinant of a tensor, given in quadratic form

deviatoric(q_form)

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

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.

fractional_anisotropy(evals[, axis])

Return Fractional anisotropy (FA) of a diffusion tensor.

from_lower_triangular(D)

Returns a tensor given the six unique tensor elements

geodesic_anisotropy(evals[, axis])

Geodesic anisotropy (GA) of a diffusion tensor.

get_sphere([name])

provide triangulated spheres

gradient_table(bvals[, bvecs, big_delta, ...])

A general function for creating diffusion MR gradients.

isotropic(q_form)

Calculate the isotropic part of the tensor [1].

iter_fit_tensor([step])

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

linearity(evals[, axis])

The linearity of the tensor [1]

lower_triangular(tensor[, b0])

Returns the six lower triangular values of the tensor and a dummy variable if b0 is not None

mean_diffusivity(evals[, axis])

Mean Diffusivity (MD) of a diffusion tensor.

mode(q_form)

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

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

Fit the cumulant expansion params (e.g.

norm(q_form)

Calculate the Frobenius norm of a tensor quadratic form

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

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

pinv(a[, rcond])

Vectorized version of numpy.linalg.pinv

planarity(evals[, axis])

The planarity of the tensor [1]

quantize_evecs(evecs[, odf_vertices])

Find the closest orientation of an evenly distributed sphere

radial_diffusivity(evals[, axis])

Radial Diffusivity (RD) of a diffusion tensor.

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

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

sphericity(evals[, axis])

The sphericity of the tensor [1]

tensor_prediction(dti_params, gtab, S0)

Predict a signal given tensor parameters.

trace(evals[, axis])

Trace of a diffusion tensor.

vec_val_vect

Vectorize vecs.diag(vals).`vecs`.T for last 2 dimensions of vecs

vector_norm(vec[, axis, keepdims])

Return vector Euclidean (L2) norm

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

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

Module: reconst.eudx_direction_getter

EuDXDirectionGetter

Deterministic Direction Getter based on peak directions.

Module: reconst.forecast

Cache()

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

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

Attributes

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

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

OdfFit(model, data)

Methods

OdfModel(gtab)

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

Version(version)

Attributes

cart2sphere(x, y, z)

Return angles for Cartesian 3D coordinates x, y, and z

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

Constrained-regularized spherical deconvolution (CSD) [1]

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

forecast_matrix(sh_order, d_par, d_perp, bvals)

Compute the FORECAST radial matrix

lb_forecast(sh_order)

Returns the Laplace-Beltrami regularization matrix for FORECAST

leastsq(func, x0[, args, Dfun, full_output, ...])

Minimize the sum of squares of a set of equations.

multi_voxel_fit(single_voxel_fit)

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

optional_package(name[, trip_msg])

Return package-like thing and module setup for package name

psi_l(l, b)

real_sh_descoteaux_from_index(m, n, theta, phi)

Compute real spherical harmonics as in Descoteaux et al. 2007 [Rded9a56186a6-1], where the real harmonic \(Y^m_n\) is defined to be:.

rho_matrix(sh_order, vecs)

Compute the SH matrix \(\rho\)

warn(/, message[, category, stacklevel, source])

Issue a warning, or maybe ignore it or raise an exception.

Module: reconst.fwdti

Classes and functions for fitting tensors without free water contamination

FreeWaterTensorFit(model, model_params)

Class for fitting the Free Water Tensor Model

FreeWaterTensorModel(gtab[, fit_method])

Class for the Free Water Elimination Diffusion Tensor Model

ReconstModel(gtab)

Abstract class for signal reconstruction models

TensorFit(model, model_params[, model_S0])

Attributes

check_multi_b(gtab, n_bvals[, non_zero, bmag])

Check if you have enough different b-values in your gradient table

cholesky_to_lower_triangular(R)

Convert Cholesky decompostion elements to the diffusion tensor elements

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.

from_lower_triangular(D)

Returns a tensor given the six unique tensor elements

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

Signal prediction given the free water DTI model parameters.

lower_triangular(tensor[, b0])

Returns the six lower triangular values of the tensor and a dummy variable if b0 is not None

lower_triangular_to_cholesky(tensor_elements)

Performs Cholesky decomposition of the diffusion tensor

multi_voxel_fit(single_voxel_fit)

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

ndindex(shape)

An N-dimensional iterator object to index arrays.

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

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

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

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

vec_val_vect

Vectorize vecs.diag(vals).`vecs`.T for last 2 dimensions of vecs

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

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

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

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

Module: reconst.gqi

Classes and functions for generalized q-sampling

Cache()

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

GeneralizedQSamplingFit(model, data)

Methods

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

Methods

OdfFit(model, data)

Methods

OdfModel(gtab)

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

equatorial_maximum(vertices, odf, pole, width)

equatorial_zone_vertices(vertices, pole[, width])

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

multi_voxel_fit(single_voxel_fit)

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

normalize_qa(qa[, max_qa])

Normalize quantitative anisotropy.

npa(self, odf[, width])

non-parametric anisotropy

odf_sum(odf)

patch_maximum(vertices, odf, pole, width)

patch_sum(vertices, odf, pole, width)

patch_vertices(vertices, pole, width)

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

polar_zone_vertices(vertices, pole[, width])

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

squared_radial_component(x[, tol])

Part of the GQI2 integral

triple_odf_maxima(vertices, odf, width)

upper_hemi_map(v)

maps a 3-vector into the z-upper hemisphere

Module: reconst.ivim

Classes and functions for fitting ivim model

IvimFit(model, model_params)

Attributes

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

Ivim model

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

Methods

ReconstModel(gtab)

Abstract class for signal reconstruction models

Version(version)

Attributes

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

differential_evolution(func, bounds[, args, ...])

Finds the global minimum of a multivariate function.

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

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

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.

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.

ivim_prediction(params, gtab)

The Intravoxel incoherent motion (IVIM) model function.

least_squares(fun, x0[, jac, bounds, ...])

Solve a nonlinear least-squares problem with bounds on the variables.

multi_voxel_fit(single_voxel_fit)

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

optional_package(name[, trip_msg])

Return package-like thing and module setup for package name

Module: reconst.mapmri

Cache()

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

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

Attributes

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

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

Optimizer(fun, x0[, args, method, jac, ...])

Attributes

ReconstFit(model, data)

Abstract class which holds the fit result of ReconstModel

ReconstModel(gtab)

Abstract class for signal reconstruction models

Version(version)

Attributes

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.

binomialfloat(n, k)

Custom Binomial function

cart2sphere(x, y, z)

Return angles for Cartesian 3D coordinates x, y, and z

create_rspace(gridsize, radius_max)

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

delta(n, m)

factorial2(n[, exact])

Double factorial.

gcv_cost_function(weight, args)

The GCV cost function that is iterated [4].

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

Generalized Cross Validation Function [Rb690cd738504-1] eq.

generalized_crossvalidation_array(data, M, LR)

Generalized Cross Validation Function 1 eq.

genlaguerre(n, alpha[, monic])

Generalized (associated) Laguerre polynomial.

gradient_table(bvals[, bvecs, big_delta, ...])

A general function for creating diffusion MR gradients.

hermite(n[, monic])

Physicist's Hermite polynomial.

isotropic_scale_factor(mu_squared)

Estimated isotropic scaling factor _[1] Eq.

map_laplace_s(n, m)

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

map_laplace_t(n, m)

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

map_laplace_u(n, m)

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

mapmri_STU_reg_matrices(radial_order)

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

mapmri_index_matrix(radial_order)

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

mapmri_isotropic_K_mu_dependent(...)

Computes mu dependent part of M.

mapmri_isotropic_K_mu_independent(...)

Computes mu independent part of K.

mapmri_isotropic_M_mu_dependent(...)

Computed the mu dependent part of the signal design matrix.

mapmri_isotropic_M_mu_independent(...)

Computed the mu independent part of the signal design matrix.

mapmri_isotropic_index_matrix(radial_order)

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

mapmri_isotropic_laplacian_reg_matrix(...)

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

mapmri_isotropic_laplacian_reg_matrix_from_index_matrix(...)

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

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_phi_matrix(radial_order, mu, q)

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

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_radial_signal_basis(j, l, ...)

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

mapmri_laplacian_reg_matrix(ind_mat, mu, ...)

Put the Laplacian regularization matrix together [Rc66aaccd07c1-1] eq.

mapmri_odf_matrix(radial_order, mu, s, vertices)

Compute the MAPMRI ODF matrix [1] Eq.

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.

mfactorial(x, /)

Find x!.

multi_voxel_fit(single_voxel_fit)

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

optional_package(name[, trip_msg])

Return package-like thing and module setup for package name

real_sh_descoteaux_from_index(m, n, theta, phi)

Compute real spherical harmonics as in Descoteaux et al. 2007 [R85c991cbd5ae-1], where the real harmonic \(Y^m_n\) is defined to be:.

sfactorial(n[, exact])

The factorial of a number or array of numbers.

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.

warn(/, message[, category, stacklevel, source])

Issue a warning, or maybe ignore it or raise an exception.

Module: reconst.mcsd

GradientTable(gradients[, big_delta, ...])

Diffusion gradient information

MSDeconvFit(model, coeff, mask)

Attributes

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

Methods

MultiShellResponse(response, sh_order, shells)

Attributes

QpFitter(X, reg)

Methods

TensorModel(gtab[, fit_method, return_S0_hat])

Diffusion Tensor

Version(version)

Attributes

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

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

fractional_anisotropy(evals[, axis])

Return Fractional anisotropy (FA) of a diffusion tensor.

get_bval_indices(bvals, bval[, tol])

Get indices where the b-value is bval

gradient_table(bvals[, bvecs, big_delta, ...])

A general function for creating diffusion MR gradients.

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

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

mean_diffusivity(evals[, axis])

Mean Diffusivity (MD) of a diffusion tensor.

multi_shell_fiber_response(sh_order, bvals, ...)

Fiber response function estimation for multi-shell data.

multi_tissue_basis(gtab, sh_order, iso_comp)

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

multi_voxel_fit(single_voxel_fit)

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

optional_package(name[, trip_msg])

Return package-like thing and module setup for package name

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

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

response_from_mask_ssst(gtab, data, mask)

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

single_tensor(gtab[, S0, evals, evecs, snr])

Simulate diffusion-weighted signals with a single tensor.

solve_qp(P, Q, G, H)

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

unique_bvals_tolerance(bvals[, tol])

Gives the unique b-values of the data, within a tolerance gap

Module: reconst.msdki

Classes and functions for fitting the mean signal diffusion kurtosis model

MeanDiffusionKurtosisFit(model, model_params)

Attributes

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

Mean signal Diffusion Kurtosis Model

ReconstModel(gtab)

Abstract class for signal reconstruction models

auto_attr(func)

Decorator to create OneTimeProperty attributes.

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]

check_multi_b(gtab, n_bvals[, non_zero, bmag])

Check if you have enough different b-values in your gradient table

design_matrix(ubvals)

Constructs design matrix for the mean signal diffusion kurtosis model

mean_signal_bvalue(data, gtab[, bmag])

Computes the average signal across different diffusion directions for each unique b-value

msdki_prediction(msdki_params, gtab[, S0])

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

msk_from_awf(f)

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

ndindex(shape)

An N-dimensional iterator object to index arrays.

round_bvals(bvals[, bmag])

"This function rounds the b-values

unique_bvals_magnitude(bvals[, bmag, rbvals])

This function gives the unique rounded b-values of the data

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

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

Module: reconst.multi_voxel

Tools to easily make multi voxel models

CallableArray

An array which can be called like a function

MultiVoxelFit(model, fit_array, mask)

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

ReconstFit(model, data)

Abstract class which holds the fit result of ReconstModel

tqdm(*_, **__)

Decorate an iterable object, returning an iterator which acts exactly like the original iterable, but prints a dynamically updating progressbar every time a value is requested.

as_strided(x[, shape, strides, subok, writeable])

Create a view into the array with the given shape and strides.

multi_voxel_fit(single_voxel_fit)

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

ndindex(shape)

An N-dimensional iterator object to index arrays.

Module: reconst.odf

OdfFit(model, data)

Methods

OdfModel(gtab)

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

ReconstFit(model, data)

Abstract class which holds the fit result of ReconstModel

ReconstModel(gtab)

Abstract class for signal reconstruction models

gfa(samples)

The general fractional anisotropy of a function evaluated on the unit sphere

minmax_normalize(samples[, out])

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

Module: reconst.qtdmri

Cache()

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

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

Methods

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

Version(version)

Attributes

GCV_cost_function(weight, arguments)

Generalized Cross Validation Function that is iterated [1].

H(value)

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

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

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

Angular basis independent of spatial scaling factor us.

cart2sphere(x, y, z)

Return angles for Cartesian 3D coordinates x, y, and z

create_rt_space_grid(grid_size_r, ...)

Generates EAP grid (for potential positivity constraint).

design_matrix_spatial(bvecs, qvals)

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

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.

factorial(n[, exact])

The factorial of a number or array of numbers.

factorial2(n[, exact])

Double factorial.

fmin_l_bfgs_b(func, x0[, fprime, args, ...])

Minimize a function func using the L-BFGS-B algorithm.

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

Generalized Cross Validation Function [1].

genlaguerre(n, alpha[, monic])

Generalized (associated) Laguerre polynomial.

gradient_table_from_gradient_strength_bvecs(...)

A general function for creating diffusion MR gradients.

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

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

multi_voxel_fit(single_voxel_fit)

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

optional_package(name[, trip_msg])

Return package-like thing and module setup for package name

part1_reg_matrix_tau(ind_mat, ut)

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

part23_iso_reg_matrix_q(ind_mat, us)

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

part23_reg_matrix_q(ind_mat, U_mat, T_mat, us)

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

part23_reg_matrix_tau(ind_mat, ut)

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

part4_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_reg_matrix_tau(ind_mat, ut)

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

qtdmri_anisotropic_scaling(data, q, bvecs, tau)

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

qtdmri_eap_matrix(radial_order, time_order, ...)

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

qtdmri_eap_matrix_(radial_order, time_order, ...)

qtdmri_index_matrix(radial_order, time_order)

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

qtdmri_isotropic_eap_matrix(radial_order, ...)

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

qtdmri_isotropic_eap_matrix_(radial_order, ...)

qtdmri_isotropic_index_matrix(radial_order, ...)

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

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

Computes the spherical qt-dMRI Laplacian regularization matrix.

qtdmri_isotropic_scaling(data, q, tau)

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

qtdmri_isotropic_signal_matrix(radial_order, ...)

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

qtdmri_isotropic_to_mapmri_matrix(...)

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

qtdmri_laplacian_reg_matrix(ind_mat, us, ut)

Computes the cartesian qt-dMRI Laplacian regularization matrix.

qtdmri_mapmri_isotropic_normalization(j, l, u0)

Normalization factor for Spherical MAP-MRI basis.

qtdmri_mapmri_normalization(mu)

Normalization factor for Cartesian MAP-MRI basis.

qtdmri_number_of_coefficients(radial_order, ...)

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

qtdmri_signal_matrix(radial_order, ...)

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

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

Function to generate the qtdmri signal basis.

qtdmri_temporal_normalization(ut)

Normalization factor for the temporal basis

qtdmri_to_mapmri_matrix(radial_order, ...)

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

radial_basis_EAP_opt(j, l, us, r)

radial_basis_opt(j, l, us, q)

Spatial basis dependent on spatial scaling factor us

real_sh_descoteaux_from_index(m, n, theta, phi)

Compute real spherical harmonics as in Descoteaux et al. 2007 [R6e399bd6d05a-1], where the real harmonic \(Y^m_n\) is defined to be:.

temporal_basis(o, ut, tau)

Temporal basis dependent on temporal scaling factor ut

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

warn(/, message[, category, stacklevel, source])

Issue a warning, or maybe ignore it or raise an exception.

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

QtiFit(params)

Methods

QtiModel(gtab[, fit_method])

Methods

ReconstModel(gtab)

Abstract class for signal reconstruction models

auto_attr(func)

Decorator to create OneTimeProperty attributes.

design_matrix(btens)

Calculate the design matrix from the b-tensors.

dtd_covariance(DTD)

Calculate covariance of a diffusion tensor distribution (DTD).

from_21x1_to_6x6(V)

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

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.

ndindex(shape)

An N-dimensional iterator object to index arrays.

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

Generate signals using the covariance tensor signal representation.

warn(/, message[, category, stacklevel, source])

Issue a warning, or maybe ignore it or raise an exception.

Module: reconst.quick_squash

Detect common dtype across object array

quick_squash

Try and make a standard array from an object array

reduce(function, sequence[, initial])

Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value.

Module: reconst.recspeed

Optimized routines for creating voxel diffusion models

adj_to_countarrs

Convert adjacency sequence to counts and flattened indices

argmax_from_adj

Indices of local maxima from vals given adjacent points

argmax_from_countarrs

Indices of local maxima from vals from count, array neighbors

le_to_odf

odf for interpolated Laplacian normalized signal

local_maxima

Local maxima of a function evaluated on a discrete set of points.

proc_reco_args

remove_similar_vertices

Remove vertices that are less than theta degrees from any other

search_descending

i in descending array a so a[i] < a[0] * relative_threshold

sum_on_blocks_1d

Summations on blocks of 1d array

Module: reconst.rumba

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

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

OdfFit(model, data)

Methods

OdfModel(gtab)

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

RumbaFit(model, model_params)

Methods

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

Methods

Sphere([x, y, z, theta, phi, xyz, faces, edges])

Points on the unit sphere.

all_tensor_evecs(e0)

Given the principle tensor axis, return the array of all eigenvectors column-wise (or, the rotation matrix that orientates the tensor).

auto_attr(func)

Decorator to create OneTimeProperty attributes.

bounding_box(vol)

Compute the bounding box of nonzero intensity voxels in the volume.

crop(vol, mins, maxs)

Crops the input volume.

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

Generate deconvolution kernel

get_bval_indices(bvals, bval[, tol])

Get indices where the b-value is bval

get_sphere([name])

provide triangulated spheres

gradient_table(bvals[, bvecs, big_delta, ...])

A general function for creating diffusion MR gradients.

lazy_index(index)

Produces a lazy index

mbessel_ratio(n, x)

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

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

Normalizes the data with respect to the mean b0

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

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

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

Fit fODF for all voxels simultaneously using RUMBA-SD.

single_tensor(gtab[, S0, evals, evecs, snr])

Simulate diffusion-weighted signals with a single tensor.

unique_bvals_tolerance(bvals[, tol])

Gives the unique b-values of the data, within a tolerance gap

vec2vec_rotmat(u, v)

rotation matrix from 2 unit vectors

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.

Cache()

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

ExponentialIsotropicFit(model, params)

A fit to the ExponentialIsotropicModel object, based on data.

ExponentialIsotropicModel(gtab)

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

IsotropicFit(model, params)

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

IsotropicModel(gtab)

A base-class for the representation of isotropic signals.

OrderedDict

Dictionary that remembers insertion order

ReconstFit(model, data)

Abstract class which holds the fit result of ReconstModel

ReconstModel(gtab)

Abstract class for signal reconstruction models

SparseFascicleFit(model, beta, S0, iso)

Methods

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

Methods

auto_attr(func)

Decorator to create OneTimeProperty attributes.

determine_num_processes(num_processes)

Determine the effective number of processes for parallelization.

nanmean(a[, axis, dtype, out, keepdims, where])

Compute the arithmetic mean along the specified axis, ignoring NaNs.

optional_package(name[, trip_msg])

Return package-like thing and module setup for package name

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

1

Aganj, I., et al. 2009. ODF Reconstruction in Q-Ball Imaging With Solid Angle Consideration.

2

Descoteaux, M., et al. 2007. Regularized, fast, and robust analytical Q-ball imaging.

3

Tristan-Vega, A., et al. 2010. A new methodology for estimation of fiber populations in white matter of the brain with Funk-Radon transform.

4

Tristan-Vega, A., et al. 2009. Estimation of fiber orientation probability density functions in high angular resolution diffusion imaging.

Note about the Transpose: In the literature the matrix representation of these methods is often written as Y = Bx where B is some design matrix and Y and x are column vectors. In our case the input data, a dwi stored as a nifti file for example, is stored as row vectors (ndarrays) of the form (x, y, z, n), where n is the number of diffusion directions. We could transpose and reshape the data to be (n, x*y*z), so that we could directly plug it into the above equation. However, I have chosen to keep the data as is and implement the relevant equations rewritten in the following form: Y.T = x.T B.T, or in python syntax data = np.dot(sh_coef, B.T) where data is Y.T and sh_coef is x.T.

Cache()

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

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

Implementation of Constant Solid Angle reconstruction method.

OdfFit(model, data)

Methods

OdfModel(gtab)

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

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

Implementation of Orientation Probability Density Transform reconstruction method.

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

To be subclassed by Qball type models.

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

SphHarmFit(model, shm_coef, mask)

Diffusion data fit to a spherical harmonic model

SphHarmModel(gtab)

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

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

Calculate anisotropic power map with a given SH coefficient matrix.

auto_attr(func)

Decorator to create OneTimeProperty attributes.

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

calculate_max_order(n_coeffs[, full_basis])

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

cart2sphere(x, y, z)

Return angles for Cartesian 3D coordinates x, y, and z

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 [R8020d68d5dcd-2]_[R8020d68d5dcd-3]_ bases.

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_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 [R2032a14b59d6-2]_[R2032a14b59d6-3]_ bases.

deprecate_with_version(message[, since, ...])

Return decorator function function for deprecation warning / error.

forward_sdeconv_mat(r_rh, n)

Build forward spherical deconvolution matrix

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

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

hat(B)

Returns the hat matrix for the design matrix B

lazy_index(index)

Produces a lazy index

lcr_matrix(H)

Returns a matrix for computing leveraged, centered residuals from data

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

Normalizes the data with respect to the mean b0

order_from_ncoef(ncoef[, full_basis])

Given a number n of coefficients, calculate back the sh_order

randint(low[, high, size, dtype])

Return random integers from low (inclusive) to high (exclusive).

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

Compute real spherical harmonics as in Descoteaux et al. 2007 [R191e35d27b5b-1], where the real harmonic \(Y^m_n\) is defined to be:.

real_sh_descoteaux_from_index(m, n, theta, phi)

Compute real spherical harmonics as in Descoteaux et al. 2007 [R700bd48b1688-1], where the real harmonic \(Y^m_n\) is defined to be:.

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_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_sph_harm(m, n, theta, phi)

Compute real spherical harmonics.

real_sym_sh_basis(sh_order, theta, phi)

Samples a real symmetric spherical harmonic basis at point on the sphere

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

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

Spherical function to spherical harmonics (SH).

sh_to_rh(r_sh, m, n)

Spherical harmonics (SH) to rotational harmonics (RH)

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

smooth_pinv(B, L)

Regularized pseudo-inverse

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.

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

Compute spherical harmonics.

warn(/, message[, category, stacklevel, source])

Issue a warning, or maybe ignore it or raise an exception.

Module: reconst.shore

Cache()

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

ShoreFit(model, shore_coef)

Attributes

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

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

Version(version)

Attributes

cart2sphere(x, y, z)

Return angles for Cartesian 3D coordinates x, y, and z

create_rspace(gridsize, radius_max)

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

factorial(x, /)

Find x!.

genlaguerre(n, alpha[, monic])

Generalized (associated) Laguerre polynomial.

l_shore(radial_order)

Returns the angular regularisation matrix for SHORE basis

multi_voxel_fit(single_voxel_fit)

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

n_shore(radial_order)

Returns the angular regularisation matrix for SHORE basis

optional_package(name[, trip_msg])

Return package-like thing and module setup for package name

real_sh_descoteaux_from_index(m, n, theta, phi)

Compute real spherical harmonics as in Descoteaux et al. 2007 [Rf0cd5775fa0d-1], where the real harmonic \(Y^m_n\) is defined to be:.

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}

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

Compute the SHORE matrix for modified Merlet's 3D-SHORE [1]

shore_matrix_odf(radial_order, zeta, ...)

Compute the SHORE ODF matrix [1]"

shore_matrix_pdf(radial_order, zeta, rtab)

Compute the SHORE propagator matrix [1]"

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.

warn(/, message[, category, stacklevel, source])

Issue a warning, or maybe ignore it or raise an exception.

Module: reconst.utils

dki_design_matrix(gtab)

Construct B design matrix for DKI.

Module: reconst.vec_val_sum

vec_val_vect

Vectorize vecs.diag(vals).`vecs`.T for last 2 dimensions of vecs

bench

dipy.reconst.bench(label='fast', verbose=1, extra_argv=None)

Run benchmarks for module using nose.

Parameters
label{‘fast’, ‘full’, ‘’, attribute identifier}, optional

Identifies the benchmarks to run. This can be a string to pass to the nosetests executable with the ‘-A’ option, or one of several special values. Special values are:

  • ‘fast’ - the default - which corresponds to the nosetests -A option of ‘not slow’.

  • ‘full’ - fast (as above) and slow benchmarks as in the ‘no -A’ option to nosetests - this is the same as ‘’.

  • None or ‘’ - run all tests.

  • attribute_identifier - string passed directly to nosetests as ‘-A’.

verboseint, optional

Verbosity value for benchmark outputs, in the range 1-10. Default is 1.

extra_argvlist, optional

List with any extra arguments to pass to nosetests.

Returns
successbool

Returns True if running the benchmarks works, False if an error occurred.

Notes

Benchmarks are like tests, but have names starting with “bench” instead of “test”, and can be found under the “benchmarks” sub-directory of the module.

Each NumPy module exposes bench in its namespace to run all benchmarks for it.

Examples

>>> success = np.lib.bench() 
Running benchmarks for numpy.lib
...
using 562341 items:
unique:
0.11
unique1d:
0.11
ratio: 1.0
nUnique: 56230 == 56230
...
OK
>>> success 
True

test

dipy.reconst.test(label='fast', verbose=1, extra_argv=None, doctests=False, coverage=False, raise_warnings=None, timer=False)

Run tests for module using nose.

Parameters
label{‘fast’, ‘full’, ‘’, attribute identifier}, optional

Identifies the tests to run. This can be a string to pass to the nosetests executable with the ‘-A’ option, or one of several special values. Special values are:

  • ‘fast’ - the default - which corresponds to the nosetests -A option of ‘not slow’.

  • ‘full’ - fast (as above) and slow tests as in the ‘no -A’ option to nosetests - this is the same as ‘’.

  • None or ‘’ - run all tests.

  • attribute_identifier - string passed directly to nosetests as ‘-A’.

verboseint, optional

Verbosity value for test outputs, in the range 1-10. Default is 1.

extra_argvlist, optional

List with any extra arguments to pass to nosetests.

doctestsbool, optional

If True, run doctests in module. Default is False.

coveragebool, optional

If True, report coverage of NumPy code. Default is False. (This requires the coverage module).

raise_warningsNone, str or sequence of warnings, optional

This specifies which warnings to configure as ‘raise’ instead of being shown once during the test execution. Valid strings are:

  • “develop” : equals (Warning,)

  • “release” : equals (), do not raise on any warnings.

timerbool or int, optional

Timing of individual tests with nose-timer (which needs to be installed). If True, time tests and report on all of them. If an integer (say N), report timing results for N slowest tests.

Returns
resultobject

Returns the result of running the tests as a nose.result.TextTestResult object.

Notes

Each NumPy module exposes test in its namespace to run all tests for it. For example, to run all tests for numpy.lib:

>>> np.lib.test() 

Examples

>>> result = np.lib.test() 
Running unit tests for numpy.lib
...
Ran 976 tests in 3.933s

OK

>>> result.errors 
[]
>>> result.knownfail 
[]

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)

ReconstModel

class dipy.reconst.base.ReconstModel(gtab)

Bases: object

Abstract class for signal reconstruction models

Methods

fit

__init__(gtab)

Initialization of the abstract class for signal reconstruction models

Parameters
gtabGradientTable class instance
fit(data, mask=None, **kwargs)

bench_bounding_box

dipy.reconst.benchmarks.bench_bounding_box.bench_bounding_box()

measure

dipy.reconst.benchmarks.bench_bounding_box.measure(code_str, times=1, label=None)

Return elapsed time for executing code in the namespace of the caller.

The supplied code string is compiled with the Python builtin compile. The precision of the timing is 10 milli-seconds. If the code will execute fast on this timescale, it can be executed many times to get reasonable timing accuracy.

Parameters
code_strstr

The code to be timed.

timesint, optional

The number of times the code is executed. Default is 1. The code is only compiled once.

labelstr, optional

A label to identify code_str with. This is passed into compile as the second argument (for run-time error messages).

Returns
elapsedfloat

Total elapsed time in seconds for executing code_str times times.

Examples

>>> times = 10
>>> etime = np.testing.measure('for i in range(1000): np.sqrt(i**2)', times=times)
>>> print("Time for a single execution : ", etime / times, "s")  
Time for a single execution :  0.005 s

ConstrainedSphericalDeconvModel

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

Bases: dipy.reconst.shm.SphHarmModel

Methods

cache_clear()

Clear the cache.

cache_get(tag, key[, default])

Retrieve a value from the cache.

cache_set(tag, key, value)

Store a value in the cache.

fit(data[, mask])

Fit method for every voxel in data

predict(sh_coeff[, gtab, S0])

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

sampling_matrix(sphere)

The matrix needed to sample ODFs from coefficients of the model.

__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
gtabGradientTable
responsetuple 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

1(1,2,3,4,5)

Tournier, J.D., et al. NeuroImage 2007. Robust determination of the fibre orientation distribution in diffusion MRI: Non-negativity constrained super-resolved spherical deconvolution

2

Descoteaux, M., et al. IEEE TMI 2009. Deterministic and Probabilistic Tractography Based on Complex Fibre Orientation Distributions

3

Côté, M-A., et al. Medical Image Analysis 2013. Tractometer: Towards validation of tractography pipelines

4

Tournier, J.D, et al. Imaging Systems and Technology 2012. MRtrix: Diffusion Tractography in Crossing Fiber Regions

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. Use the model’s gradient table by default.

S0ndarray or float

The non diffusion-weighted signal value.

Returns
pred_signdarray

The predicted signal.

GradientTable

class dipy.reconst.benchmarks.bench_csd.GradientTable(gradients, big_delta=None, small_delta=None, b0_threshold=50, btens=None)

Bases: object

Diffusion gradient information

Parameters
gradientsarray_like (N, 3)

Diffusion gradients. The direction of each of these vectors corresponds to the b-vector, and the length corresponds to the b-value.

b0_thresholdfloat

Gradients with b-value less than or equal to b0_threshold are considered as b0s i.e. without diffusion weighting.

See also

gradient_table

Notes

The GradientTable object is immutable. Do NOT assign attributes. If you have your gradient table in a bval & bvec format, we recommend using the factory function gradient_table

Attributes
gradients(N,3) ndarray

diffusion gradients

bvals(N,) ndarray

The b-value, or magnitude, of each gradient direction.

qvals: (N,) ndarray

The q-value for each gradient direction. Needs big and small delta.

bvecs(N,3) ndarray

The direction, represented as a unit vector, of each gradient.

b0s_mask(N,) ndarray

Boolean array indicating which gradients have no diffusion weighting, ie b-value is close to 0.

b0_thresholdfloat

Gradients with b-value less than or equal to b0_threshold are considered to not have diffusion weighting.

btens(N,3,3) ndarray

The b-tensor of each gradient direction.

Methods

b0s_mask

bvals

bvecs

gradient_strength

qvals

tau

__init__(gradients, big_delta=None, small_delta=None, b0_threshold=50, btens=None)

Constructor for GradientTable class

b0s_mask()
bvals()
bvecs()
gradient_strength()
property info
qvals()
tau()

bench_csdeconv

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

load_nifti_data

dipy.reconst.benchmarks.bench_csd.load_nifti_data(fname, as_ndarray=True)

Load only the data array from a nifti file.

Parameters
fnamestr

Full path to the file.

as_ndarray: bool, optional

convert nibabel ArrayProxy to a numpy.ndarray. If you want to save memory and delay this casting, just turn this option to False (default: True)

Returns
data: np.ndarray or nib.ArrayProxy

See also

load_nifti

num_grad

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

read_stanford_labels

dipy.reconst.benchmarks.bench_csd.read_stanford_labels()

Read stanford hardi data and label map.

bench_local_maxima

dipy.reconst.benchmarks.bench_peaks.bench_local_maxima()

measure

dipy.reconst.benchmarks.bench_peaks.measure(code_str, times=1, label=None)

Return elapsed time for executing code in the namespace of the caller.

The supplied code string is compiled with the Python builtin compile. The precision of the timing is 10 milli-seconds. If the code will execute fast on this timescale, it can be executed many times to get reasonable timing accuracy.

Parameters
code_strstr

The code to be timed.

timesint, optional

The number of times the code is executed. Default is 1. The code is only compiled once.

labelstr, optional

A label to identify code_str with. This is passed into compile as the second argument (for run-time error messages).

Returns
elapsedfloat

Total elapsed time in seconds for executing code_str times times.

Examples

>>> times = 10
>>> etime = np.testing.measure('for i in range(1000): np.sqrt(i**2)', times=times)
>>> print("Time for a single execution : ", etime / times, "s")  
Time for a single execution :  0.005 s

bench_quick_squash

dipy.reconst.benchmarks.bench_squash.bench_quick_squash()

measure

dipy.reconst.benchmarks.bench_squash.measure(code_str, times=1, label=None)

Return elapsed time for executing code in the namespace of the caller.

The supplied code string is compiled with the Python builtin compile. The precision of the timing is 10 milli-seconds. If the code will execute fast on this timescale, it can be executed many times to get reasonable timing accuracy.

Parameters
code_strstr

The code to be timed.

timesint, optional

The number of times the code is executed. Default is 1. The code is only compiled once.

labelstr, optional

A label to identify code_str with. This is passed into compile as the second argument (for run-time error messages).

Returns
elapsedfloat

Total elapsed time in seconds for executing code_str times times.

Examples

>>> times = 10
>>> etime = np.testing.measure('for i in range(1000): np.sqrt(i**2)', times=times)
>>> print("Time for a single execution : ", etime / times, "s")  
Time for a single execution :  0.005 s

ndindex

dipy.reconst.benchmarks.bench_squash.ndindex(shape)

An N-dimensional iterator object to index arrays.

Given the shape of an array, an ndindex instance iterates over the N-dimensional index of the array. At each iteration a tuple of indices is returned; the last dimension is iterated over first.

Parameters
shapetuple of ints

The dimensions of the array.

Examples

>>> from dipy.core.ndindex import ndindex
>>> shape = (3, 2, 1)
>>> for index in ndindex(shape):
...     print(index)
(0, 0, 0)
(0, 1, 0)
(1, 0, 0)
(1, 1, 0)
(2, 0, 0)
(2, 1, 0)

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
resultarray

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

reduce

dipy.reconst.benchmarks.bench_squash.reduce(function, sequence[, initial]) value

Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). If initial is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty.

bench_vec_val_vect

dipy.reconst.benchmarks.bench_vec_val_sum.bench_vec_val_vect()

measure

dipy.reconst.benchmarks.bench_vec_val_sum.measure(code_str, times=1, label=None)

Return elapsed time for executing code in the namespace of the caller.

The supplied code string is compiled with the Python builtin compile. The precision of the timing is 10 milli-seconds. If the code will execute fast on this timescale, it can be executed many times to get reasonable timing accuracy.

Parameters
code_strstr

The code to be timed.

timesint, optional

The number of times the code is executed. Default is 1. The code is only compiled once.

labelstr, optional

A label to identify code_str with. This is passed into compile as the second argument (for run-time error messages).

Returns
elapsedfloat

Total elapsed time in seconds for executing code_str times times.

Examples

>>> times = 10
>>> etime = np.testing.measure('for i in range(1000): np.sqrt(i**2)', times=times)
>>> print("Time for a single execution : ", etime / times, "s")  
Time for a single execution :  0.005 s

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)

Methods

cache_clear()

Clear the cache.

cache_get(tag, key[, default])

Retrieve a value from the cache.

cache_set(tag, key, value)

Store a value in the cache.

__init__(*args, **kwargs)
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

auto_attr

dipy.reconst.cache.auto_attr(func)

Decorator to create OneTimeProperty attributes.

Parameters
funcmethod

The method that will be called the first time to compute a value. Afterwards, the method’s name will be a standard attribute holding the value of this computation.

Examples

>>> class MagicProp(object):
...     @auto_attr
...     def a(self):
...         return 99
...
>>> x = MagicProp()
>>> 'a' in x.__dict__
False
>>> x.a
99
>>> 'a' in x.__dict__
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.

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

Returns
CODndarray

The coefficient of determination. This has shape data.shape[:-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 implementd 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

1

Rokem, A., Chan, K.L. Yeatman, J.D., Pestilli, F., Mezer, A., Wandell, B.A., 2014. Evaluating the accuracy of diffusion models at multiple b-values with cross-validation. ISMRM 2014.

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.

Methods

basis(sphere)

A basis that maps the response coefficients onto a sphere.

on_sphere(sphere)

Evaluates the response function on sphere.

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

ConstrainedSDTModel

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

Bases: dipy.reconst.shm.SphHarmModel

Methods

cache_clear()

Clear the cache.

cache_get(tag, key[, default])

Retrieve a value from the cache.

cache_set(tag, key, value)

Store a value in the cache.

fit(data[, mask])

Fit method for every voxel in data

sampling_matrix(sphere)

The matrix needed to sample ODFs from coefficients of the model.

__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
gtabGradientTable
ratiofloat

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

1(1,2)

Descoteaux, M., et al. IEEE TMI 2009. Deterministic and Probabilistic Tractography Based on Complex Fibre Orientation Distributions.

fit(data, mask=None)

Fit method for every voxel in data

ConstrainedSphericalDeconvModel

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

Bases: dipy.reconst.shm.SphHarmModel

Methods

cache_clear()

Clear the cache.

cache_get(tag, key[, default])

Retrieve a value from the cache.

cache_set(tag, key, value)

Store a value in the cache.

fit(data[, mask])

Fit method for every voxel in data

predict(sh_coeff[, gtab, S0])

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

sampling_matrix(sphere)

The matrix needed to sample ODFs from coefficients of the model.

__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
gtabGradientTable
responsetuple 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

1(1,2,3,4,5)

Tournier, J.D., et al. NeuroImage 2007. Robust determination of the fibre orientation distribution in diffusion MRI: Non-negativity constrained super-resolved spherical deconvolution

2

Descoteaux, M., et al. IEEE TMI 2009. Deterministic and Probabilistic Tractography Based on Complex Fibre Orientation Distributions

3

Côté, M-A., et al. Medical Image Analysis 2013. Tractometer: Towards validation of tractography pipelines

4

Tournier, J.D, et al. Imaging Systems and Technology 2012. MRtrix: Diffusion Tractography in Crossing Fiber Regions

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. Use the model’s gradient table by default.

S0ndarray or float

The non diffusion-weighted signal value.

Returns
pred_signdarray

The predicted signal.

SphHarmFit

class dipy.reconst.csdeconv.SphHarmFit(model, shm_coef, mask)

Bases: dipy.reconst.odf.OdfFit

Diffusion data fit to a spherical harmonic model

Attributes
shape
shm_coeff

The spherical harmonic coefficients of the odf

Methods

odf(sphere)

Samples the odf function on the points of a sphere

predict([gtab, S0])

Predict the diffusion signal from the model coefficients.

gfa

__init__(model, shm_coef, mask)
gfa()
odf(sphere)

Samples the odf function on the points of a sphere

Parameters
sphereSphere

The points on which to sample the odf.

Returns
valuesndarray

The value of the odf on each point of sphere.

predict(gtab=None, S0=1.0)

Predict the diffusion signal from the model coefficients.

Parameters
gtaba GradientTable class instance

The directions and bvalues on which prediction is desired

S0float array

The mean non-diffusion-weighted signal in each voxel.

property shape
property shm_coeff

The spherical harmonic coefficients of the odf

Make this a property for now, if there is a usecase for modifying the coefficients we can add a setter or expose the coefficients more directly

SphHarmModel

class dipy.reconst.csdeconv.SphHarmModel(gtab)

Bases: dipy.reconst.odf.OdfModel, dipy.reconst.cache.Cache

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

Methods

cache_clear()

Clear the cache.

cache_get(tag, key[, default])

Retrieve a value from the cache.

cache_set(tag, key, value)

Store a value in the cache.

fit(data)

To be implemented by specific odf models

sampling_matrix(sphere)

The matrix needed to sample ODFs from coefficients of the model.

__init__(gtab)

Initialization of the abstract class for signal reconstruction models

Parameters
gtabGradientTable class instance
sampling_matrix(sphere)

The matrix needed to sample ODFs from coefficients of the model.

Parameters
sphereSphere

Points used to sample ODF.

Returns
sampling_matrixarray

The size of the matrix will be (N, M) where N is the number of vertices on sphere and M is the number of coefficients needed by the model.

TensorModel

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

Bases: dipy.reconst.base.ReconstModel

Diffusion Tensor

Methods

fit(data[, mask])

Fit method of the DTI model class

predict(dti_params[, S0])

Predict a signal for this TensorModel class instance given parameters.

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

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

Parameters
gtabGradientTable 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

1

Basser, P.J., Mattiello, J., LeBihan, D., 1994. Estimation of the effective self-diffusion tensor from the NMR spin echo. J Magn Reson B 103, 247-254.

2

Basser, P., Pierpaoli, C., 1996. Microstructural and physiological features of tissues elucidated by quantitative diffusion-tensor MRI. Journal of Magnetic Resonance 111, 209-219.

3

Lin-Ching C., Jones D.K., Pierpaoli, C. 2005. RESTORE: Robust estimation of tensors by outlier rejection. MRM 53: 1088-1095

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

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
gtabGradientTable
datandarray

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

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
gtabGradientTable
datandarray

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

cart2sphere

dipy.reconst.csdeconv.cart2sphere(x, y, z)

Return angles for Cartesian 3D coordinates x, y, and z

See doc for sphere2cart for angle conventions and derivation of the formulae.

\(0\le\theta\mathrm{(theta)}\le\pi\) and \(-\pi\le\phi\mathrm{(phi)}\le\pi\)

Parameters
xarray_like

x coordinate in Cartesian space

yarray_like

y coordinate in Cartesian space

zarray_like

z coordinate

Returns
rarray

radius

thetaarray

inclination (polar) angle

phiarray

azimuth angle

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
dwsignalarray

Diffusion weighted signals to be deconvolved.

Xarray

Prediction matrix which estimates diffusion weighted signals from FOD coefficients.

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

taufloat

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.

convergenceint

Maximum number of iterations to allow the deconvolution to converge.

Pndarray

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_shndarray ((sh_order + 1)*(sh_order + 2)/2,)

Spherical harmonics coefficients of the constrained-regularized fiber ODF.

num_itint

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(1,2)

Tournier, J.D., et al. NeuroImage 2007. Robust determination of the fibre orientation distribution in diffusion MRI: Non-negativity constrained super-resolved spherical deconvolution.

deprecate_with_version

dipy.reconst.csdeconv.deprecate_with_version(message, since='', until='', version_comparator=<function cmp_pkg_version>, warn_class=<class 'DeprecationWarning'>, error_class=<class 'dipy.utils.deprecator.ExpiredDeprecationError'>)

Return decorator function function for deprecation warning / error.

The decorated function / method will:

  • Raise the given warning_class warning when the function / method gets called, up to (and including) version until (if specified);

  • Raise the given error_class error when the function / method gets called, when the package version is greater than version until (if specified).

Parameters
messagestr

Message explaining deprecation, giving possible alternatives.

sincestr, optional

Released version at which object was first deprecated.

untilstr, optional

Last released version at which this function will still raise a deprecation warning. Versions higher than this will raise an error.

version_comparatorcallable

Callable accepting string as argument, and return 1 if string represents a higher version than encoded in the version_comparator, 0 if the version is equal, and -1 if the version is lower. For example, the version_comparator may compare the input version string to the current package version string.

warn_classclass, optional

Class of warning to generate for deprecation.

error_classclass, optional

Class of error to generate when version_comparator returns 1 for a given argument of until.

Returns
deprecatorfunc

Function returning a decorator.

deprecated_params

dipy.reconst.csdeconv.deprecated_params(old_name, new_name=None, since='', until='', version_comparator=<function cmp_pkg_version>, arg_in_kwargs=False, warn_class=<class 'dipy.utils.deprecator.ArgsDeprecationWarning'>, error_class=<class 'dipy.utils.deprecator.ExpiredDeprecationError'>, alternative='')

Deprecate a renamed or removed function argument.

The decorator assumes that the argument with the old_name was removed from the function signature and the new_name replaced it at the same position in the signature. If the old_name argument is given when calling the decorated function the decorator will catch it and issue a deprecation warning and pass it on as new_name argument.

Parameters
old_namestr or list/tuple thereof

The old name of the argument.

new_namestr or list/tuple thereof or None, optional

The new name of the argument. Set this to None to remove the argument old_name instead of renaming it.

sincestr or number or list/tuple thereof, optional

The release at which the old argument became deprecated.

untilstr or number or list/tuple thereof, optional

Last released version at which this function will still raise a deprecation warning. Versions higher than this will raise an error.

version_comparatorcallable

Callable accepting string as argument, and return 1 if string represents a higher version than encoded in the version_comparator, 0 if the version is equal, and -1 if the version is lower. For example, the version_comparator may compare the input version string to the current package version string.

arg_in_kwargsbool or list/tuple thereof, optional

If the argument is not a named argument (for example it was meant to be consumed by **kwargs) set this to True. Otherwise the decorator will throw an Exception if the new_name cannot be found in the signature of the decorated function. Default is False.

warn_classwarning, optional

Warning to be issued.

error_classException, optional

Error to be issued

alternativestr, optional

An alternative function or class name that the user may use in place of the deprecated object if new_name is None. The deprecation warning will tell the user about this alternative if provided.

Raises
TypeError

If the new argument name cannot be found in the function signature and arg_in_kwargs was False or if it is used to deprecate the name of the *args-, **kwargs-like arguments. At runtime such an Error is raised if both the new_name and old_name were specified when calling the function and “relax=False”.

Notes

This function is based on the Astropy (major modification). https://github.com/astropy/astropy. See COPYING file distributed along with the astropy package for the copyright and license terms.

Examples

The deprecation warnings are not shown in the following examples. To deprecate a positional or keyword argument:: >>> from dipy.utils.deprecator import deprecated_params >>> @deprecated_params(‘sig’, ‘sigma’, ‘0.3’) … def test(sigma): … return sigma >>> test(2) 2 >>> test(sigma=2) 2 >>> test(sig=2) # doctest: +SKIP 2

It is also possible to replace multiple arguments. The old_name, new_name and since have to be tuple or list and contain the same number of entries:: >>> @deprecated_params([‘a’, ‘b’], [‘alpha’, ‘beta’], … [‘0.2’, 0.4]) … def test(alpha, beta): … return alpha, beta >>> test(a=2, b=3) # doctest: +SKIP (2, 3)

estimate_response

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

Estimate single fiber response function

Parameters
gtabGradientTable
evalsndarray
S0float

non diffusion weighted

Returns
Sestimated signal

fa_trace_to_lambdas

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

forward_sdeconv_mat

dipy.reconst.csdeconv.forward_sdeconv_mat(r_rh, n)

Build forward spherical deconvolution matrix

Parameters
r_rhndarray

Rotational harmonics coefficients for the single fiber response function. Each element rh[i] is associated with spherical harmonics of degree 2*i.

nndarray

The order of spherical harmonic function associated with each row of the deconvolution matrix. Only even orders are allowed

Returns
Rndarray (N, N)

Deconvolution matrix with shape (N, N)

forward_sdt_deconv_mat

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

Build forward sharpening deconvolution transform (SDT) matrix

Parameters
ratiofloat

ratio = \(\frac{\lambda_2}{\lambda_1}\) of the single fiber response function

nndarray (N,)

The degree of spherical harmonic function associated with each row of the deconvolution matrix. Only even degrees are allowed.

r2_termbool

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
Rndarray (N, N)

SDT deconvolution matrix

Pndarray (N, N)

Funk-Radon Transform (FRT) matrix

References

1

Descoteaux, M. PhD Thesis. INRIA Sophia-Antipolis. 2008.

fractional_anisotropy

dipy.reconst.csdeconv.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}}\]

get_sphere

dipy.reconst.csdeconv.get_sphere(name='symmetric362')

provide triangulated spheres

Parameters
namestr

which sphere - one of: * ‘symmetric362’ * ‘symmetric642’ * ‘symmetric724’ * ‘repulsion724’ * ‘repulsion100’ * ‘repulsion200’

Returns
spherea dipy.core.sphere.Sphere class instance

Examples

>>> import numpy as np
>>> from dipy.data import get_sphere
>>> sphere = get_sphere('symmetric362')
>>> verts, faces = sphere.vertices, sphere.faces
>>> verts.shape == (362, 3)
True
>>> faces.shape == (720, 3)
True
>>> verts, faces = get_sphere('not a sphere name') 
Traceback (most recent call last):
    ...
DataError: No sphere called "not a sphere name"

lazy_index

dipy.reconst.csdeconv.lazy_index(index)

Produces a lazy index

Returns a slice that can be used for indexing an array, if no slice can be made index is returned as is.

lpn

dipy.reconst.csdeconv.lpn(n, z)

Legendre function of the first kind.

Compute sequence of Legendre functions of the first kind (polynomials), Pn(z) and derivatives for all degrees from 0 to n (inclusive).

See also special.legendre for polynomial class.

References

1

Zhang, Shanjie and Jin, Jianming. “Computation of Special Functions”, John Wiley and Sons, 1996. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html

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
gtabGradientTable
datandarray

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

1

Tournier, J.D., et al. NeuroImage 2004. Direct estimation of the

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

multi_voxel_fit

dipy.reconst.csdeconv.multi_voxel_fit(single_voxel_fit)

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

ndindex

dipy.reconst.csdeconv.ndindex(shape)

An N-dimensional iterator object to index arrays.

Given the shape of an array, an ndindex instance iterates over the N-dimensional index of the array. At each iteration a tuple of indices is returned; the last dimension is iterated over first.

Parameters
shapetuple of ints

The dimensions of the array.

Examples

>>> from dipy.core.ndindex import ndindex
>>> shape = (3, 2, 1)
>>> for index in ndindex(shape):
...     print(index)
(0, 0, 0)
(0, 1, 0)
(1, 0, 0)
(1, 1, 0)
(2, 0, 0)
(2, 1, 0)

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_shndarray ((sh_order + 1)*(sh_order + 2)/2,)

ndarray of SH coefficients for the ODF spherical function to be deconvolved

Rndarray ((sh_order + 1)(sh_order + 2)/2,

(sh_order + 1)(sh_order + 2)/2) SDT matrix in SH basis

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

taufloat

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

r2_termbool

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_shndarray ((sh_order + 1)(sh_order + 2)/2,)

Spherical harmonics coefficients of the constrained-regularized fiber ODF

num_itint

Number of iterations in the constrained-regularization used for convergence

References

1(1,2,3)

Tuch, D. MRM 2004. Q-Ball Imaging.

2(1,2,3)

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_shndarray ((sh_order + 1)*(sh_order + 2)/2, )

array of odfs expressed as spherical harmonics coefficients

sphereSphere

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

ratiofloat,

ratio of the smallest vs the largest eigenvalue of the single prolate tensor response function (\(\frac{\lambda_2}{\lambda_1}\))

sh_orderint

maximal SH order of the SH representation

lambda_float

lambda parameter (see odfdeconv) (default 1.0)

taufloat

tau parameter in the L matrix construction (see odfdeconv) (default 0.1)

r2_termbool

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_shndarray

sharpened odf expressed as spherical harmonics coefficients

References

1

Tuch, D. MRM 2004. Q-Ball Imaging.

2(1,2,3)

Descoteaux, M., et al. IEEE TMI 2009. Deterministic and Probabilistic Tractography Based on Complex Fibre Orientation Distributions

3(1,2)

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.

peaks_from_model

dipy.reconst.csdeconv.peaks_from_model(model, data, sphere, relative_peak_threshold, min_separation_angle, mask=None, return_odf=False, return_sh=True, gfa_thr=0, normalize_peaks=False, sh_order=8, sh_basis_type=None, npeaks=5, B=None, invB=None, parallel=False, num_processes=None)

Fit the model to data and computes peaks and metrics

Parameters
modela model instance

model will be used to fit the data.

datandarray

Diffusion data.

sphereSphere

The Sphere providing discrete directions for evaluation.

relative_peak_thresholdfloat

Only return peaks greater than relative_peak_threshold * m where m is the largest peak.

min_separation_anglefloat in [0, 90] The minimum distance between

directions. If two peaks are too close only the larger of the two is returned.

maskarray, optional

If mask is provided, voxels that are False in mask are skipped and no peaks are returned.

return_odfbool

If True, the odfs are returned.

return_shbool

If True, the odf as spherical harmonics coefficients is returned

gfa_thrfloat

Voxels with gfa less than gfa_thr are skipped, no peaks are returned.

normalize_peaksbool

If true, all peak values are calculated relative to max(odf).

sh_orderint, optional

Maximum SH order in the SH fit. For sh_order, there will be (sh_order + 1) * (sh_order + 2) / 2 SH coefficients (default 8).

sh_basis_type{None, ‘tournier07’, ‘descoteaux07’}

None for the default DIPY basis, tournier07 for the Tournier 2007 [2] basis, and descoteaux07 for the Descoteaux 2007 [1] basis (None defaults to descoteaux07).

npeaksint

Maximum number of peaks found (default 5 peaks).

Bndarray, optional

Matrix that transforms spherical harmonics to spherical function sf = np.dot(sh, B).

invBndarray, optional

Inverse of B.

parallel: bool

If True, use multiprocessing to compute peaks and metric (default False). Temporary files are saved in the default temporary directory of the system. It can be changed using import tempfile and tempfile.tempdir = '/path/to/tempdir'.

num_processes: int, 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.

Returns
pamPeaksAndMetrics

An object with gfa, peak_directions, peak_values, peak_indices, odf, shm_coeffs as attributes

References

1

Descoteaux, M., Angelino, E., Fitzgibbons, S. and Deriche, R. Regularized, Fast, and Robust Analytical Q-ball Imaging. Magn. Reson. Med. 2007;58:497-510.

2

Tournier J.D., Calamante F. and Connelly A. Robust determination of the fibre orientation distribution in diffusion MRI: Non-negativity constrained super-resolved spherical deconvolution. NeuroImage. 2007;35(4):1459-1472.

quad

dipy.reconst.csdeconv.quad(func, a, b, args=(), full_output=0, epsabs=1.49e-08, epsrel=1.49e-08, limit=50, points=None, weight=None, wvar=None, wopts=None, maxp1=50, limlst=50)

Compute a definite integral.

Integrate func from a to b (possibly infinite interval) using a technique from the Fortran library QUADPACK.

Parameters
func{function, scipy.LowLevelCallable}

A Python function or method to integrate. If func takes many arguments, it is integrated along the axis corresponding to the first argument.

If the user desires improved integration performance, then f may be a scipy.LowLevelCallable with one of the signatures:

double func(double x)
double func(double x, void *user_data)
double func(int n, double *xx)
double func(int n, double *xx, void *user_data)

The user_data is the data contained in the scipy.LowLevelCallable. In the call forms with xx, n is the length of the xx array which contains xx[0] == x and the rest of the items are numbers contained in the args argument of quad.

In addition, certain ctypes call signatures are supported for backward compatibility, but those should not be used in new code.

afloat

Lower limit of integration (use -numpy.inf for -infinity).

bfloat

Upper limit of integration (use numpy.inf for +infinity).

argstuple, optional

Extra arguments to pass to func.

full_outputint, optional

Non-zero to return a dictionary of integration information. If non-zero, warning messages are also suppressed and the message is appended to the output tuple.

Returns
yfloat

The integral of func from a to b.

abserrfloat

An estimate of the absolute error in the result.

infodictdict

A dictionary containing additional information. Run scipy.integrate.quad_explain() for more information.

message

A convergence message.

explain

Appended only with ‘cos’ or ‘sin’ weighting and infinite integration limits, it contains an explanation of the codes in infodict[‘ierlst’]

Other Parameters
epsabsfloat or int, optional

Absolute error tolerance. Default is 1.49e-8. quad tries to obtain an accuracy of abs(i-result) <= max(epsabs, epsrel*abs(i)) where i = integral of func from a to b, and result is the numerical approximation. See epsrel below.

epsrelfloat or int, optional

Relative error tolerance. Default is 1.49e-8. If epsabs <= 0, epsrel must be greater than both 5e-29 and 50 * (machine epsilon). See epsabs above.

limitfloat or int, optional

An upper bound on the number of subintervals used in the adaptive algorithm.

points(sequence of floats,ints), optional

A sequence of break points in the bounded integration interval where local difficulties of the integrand may occur (e.g., singularities, discontinuities). The sequence does not have to be sorted. Note that this option cannot be used in conjunction with weight.

weightfloat or int, optional

String indicating weighting function. Full explanation for this and the remaining arguments can be found below.

wvaroptional

Variables for use with weighting functions.

woptsoptional

Optional input for reusing Chebyshev moments.

maxp1float or int, optional

An upper bound on the number of Chebyshev moments.

limlstint, optional

Upper bound on the number of cycles (>=3) for use with a sinusoidal weighting and an infinite end-point.

See also

dblquad

double integral

tplquad

triple integral

nquad

n-dimensional integrals (uses quad recursively)

fixed_quad

fixed-order Gaussian quadrature

quadrature

adaptive Gaussian quadrature

odeint

ODE integrator

ode

ODE integrator

simpson

integrator for sampled data

romb

integrator for sampled data

scipy.special

for coefficients and roots of orthogonal polynomials

Notes

Extra information for quad() inputs and outputs

If full_output is non-zero, then the third output argument (infodict) is a dictionary with entries as tabulated below. For infinite limits, the range is transformed to (0,1) and the optional outputs are given with respect to this transformed range. Let M be the input argument limit and let K be infodict[‘last’]. The entries are:

‘neval’

The number of function evaluations.

‘last’

The number, K, of subintervals produced in the subdivision process.

‘alist’

A rank-1 array of length M, the first K elements of which are the left end points of the subintervals in the partition of the integration range.

‘blist’

A rank-1 array of length M, the first K elements of which are the right end points of the subintervals.

‘rlist’

A rank-1 array of length M, the first K elements of which are the integral approximations on the subintervals.

‘elist’

A rank-1 array of length M, the first K elements of which are the moduli of the absolute error estimates on the subintervals.

‘iord’

A rank-1 integer array of length M, the first L elements of which are pointers to the error estimates over the subintervals with L=K if K<=M/2+2 or L=M+1-K otherwise. Let I be the sequence infodict['iord'] and let E be the sequence infodict['elist']. Then E[I[1]], ..., E[I[L]] forms a decreasing sequence.

If the input argument points is provided (i.e., it is not None), the following additional outputs are placed in the output dictionary. Assume the points sequence is of length P.

‘pts’

A rank-1 array of length P+2 containing the integration limits and the break points of the intervals in ascending order. This is an array giving the subintervals over which integration will occur.

‘level’

A rank-1 integer array of length M (=limit), containing the subdivision levels of the subintervals, i.e., if (aa,bb) is a subinterval of (pts[1], pts[2]) where pts[0] and pts[2] are adjacent elements of infodict['pts'], then (aa,bb) has level l if |bb-aa| = |pts[2]-pts[1]| * 2**(-l).

‘ndin’

A rank-1 integer array of length P+2. After the first integration over the intervals (pts[1], pts[2]), the error estimates over some of the intervals may have been increased artificially in order to put their subdivision forward. This array has ones in slots corresponding to the subintervals for which this happens.

Weighting the integrand

The input variables, weight and wvar, are used to weight the integrand by a select list of functions. Different integration methods are used to compute the integral with these weighting functions, and these do not support specifying break points. The possible values of weight and the corresponding weighting functions are.

weight

Weight function used

wvar

‘cos’

cos(w*x)

wvar = w

‘sin’

sin(w*x)

wvar = w

‘alg’

g(x) = ((x-a)**alpha)*((b-x)**beta)

wvar = (alpha, beta)

‘alg-loga’

g(x)*log(x-a)

wvar = (alpha, beta)

‘alg-logb’

g(x)*log(b-x)

wvar = (alpha, beta)

‘alg-log’

g(x)*log(x-a)*log(b-x)

wvar = (alpha, beta)

‘cauchy’

1/(x-c)

wvar = c

wvar holds the parameter w, (alpha, beta), or c depending on the weight selected. In these expressions, a and b are the integration limits.

For the ‘cos’ and ‘sin’ weighting, additional inputs and outputs are available.

For finite integration limits, the integration is performed using a Clenshaw-Curtis method which uses Chebyshev moments. For repeated calculations, these moments are saved in the output dictionary:

‘momcom’

The maximum level of Chebyshev moments that have been computed, i.e., if M_c is infodict['momcom'] then the moments have been computed for intervals of length |b-a| * 2**(-l), l=0,1,...,M_c.

‘nnlog’

A rank-1 integer array of length M(=limit), containing the subdivision levels of the subintervals, i.e., an element of this array is equal to l if the corresponding subinterval is |b-a|* 2**(-l).

‘chebmo’

A rank-2 array of shape (25, maxp1) containing the computed Chebyshev moments. These can be passed on to an integration over the same interval by passing this array as the second element of the sequence wopts and passing infodict[‘momcom’] as the first element.

If one of the integration limits is infinite, then a Fourier integral is computed (assuming w neq 0). If full_output is 1 and a numerical error is encountered, besides the error message attached to the output tuple, a dictionary is also appended to the output tuple which translates the error codes in the array info['ierlst'] to English messages. The output information dictionary contains the following entries instead of ‘last’, ‘alist’, ‘blist’, ‘rlist’, and ‘elist’:

‘lst’

The number of subintervals needed for the integration (call it K_f).

‘rslst’

A rank-1 array of length M_f=limlst, whose first K_f elements contain the integral contribution over the interval (a+(k-1)c, a+kc) where c = (2*floor(|w|) + 1) * pi / |w| and k=1,2,...,K_f.

‘erlst’

A rank-1 array of length M_f containing the error estimate corresponding to the interval in the same position in infodict['rslist'].

‘ierlst’

A rank-1 integer array of length M_f containing an error flag corresponding to the interval in the same position in infodict['rslist']. See the explanation dictionary (last entry in the output tuple) for the meaning of the codes.

Examples

Calculate \(\int^4_0 x^2 dx\) and compare with an analytic result

>>> from scipy import integrate
>>> x2 = lambda x: x**2
>>> integrate.quad(x2, 0, 4)
(21.333333333333332, 2.3684757858670003e-13)
>>> print(4**3 / 3.)  # analytical result
21.3333333333

Calculate \(\int^\infty_0 e^{-x} dx\)

>>> invexp = lambda x: np.exp(-x)
>>> integrate.quad(invexp, 0, np.inf)
(1.0, 5.842605999138044e-11)
>>> f = lambda x,a : a*x
>>> y, err = integrate.quad(f, 0, 1, args=(1,))
>>> y
0.5
>>> y, err = integrate.quad(f, 0, 1, args=(3,))
>>> y
1.5

Calculate \(\int^1_0 x^2 + y^2 dx\) with ctypes, holding y parameter as 1:

testlib.c =>
    double func(int n, double args[n]){
        return args[0]*args[0] + args[1]*args[1];}
compile to library testlib.*
from scipy import integrate
import ctypes
lib = ctypes.CDLL('/home/.../testlib.*') #use absolute path
lib.func.restype = ctypes.c_double
lib.func.argtypes = (ctypes.c_int,ctypes.c_double)
integrate.quad(lib.func,0,1,(1))
#(1.3333333333333333, 1.4802973661668752e-14)
print((1.0**3/3.0 + 1.0) - (0.0**3/3.0 + 0.0)) #Analytic result
# 1.3333333333333333

Be aware that pulse shapes and other sharp features as compared to the size of the integration interval may not be integrated correctly using this method. A simplified example of this limitation is integrating a y-axis reflected step function with many zero values within the integrals bounds.

>>> y = lambda x: 1 if x<=0 else 0
>>> integrate.quad(y, -1, 1)
(1.0, 1.1102230246251565e-14)
>>> integrate.quad(y, -1, 100)
(1.0000000002199108, 1.0189464580163188e-08)
>>> integrate.quad(y, -1, 10000)
(0.0, 0.0)

real_sh_descoteaux

dipy.reconst.csdeconv.real_sh_descoteaux(sh_order, theta, phi, full_basis=False, legacy=True)

Compute real spherical harmonics as in Descoteaux et al. 2007 [Ra6d8f6cd2652-1], where the real harmonic \(Y^m_n\) is defined to be:

Imag(\(Y^m_n\)) * sqrt(2) if m > 0 \(Y^0_n\) if m = 0 Real(\(Y^m_n\)) * sqrt(2) if m < 0

This may take scalar or array arguments. The inputs will be broadcasted against each other.

Parameters
sh_orderint

The maximum degree or the spherical harmonic basis.

thetafloat [0, pi]

The polar (colatitudinal) coordinate.

phifloat [0, 2*pi]

The azimuthal (longitudinal) coordinate.

full_basis: bool, optional

If true, returns a basis including odd order SH functions as well as even order SH functions. Otherwise returns only even order SH functions.

legacy: bool, optional

If true, uses DIPY’s legacy descoteaux07 implementation (where |m| for m < 0). Else, implements the basis as defined in Descoteaux et al. 2007.

Returns
real_shreal float

The real harmonic \(Y^m_n\) sampled at theta and phi.

marray

The degree of the harmonics.

narray

The order of the harmonics.

real_sh_descoteaux_from_index

dipy.reconst.csdeconv.real_sh_descoteaux_from_index(m, n, theta, phi, legacy=True)

Compute real spherical harmonics as in Descoteaux et al. 2007 [R2763a8caef3c-1], where the real harmonic \(Y^m_n\) is defined to be:

Imag(\(Y^m_n\)) * sqrt(2) if m > 0 \(Y^0_n\) if m = 0 Real(\(Y^m_n\)) * sqrt(2) if m < 0

This may take scalar or array arguments. The inputs will be broadcasted against each other.

Parameters
mint |m| <= n

The degree of the harmonic.

nint >= 0

The order of the harmonic.

thetafloat [0, pi]

The polar (colatitudinal) coordinate.

phifloat [0, 2*pi]

The azimuthal (longitudinal) coordinate.

legacy: bool, optional

If true, uses DIPY’s legacy descoteaux07 implementation (where |m| is used for m < 0). Else, implements the basis as defined in Descoteaux et al. 2007 (without the absolute value).

Returns
real_shreal float

The real harmonic \(Y^m_n\) sampled at theta and phi.

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
gtabGradientTable
datandarray

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

1

Tax, C.M.W., et al. NeuroImage 2014. Recursive calibration of the fiber response function for spherical deconvolution of diffusion MRI data.

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
gtabGradientTable
datandarray

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[R64bc28ca561d-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

1

Tournier, J.D., et al. NeuroImage 2004. Direct estimation of the

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
gtabGradientTable
datandarray

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[Rb280cc58c30e-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

1

Tournier, J.D., et al. NeuroImage 2004. Direct estimation of the

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

sh_to_rh

dipy.reconst.csdeconv.sh_to_rh(r_sh, m, n)

Spherical harmonics (SH) to rotational harmonics (RH)

Calculate the rotational harmonic decomposition up to harmonic order n, degree m for an axially and antipodally symmetric function. Note that all m != 0 coefficients will be ignored as axial symmetry is assumed. Hence, there will be (sh_order/2 + 1) non-zero coefficients.

Parameters
r_shndarray (N,)

ndarray of SH coefficients for the single fiber response function. These coefficients must correspond to the real spherical harmonic functions produced by shm.real_sh_descoteaux_from_index.

mndarray (N,)

The degree of the spherical harmonic function associated with each coefficient.

nndarray (N,)

The order of the spherical harmonic function associated with each coefficient.

Returns
r_rhndarray ((sh_order + 1)*(sh_order + 2)/2,)

Rotational harmonics coefficients representing the input r_sh

See also

shm.real_sh_descoteaux_from_index, shm.real_sh_descoteaux

References

1

Tournier, J.D., et al. NeuroImage 2007. Robust determination of the fibre orientation distribution in diffusion MRI: Non-negativity constrained super-resolved spherical deconvolution

single_tensor

dipy.reconst.csdeconv.single_tensor(gtab, S0=1, evals=None, evecs=None, snr=None)

Simulate diffusion-weighted signals with a single tensor.

Parameters
gtabGradientTable

Table with information of b-values and gradient directions g. Note that if gtab has a btens attribute, simulations will be performed according to the given b-tensor B information.

S0double,

Strength of signal in the presence of no diffusion gradient (also called the b=0 value).

evals(3,) ndarray

Eigenvalues of the diffusion tensor. By default, values typical for prolate white matter are used.

evecs(3, 3) ndarray

Eigenvectors of the tensor. You can also think of this as a rotation matrix that transforms the direction of the tensor. The eigenvectors need to be column wise.

snrfloat

Signal to noise ratio, assuming Rician noise. None implies no noise.

Returns
S(N,) ndarray
Simulated signal:

S(b, g) = S_0 e^(-b g^T R D R.T g), if gtab.tens=None S(B) = S_0 e^(-B:D), if gtab.tens information is given

References

1

M. Descoteaux, “High Angular Resolution Diffusion MRI: from Local Estimation to Segmentation and Tractography”, PhD thesis, University of Nice-Sophia Antipolis, p. 42, 2008.

2

E. Stejskal and J. Tanner, “Spin diffusion measurements: spin echos in the presence of a time-dependent field gradient”, Journal of Chemical Physics, nr. 42, pp. 288–292, 1965.

sph_harm_ind_list

dipy.reconst.csdeconv.sph_harm_ind_list(sh_order, full_basis=False)

Returns the degree (m) and order (n) of all the symmetric spherical harmonics of degree less then or equal to sh_order. The results, m_list and n_list are kx1 arrays, where k depends on sh_order. They can be passed to real_sh_descoteaux_from_index() and :func:real_sh_tournier_from_index.

Parameters
sh_orderint

even int > 0, max order to return

full_basis: bool, optional

True for SH basis with even and odd order terms

Returns
m_listarray

degrees of even spherical harmonics

n_listarray

orders of even spherical harmonics

See also

shm.real_sh_descoteaux_from_index, shm.real_sh_tournier_from_index

vec2vec_rotmat

dipy.reconst.csdeconv.vec2vec_rotmat(u, v)

rotation matrix from 2 unit vectors

u, v being unit 3d vectors return a 3x3 rotation matrix R than aligns u to v.

In general there are many rotations that will map u to v. If S is any rotation using v as an axis then R.S will also map u to v since (S.R)u = S(Ru) = Sv = v. The rotation R returned by vec2vec_rotmat leaves fixed the perpendicular to the plane spanned by u and v.

The transpose of R will align v to u.

Parameters
uarray, shape(3,)
varray, shape(3,)
Returns
Rarray, shape(3,3)

Examples

>>> import numpy as np
>>> from dipy.core.geometry import vec2vec_rotmat
>>> u=np.array([1,0,0])
>>> v=np.array([0,1,0])
>>> R=vec2vec_rotmat(u,v)
>>> np.dot(R,u)
array([ 0.,  1.,  0.])
>>> np.dot(R.T,v)
array([ 1.,  0.,  0.])

DiffusionKurtosisFit

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

Bases: dipy.reconst.dti.TensorFit

Class for fitting the Diffusion Kurtosis Model

Attributes
S0_hat
directions

For tracking - return the primary direction in each voxel

evals

Returns the eigenvalues of the tensor as an array

evecs

Returns the eigenvectors of the tensor as an array, columnwise

kfa

Returns the kurtosis tensor (KFA) 1.

kt

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

quadratic_form

Calculates the 3x3 diffusion tensor for each voxel

shape

Methods

ad()

Axial diffusivity (AD) calculated from cached eigenvalues.

adc(sphere)

Calculate the apparent diffusion coefficient (ADC) in each direction on

ak([min_kurtosis, max_kurtosis, analytical])

Axial Kurtosis (AK) of a diffusion kurtosis tensor [1].

akc(sphere)

Calculates the apparent kurtosis coefficient (AKC) in each direction on the sphere for each voxel in the data

color_fa()

Color fractional anisotropy of diffusion tensor

fa()

Fractional anisotropy (FA) calculated from cached eigenvalues.

ga()

Geodesic anisotropy (GA) calculated from cached eigenvalues.

kmax([sphere, gtol, mask])

Computes the maximum value of a single voxel kurtosis tensor

linearity()

Returns

md()

Mean diffusivity (MD) calculated from cached eigenvalues.

mk([min_kurtosis, max_kurtosis, analytical])

Computes mean Kurtosis (MK) from the kurtosis tensor.

mkt([min_kurtosis, max_kurtosis])

Computes mean of the kurtosis tensor (MKT) [1].

mode()

Tensor mode calculated from cached eigenvalues.

odf(sphere)

The diffusion orientation distribution function (dODF).

planarity()

Returns

predict(gtab[, S0])

Given a DKI model fit, predict the signal on the vertices of a gradient table

rd()

Radial diffusivity (RD) calculated from cached eigenvalues.

rk([min_kurtosis, max_kurtosis, analytical])

Radial Kurtosis (RK) of a diffusion kurtosis tensor [1].

sphericity()

Returns

trace()

Trace of the tensor calculated from cached eigenvalues.

lower_triangular

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

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

1(1,2,3)

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(1,2,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

3

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

akc(sphere)

Calculates the apparent kurtosis coefficient (AKC) in each direction on the sphere for each voxel in the data

Parameters
sphereSphere class instance
Returns
akcndarray

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:

\[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 coefficent computed as:

\[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

Returns the kurtosis tensor (KFA) [1].

Notes

The KFA is defined as [1]:

\[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(1,2,3)

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)

Computes 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

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

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

Computes mean Kurtosis (MK) from the kurtosis tensor.

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 [4])

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

analyticalbool (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
mkarray

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[R1a4c5980fd18-1]_:

\[MK \equiv \frac{1}{4\pi} \int d\Omega_\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:

\[\begin{split}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}\end{split}\]

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

\[ \begin{align}\begin{aligned}\begin{split}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_2\lambda_3}}{\lambda_1} R_F(\frac{\lambda_1}{\lambda_2},\frac{\lambda_1}{\lambda_3},1)+\\ \frac{3\lambda_1^2-\lambda_1\lambda_2-\lambda_2\lambda_3- \lambda_1\lambda_3} {3\lambda_1 \sqrt{\lambda_2 \lambda_3}} R_D(\frac{\lambda_1}{\lambda_2},\frac{\lambda_1}{\lambda_3},1)-1 ]\end{split}\\\begin{split}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_2\lambda_3}} R_F(\frac{\lambda_1}{\lambda_2},\frac{\lambda_1}{\lambda_3},1)+\\ \frac{2\lambda_1-\lambda_2-\lambda_3}{3\sqrt{\lambda_2 \lambda_3}} R_D(\frac{\lambda_1}{\lambda_2},\frac{\lambda_1}{\lambda_3},1)-2]\end{split}\end{aligned}\end{align} \]

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)

Computes 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

1(1,2,3)

Hansen, B., Lund, T. E., Sangill, R., and Jespersen, S. N. 2013. Experimentally and computationally fast method for estimation of a mean kurtosis. Magnetic Resonance in Medicine69, 1754–1760. 388. doi:10.1002/mrm.24743

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

predict(gtab, S0=1.0)

Given a DKI model fit, predict the signal on the vertices of a gradient table

Parameters
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

Notes

The predicted signal is given by:

\[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:

\[D(n)=\sum_{i=1}^{3}\sum_{j=1}^{3}n_{i}n_{j}D_{ij}\]

and

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

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

1(1,2,3)

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(1,2)

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

3

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

DiffusionKurtosisModel

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

Bases: dipy.reconst.base.ReconstModel

Class for the Diffusion Kurtosis Model

Methods

fit(data[, mask])

Fit method of the DKI model class

predict(dki_params[, S0])

Predict a signal for this DKI model class instance given parameters.

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

Diffusion Kurtosis Tensor Model [1]

Parameters
gtabGradientTable class instance
fit_methodstr or callable

str can be one of the following: ‘OLS’ or ‘ULLS’ for ordinary least squares

dki.ols_fit_dki

‘WLS’ or ‘UWLLS’ for weighted ordinary least squares

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

1

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

fit(data, mask=None)

Fit method of the DKI 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(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

ReconstModel

class dipy.reconst.dki.ReconstModel(gtab)

Bases: object

Abstract class for signal reconstruction models

Methods

fit

__init__(gtab)

Initialization of the abstract class for signal reconstruction models

Parameters
gtabGradientTable class instance
fit(data, mask=None, **kwargs)

TensorFit

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

Bases: object

Attributes
S0_hat
directions

For tracking - return the primary direction in each voxel

evals

Returns the eigenvalues of the tensor as an array

evecs

Returns the eigenvectors of the tensor as an array, columnwise

quadratic_form

Calculates the 3x3 diffusion tensor for each voxel

shape

Methods

ad()

Axial diffusivity (AD) calculated from cached eigenvalues.

adc(sphere)

Calculate the apparent diffusion coefficient (ADC) in each direction on

color_fa()

Color fractional anisotropy of diffusion tensor

fa()

Fractional anisotropy (FA) calculated from cached eigenvalues.

ga()

Geodesic anisotropy (GA) calculated from cached eigenvalues.

linearity()

Returns

md()

Mean diffusivity (MD) calculated from cached eigenvalues.

mode()

Tensor mode calculated from cached eigenvalues.

odf(sphere)

The diffusion orientation distribution function (dODF).

planarity()

Returns

predict(gtab[, S0, step])

Given a model fit, predict the signal on the vertices of a sphere

rd()

Radial diffusivity (RD) calculated from cached eigenvalues.

sphericity()

Returns

trace()

Trace of the tensor calculated from cached eigenvalues.

lower_triangular

__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

Parameters
sphereSphere class instance
Returns
adcndarray

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

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

1

Westin C.-F., Peled S., Gubjartsson H., Kikinis R., Jolesz F., “Geometrical diffusion measures for MRI from tensor basis analysis” in Proc. 5th Annual ISMRM, 1997.

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
sphereSphere class instance.

The dODF is calculated in the vertices of this input.

Returns
odfndarray

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

1

Westin C.-F., Peled S., Gubjartsson H., Kikinis R., Jolesz F., “Geometrical diffusion measures for MRI from tensor basis analysis” in Proc. 5th Annual ISMRM, 1997.

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

Given a model fit, predict the signal on the vertices of a sphere

Parameters
gtaba GradientTable class instance

This encodes the directions for which a prediction is made

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

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.

Notes

The predicted signal is given by:

\[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

1

Westin C.-F., Peled S., Gubjartsson H., Kikinis R., Jolesz F., “Geometrical diffusion measures for MRI from tensor basis analysis” in Proc. 5th Annual ISMRM, 1997.

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

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:

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

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)

Computes 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

apparent_kurtosis_coef

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

Calculates the apparent kurtosis coefficient (AKC) in each direction of a sphere [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 eigenvectors respectively

  3. Fifteen elements of the kurtosis tensor

spherea Sphere class instance

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

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 physicaly 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
akcndarray (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]:

\[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 coefficent computed as:

\[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(1,2,3)

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

axial_kurtosis

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

Computes 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

1(1,2,3)

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(1,2,3,4)

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

3

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

carlson_rd

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

Computes the Carlson’s incomplete elliptic integral of the second kind 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.

carlson_rf

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

Computes the Carlson’s incomplete elliptic integral of the first kind 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

1

Carlson, B.C., 1994. Numerical computation of real or complex elliptic integrals. arXiv:math/9409227 [math.CA]

cart2sphere

dipy.reconst.dki.cart2sphere(x, y, z)

Return angles for Cartesian 3D coordinates x, y, and z

See doc for sphere2cart for angle conventions and derivation of the formulae.

\(0\le\theta\mathrm{(theta)}\le\pi\) and \(-\pi\le\phi\mathrm{(phi)}\le\pi\)

Parameters
xarray_like

x coordinate in Cartesian space

yarray_like

y coordinate in Cartesian space

zarray_like

z coordinate

Returns
rarray

radius

thetaarray

inclination (polar) angle

phiarray

azimuth angle

check_multi_b

dipy.reconst.dki.check_multi_b(gtab, n_bvals, non_zero=True, bmag=None)

Check if you have enough different b-values in your gradient table

Parameters
gtabGradientTable class instance.
n_bvalsint

The number of different b-values you are checking for.

non_zerobool

Whether to check only non-zero bvalues. In this case, we will require at least n_bvals non-zero b-values (where non-zero is defined depending on the gtab object’s b0_threshold attribute)

bmagint

The order of magnitude of the b-values used. The function will normalize the b-values relative \(10^{bmag}\). Default: derive this value from the maximal b-value provided: \(bmag=log_{10}(max(bvals)) - 1\).

Returns
boolWhether there are at least n_bvals different b-values in the
gradient table used.

decompose_tensor

dipy.reconst.dki.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.dki.design_matrix(gtab)

Construct B design matrix for DKI.

Parameters
gtabGradientTable

Measurement directions.

Returns
Barray (N, 22)

Design matrix or B matrix for the DKI model B[j, :] = (Bxx, Bxy, Bzz, Bxz, Byz, Bzz,

Bxxxx, Byyyy, Bzzzz, Bxxxy, Bxxxz, Bxyyy, Byyyz, Bxzzz, Byzzz, Bxxyy, Bxxzz, Byyzz, Bxxyz, Bxyyz, Bxyzz, BlogS0)

directional_diffusion

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

Calculates 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

1(1,2)

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

directional_diffusion_variance

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

Calculates 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 physicaly 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

1(1,2)

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

directional_kurtosis

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

Calculates 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 physicaly 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

1(1,2)

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

dki_prediction

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

Predict a signal given diffusion kurtosis imaging 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

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

Returns
S(…, N) ndarray

Simulated signal based on the DKI model:

\[S=S_{0}e^{-bD+\]
rac{1}{6}b^{2}D^{2}K}

from_lower_triangular

dipy.reconst.dki.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

get_fnames

dipy.reconst.dki.get_fnames(name='small_64D')

Provide full paths to example or test datasets.

Parameters
namestr

the filename/s of which dataset to return, one of:

  • ‘small_64D’ small region of interest nifti,bvecs,bvals 64 directions

  • ‘small_101D’ small region of interest nifti, bvecs, bvals 101 directions

  • ‘aniso_vox’ volume with anisotropic voxel size as Nifti

  • ‘fornix’ 300 tracks in Trackvis format (from Pittsburgh Brain Competition)

  • ‘gqi_vectors’ the scanner wave vectors needed for a GQI acquisitions of 101 directions tested on Siemens 3T Trio

  • ‘small_25’ small ROI (10x8x2) DTI data (b value 2000, 25 directions)

  • ‘test_piesno’ slice of N=8, K=14 diffusion data

  • ‘reg_c’ small 2D image used for validating registration

  • ‘reg_o’ small 2D image used for validation registration

  • ‘cb_2’ two vectorized cingulum bundles

Returns
fnamestuple

filenames for dataset

Examples

>>> import numpy as np
>>> from dipy.io.image import load_nifti
>>> from dipy.data import get_fnames
>>> fimg, fbvals, fbvecs = get_fnames('small_101D')
>>> bvals=np.loadtxt(fbvals)
>>> bvecs=np.loadtxt(fbvecs).T
>>> data, affine = load_nifti(fimg)
>>> data.shape == (6, 10, 10, 102)
True
>>> bvals.shape == (102,)
True
>>> bvecs.shape == (102, 3)
True

get_sphere

dipy.reconst.dki.get_sphere(name='symmetric362')

provide triangulated spheres

Parameters
namestr

which sphere - one of: * ‘symmetric362’ * ‘symmetric642’ * ‘symmetric724’ * ‘repulsion724’ * ‘repulsion100’ * ‘repulsion200’

Returns
spherea dipy.core.sphere.Sphere class instance

Examples

>>> import numpy as np
>>> from dipy.data import get_sphere
>>> sphere = get_sphere('symmetric362')
>>> verts, faces = sphere.vertices, sphere.faces
>>> verts.shape == (362, 3)
True
>>> faces.shape == (720, 3)
True
>>> verts, faces = get_sphere('not a sphere name') 
Traceback (most recent call last):
    ...
DataError: No sphere called "not a sphere name"

kurtosis_fractional_anisotropy

dipy.reconst.dki.kurtosis_fractional_anisotropy(dki_params)

Computes the anisotropy of the kurtosis tensor (KFA) [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

Returns
——-
kfaarray

Calculated mean kurtosis tensor.

Notes

The KFA is defined as [1]:

\[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(1,2,3,4)

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

kurtosis_maximum

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

Computes 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

local_maxima

dipy.reconst.dki.local_maxima()

Local maxima of a function evaluated on a discrete set of points.

If a function is evaluated on some set of points where each pair of neighboring points is an edge in edges, find the local maxima.

Parameters
odfarray, 1d, dtype=double

The function evaluated on a set of discrete points.

edgesarray (N, 2)

The set of neighbor relations between the points. Every edge, ie edges[i, :], is a pair of neighboring points.

Returns
peak_valuesndarray

Value of odf at a maximum point. Peak values is sorted in descending order.

peak_indicesndarray

Indices of maximum points. Sorted in the same order as peak_values so odf[peak_indices[i]] == peak_values[i].

See also

dipy.core.sphere

Notes

A point is a local maximum if it is > at least one neighbor and >= all neighbors. If no points meet the above criteria, 1 maximum is returned such that odf[maximum] == max(odf).

lower_triangular

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

Returns the six lower triangular values of the tensor 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)

mean_diffusivity

dipy.reconst.dki.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}\]

mean_kurtosis

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

Computes mean Kurtosis (MK) from the kurtosis tensor.

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 [4])

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

analyticalbool (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
mkarray

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[R953e26c55b6a-1]_:

\[MK \equiv \frac{1}{4\pi} \int d\Omega_\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:

\[\begin{split}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}\end{split}\]

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

\[ \begin{align}\begin{aligned}\begin{split}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_2\lambda_3}}{\lambda_1} R_F(\frac{\lambda_1}{\lambda_2},\frac{\lambda_1}{\lambda_3},1)+\\ \frac{3\lambda_1^2-\lambda_1\lambda_2-\lambda_2\lambda_3- \lambda_1\lambda_3} {3\lambda_1 \sqrt{\lambda_2 \lambda_3}} R_D(\frac{\lambda_1}{\lambda_2},\frac{\lambda_1}{\lambda_3},1)-1 ]\end{split}\\\begin{split}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_2\lambda_3}} R_F(\frac{\lambda_1}{\lambda_2},\frac{\lambda_1}{\lambda_3},1)+\\ \frac{2\lambda_1-\lambda_2-\lambda_3}{3\sqrt{\lambda_2 \lambda_3}} R_D(\frac{\lambda_1}{\lambda_2},\frac{\lambda_1}{\lambda_3},1)-2]\end{split}\end{aligned}\end{align} \]

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

mean_kurtosis_tensor

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

Computes 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

1(1,2,3)

Hansen, B., Lund, T. E., Sangill, R., and Jespersen, S. N. (2013). Experimentally and computationally fast method for estimation of a mean kurtosis.Magnetic Resonance in Medicine69, 1754–1760.388 doi:10.1002/mrm.24743

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

ndindex

dipy.reconst.dki.ndindex(shape)

An N-dimensional iterator object to index arrays.

Given the shape of an array, an ndindex instance iterates over the N-dimensional index of the array. At each iteration a tuple of indices is returned; the last dimension is iterated over first.

Parameters
shapetuple of ints

The dimensions of the array.

Examples

>>> from dipy.core.ndindex import ndindex
>>> shape = (3, 2, 1)
>>> for index in ndindex(shape):
...     print(index)
(0, 0, 0)
(0, 1, 0)
(1, 0, 0)
(1, 1, 0)
(2, 0, 0)
(2, 1, 0)

nlls_fit_tensor

dipy.reconst.dki.nlls_fit_tensor(design_matrix, data, weighting=None, sigma=None, jac=True, return_S0_hat=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.

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

voxel.

ols_fit_dki

dipy.reconst.dki.ols_fit_dki(design_matrix, data)

Computes the diffusion and kurtosis tensors using an ordinary linear least squares (OLS) approach 1.

Parameters
design_matrixarray (g, 22)

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

dataarray (N, g)

Data or response variables holding the data. Note that the last dimension should contain the data. It makes no copies of data.

Returns
dki_paramsarray (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

See also

wls_fit_dki, nls_fit_dki

References

[1] Lu, H., Jensen, J. H., Ramani, A., and Helpern, J. A. (2006).

Three-dimensional characterization of non-gaussian water diffusion in humans using diffusion kurtosis imaging. NMR in Biomedicine 19, 236–247. doi:10.1002/nbm.1020

perpendicular_directions

dipy.reconst.dki.perpendicular_directions(v, num=30, half=False)

Computes n evenly spaced perpendicular directions relative to a given vector v

Parameters
varray (3,)

Array containing the three cartesian coordinates of vector v

numint, optional

Number of perpendicular directions to generate

halfbool, optional

If half is True, perpendicular directions are sampled on half of the unit circumference perpendicular to v, otherwive perpendicular directions are sampled on the full circumference. Default of half is False

Returns
psamplesarray (n, 3)

array of vectors perpendicular to v

Notes

Perpendicular directions are estimated using the following two step procedure:

1) the perpendicular directions are first sampled in a unit circumference parallel to the plane normal to the x-axis.

2) Samples are then rotated and aligned to the plane normal to vector v. The rotational matrix for this rotation is constructed as reference frame basis which axis are the following:

  • The first axis is vector v

  • The second axis is defined as the normalized vector given by the

cross product between vector v and the unit vector aligned to the x-axis - The third axis is defined as the cross product between the previous computed vector and vector v.

Following this two steps, coordinates of the final perpendicular directions are given as:

\[\left [ -\sin(a_{i}) \sqrt{{v_{y}}^{2}+{v_{z}}^{2}} \; , \; \frac{v_{x}v_{y}\sin(a_{i})-v_{z}\cos(a_{i})} {\sqrt{{v_{y}}^{2}+{v_{z}}^{2}}} \; , \; \frac{v_{x}v_{z}\sin(a_{i})-v_{y}\cos(a_{i})} {\sqrt{{v_{y}}^{2}+{v_{z}}^{2}}} \right ]\]

This procedure has a singularity when vector v is aligned to the x-axis. To solve this singularity, perpendicular directions in procedure’s step 1 are defined in the plane normal to y-axis and the second axis of the rotated frame of reference is computed as the normalized vector given by the cross product between vector v and the unit vector aligned to the y-axis. Following this, the coordinates of the perpendicular directions are given as:

left [ -frac{left (v_{x}v_{y}sin(a_{i})+v_{z}cos(a_{i}) right )} {sqrt{{v_{x}}^{2}+{v_{z}}^{2}}} ; , ; sin(a_{i}) sqrt{{v_{x}}^{2}+{v_{z}}^{2}} ; , ; frac{v_{y}v_{z}sin(a_{i})+v_{x}cos(a_{i})} {sqrt{{v_{x}}^{2}+{v_{z}}^{2}}} right ]

For more details on this calculation, see ` here <http://gsoc2015dipydki.blogspot.it/2015/07/rnh-post-8-computing-perpendicular.html>`_.

radial_kurtosis

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

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

1(1,2,3)

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(1,2,3,4)

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

3

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

restore_fit_tensor

dipy.reconst.dki.restore_fit_tensor(design_matrix, data, sigma=None, jac=True, return_S0_hat=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

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

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.

Returns
restore_paramsan estimate of the tensor parameters in each voxel.

References

1(1,2,3)

Chang, L-C, Jones, DK and Pierpaoli, C (2005). RESTORE: robust

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

sphere2cart

dipy.reconst.dki.sphere2cart(r, theta, phi)

Spherical to Cartesian coordinates

This is the standard physics convention where theta is the inclination (polar) angle, and phi is the azimuth angle.

Imagine a sphere with center (0,0,0). Orient it with the z axis running south-north, the y axis running west-east and the x axis from posterior to anterior. theta (the inclination angle) is the angle to rotate from the z-axis (the zenith) around the y-axis, towards the x axis. Thus the rotation is counter-clockwise from the point of view of positive y. phi (azimuth) gives the angle of rotation around the z-axis towards the y axis. The rotation is counter-clockwise from the point of view of positive z.

Equivalently, given a point P on the sphere, with coordinates x, y, z, theta is the angle between P and the z-axis, and phi is the angle between the projection of P onto the XY plane, and the X axis.

Geographical nomenclature designates theta as ‘co-latitude’, and phi as ‘longitude’

Parameters
rarray_like

radius

thetaarray_like

inclination or polar angle

phiarray_like

azimuth angle

Returns
xarray

x coordinate(s) in Cartesion space

yarray

y coordinate(s) in Cartesian space

zarray

z coordinate

Notes

See these pages:

for excellent discussion of the many different conventions possible. Here we use the physics conventions, used in the wikipedia page.

Derivations of the formulae are simple. Consider a vector x, y, z of length r (norm of x, y, z). The inclination angle (theta) can be found from: cos(theta) == z / r -> z == r * cos(theta). This gives the hypotenuse of the projection onto the XY plane, which we will call Q. Q == r*sin(theta). Now x / Q == cos(phi) -> x == r * sin(theta) * cos(phi) and so on.

We have deliberately named this function sphere2cart rather than sph2cart to distinguish it from the Matlab function of that name, because the Matlab function uses an unusual convention for the angles that we did not want to replicate. The Matlab function is trivial to implement with the formulae given in the Matlab help.

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

vec_val_vect

dipy.reconst.dki.vec_val_vect()

Vectorize vecs.diag(vals).`vecs`.T for last 2 dimensions of vecs

Parameters
vecsshape (…, M, N) array

containing tensor in last two dimensions; M, N usually equal to (3, 3)

valsshape (…, N) array

diagonal values carried in last dimension, ... shape above must match that for vecs

Returns
resshape (…, M, M) array

For all the dimensions ellided by ..., loops to get (M, N) vec matrix, and (N,) vals vector, and calculates vec.dot(np.diag(val).dot(vec.T).

Raises
ValueErrornon-matching ... dimensions of vecs, vals
ValueErrornon-matching N dimensions of vecs, vals

Examples

Make a 3D array where the first dimension is only 1

>>> vecs = np.arange(9).reshape((1, 3, 3))
>>> vals = np.arange(3).reshape((1, 3))
>>> vec_val_vect(vecs, vals)
array([[[   9.,   24.,   39.],
        [  24.,   66.,  108.],
        [  39.,  108.,  177.]]])

That’s the same as the 2D case (apart from the float casting):

>>> vecs = np.arange(9).reshape((3, 3))
>>> vals = np.arange(3)
>>> np.dot(vecs, np.dot(np.diag(vals), vecs.T))
array([[  9,  24,  39],
       [ 24,  66, 108],
       [ 39, 108, 177]])

wls_fit_dki

dipy.reconst.dki.wls_fit_dki(design_matrix, data)

Computes the diffusion and kurtosis tensors using a weighted linear least squares (WLS) approach 1.

Parameters
design_matrixarray (g, 22)

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

dataarray (N, g)

Data or response variables holding the data. Note that the last dimension should contain the data. It makes no copies of data.

Returns
dki_paramsarray (N, 27)

All parameters estimated from the diffusion kurtosis model for all N voxels. 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

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.

DiffusionKurtosisFit

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

Bases: dipy.reconst.dti.TensorFit

Class for fitting the Diffusion Kurtosis Model

Attributes
S0_hat
directions

For tracking - return the primary direction in each voxel

evals

Returns the eigenvalues of the tensor as an array

evecs

Returns the eigenvectors of the tensor as an array, columnwise

kfa

Returns the kurtosis tensor (KFA) 1.

kt

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

quadratic_form

Calculates the 3x3 diffusion tensor for each voxel

shape

Methods

ad()

Axial diffusivity (AD) calculated from cached eigenvalues.

adc(sphere)

Calculate the apparent diffusion coefficient (ADC) in each direction on

ak([min_kurtosis, max_kurtosis, analytical])

Axial Kurtosis (AK) of a diffusion kurtosis tensor [1].

akc(sphere)

Calculates the apparent kurtosis coefficient (AKC) in each direction on the sphere for each voxel in the data

color_fa()

Color fractional anisotropy of diffusion tensor

fa()

Fractional anisotropy (FA) calculated from cached eigenvalues.

ga()

Geodesic anisotropy (GA) calculated from cached eigenvalues.

kmax([sphere, gtol, mask])

Computes the maximum value of a single voxel kurtosis tensor

linearity()

Returns

md()

Mean diffusivity (MD) calculated from cached eigenvalues.

mk([min_kurtosis, max_kurtosis, analytical])

Computes mean Kurtosis (MK) from the kurtosis tensor.

mkt([min_kurtosis, max_kurtosis])

Computes mean of the kurtosis tensor (MKT) [1].

mode()

Tensor mode calculated from cached eigenvalues.

odf(sphere)

The diffusion orientation distribution function (dODF).

planarity()

Returns

predict(gtab[, S0])

Given a DKI model fit, predict the signal on the vertices of a gradient table

rd()

Radial diffusivity (RD) calculated from cached eigenvalues.

rk([min_kurtosis, max_kurtosis, analytical])

Radial Kurtosis (RK) of a diffusion kurtosis tensor [1].

sphericity()

Returns

trace()

Trace of the tensor calculated from cached eigenvalues.

lower_triangular

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

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

1(1,2,3)

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(1,2,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

3

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

akc(sphere)

Calculates the apparent kurtosis coefficient (AKC) in each direction on the sphere for each voxel in the data

Parameters
sphereSphere class instance
Returns
akcndarray

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:

\[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 coefficent computed as:

\[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

Returns the kurtosis tensor (KFA) [1].

Notes

The KFA is defined as [1]:

\[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(1,2,3)

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)

Computes 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

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

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

Computes mean Kurtosis (MK) from the kurtosis tensor.

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 [4])

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

analyticalbool (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
mkarray

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[Rb657f27beb9e-1]_:

\[MK \equiv \frac{1}{4\pi} \int d\Omega_\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:

\[\begin{split}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}\end{split}\]

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

\[ \begin{align}\begin{aligned}\begin{split}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_2\lambda_3}}{\lambda_1} R_F(\frac{\lambda_1}{\lambda_2},\frac{\lambda_1}{\lambda_3},1)+\\ \frac{3\lambda_1^2-\lambda_1\lambda_2-\lambda_2\lambda_3- \lambda_1\lambda_3} {3\lambda_1 \sqrt{\lambda_2 \lambda_3}} R_D(\frac{\lambda_1}{\lambda_2},\frac{\lambda_1}{\lambda_3},1)-1 ]\end{split}\\\begin{split}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_2\lambda_3}} R_F(\frac{\lambda_1}{\lambda_2},\frac{\lambda_1}{\lambda_3},1)+\\ \frac{2\lambda_1-\lambda_2-\lambda_3}{3\sqrt{\lambda_2 \lambda_3}} R_D(\frac{\lambda_1}{\lambda_2},\frac{\lambda_1}{\lambda_3},1)-2]\end{split}\end{aligned}\end{align} \]

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)

Computes 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

1(1,2,3)

Hansen, B., Lund, T. E., Sangill, R., and Jespersen, S. N. 2013. Experimentally and computationally fast method for estimation of a mean kurtosis. Magnetic Resonance in Medicine69, 1754–1760. 388. doi:10.1002/mrm.24743

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

predict(gtab, S0=1.0)

Given a DKI model fit, predict the signal on the vertices of a gradient table

Parameters
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

Notes

The predicted signal is given by:

\[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:

\[D(n)=\sum_{i=1}^{3}\sum_{j=1}^{3}n_{i}n_{j}D_{ij}\]

and

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

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

1(1,2,3)

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(1,2)

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

3

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

DiffusionKurtosisModel

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

Bases: dipy.reconst.base.ReconstModel

Class for the Diffusion Kurtosis Model

Methods

fit(data[, mask])

Fit method of the DKI model class

predict(dki_params[, S0])

Predict a signal for this DKI model class instance given parameters.

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

Diffusion Kurtosis Tensor Model [1]

Parameters
gtabGradientTable class instance
fit_methodstr or callable

str can be one of the following: ‘OLS’ or ‘ULLS’ for ordinary least squares

dki.ols_fit_dki

‘WLS’ or ‘UWLLS’ for weighted ordinary least squares

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

1

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

fit(data, mask=None)

Fit method of the DKI 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(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

KurtosisMicrostructuralFit

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

Bases: dipy.reconst.dki.DiffusionKurtosisFit

Class for fitting the Diffusion Kurtosis Microstructural Model

Attributes
S0_hat
awf

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

axonal_diffusivity

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

directions

For tracking - return the primary direction in each voxel

evals

Returns the eigenvalues of the tensor as an array

evecs

Returns the eigenvectors of the tensor as an array, columnwise

hindered_ad

Returns the axial diffusivity of the hindered compartment.

hindered_evals

Returns the eigenvalues of the hindered diffusion compartment.

hindered_rd

Returns the radial diffusivity of the hindered compartment.

kfa

Returns the kurtosis tensor (KFA) 1.

kt

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

quadratic_form

Calculates the 3x3 diffusion tensor for each voxel

restricted_evals

Returns the eigenvalues of the restricted diffusion compartment.

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

Methods

ad()

Axial diffusivity (AD) calculated from cached eigenvalues.

adc(sphere)

Calculate the apparent diffusion coefficient (ADC) in each direction on

ak([min_kurtosis, max_kurtosis, analytical])

Axial Kurtosis (AK) of a diffusion kurtosis tensor [R0b1a747e81c9-1].

akc(sphere)

Calculates the apparent kurtosis coefficient (AKC) in each direction on the sphere for each voxel in the data

color_fa()

Color fractional anisotropy of diffusion tensor

fa()

Fractional anisotropy (FA) calculated from cached eigenvalues.

ga()

Geodesic anisotropy (GA) calculated from cached eigenvalues.

kmax([sphere, gtol, mask])

Computes the maximum value of a single voxel kurtosis tensor

linearity()

Returns

md()

Mean diffusivity (MD) calculated from cached eigenvalues.

mk([min_kurtosis, max_kurtosis, analytical])

Computes mean Kurtosis (MK) from the kurtosis tensor.

mkt([min_kurtosis, max_kurtosis])

Computes mean of the kurtosis tensor (MKT) [R8b3dd90f2e0d-1].

mode()

Tensor mode calculated from cached eigenvalues.

odf(sphere)

The diffusion orientation distribution function (dODF).

planarity()

Returns

predict(gtab[, S0])

Given a DKI microstructural model fit, predict the signal on the vertices of a gradient table

rd()

Radial diffusivity (RD) calculated from cached eigenvalues.

rk([min_kurtosis, max_kurtosis, analytical])

Radial Kurtosis (RK) of a diffusion kurtosis tensor [Rc4101656d30e-1].

sphericity()

Returns

trace()

Trace of the tensor calculated from cached eigenvalues.

lower_triangular

__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 definde as the intra-cellular and extra-cellular diffusion compartments respectively.

References

1

Fieremans, E., Jensen, J.H., Helpern, J.A., 2011. White Matter Characterization with Diffusion Kurtosis Imaging. Neuroimage 58(1): 177-188. doi:10.1016/j.neuroimage.2011.06.006

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

1

Fieremans, E., Jensen, J.H., Helpern, J.A., 2011. White Matter Characterization with Diffusion Kurtosis Imaging. Neuroimage 58(1): 177-188. doi:10.1016/j.neuroimage.2011.06.006

property axonal_diffusivity

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

References

1

Fieremans, E., Jensen, J.H., Helpern, J.A., 2011. White Matter Characterization with Diffusion Kurtosis Imaging. Neuroimage 58(1): 177-188. doi:10.1016/j.neuroimage.2011.06.006

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

1

Fieremans, E., Jensen, J.H., Helpern, J.A., 2011. White Matter Characterization with Diffusion Kurtosis Imaging. Neuroimage 58(1): 177-188. doi:10.1016/j.neuroimage.2011.06.006

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

1

Fieremans, E., Jensen, J.H., Helpern, J.A., 2011. White Matter Characterization with Diffusion Kurtosis Imaging. Neuroimage 58(1): 177-188. doi:10.1016/j.neuroimage.2011.06.006

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

1

Fieremans, E., Jensen, J.H., Helpern, J.A., 2011. White Matter Characterization with Diffusion Kurtosis Imaging. Neuroimage 58(1): 177-188. doi:10.1016/j.neuroimage.2011.06.006

predict(gtab, S0=1.0)

Given a DKI microstructural model fit, predict the signal on the vertices of a gradient table

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

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

1

Fieremans, E., Jensen, J.H., Helpern, J.A., 2011. White Matter Characterization with Diffusion Kurtosis Imaging. Neuroimage 58(1): 177-188. doi:10.1016/j.neuroimage.2011.06.006

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

1(1,2)

Fieremans, E., Jensen, J.H., Helpern, J.A., 2011. White Matter Characterization with Diffusion Kurtosis Imaging. Neuroimage 58(1): 177-188. doi:10.1016/j.neuroimage.2011.06.006

KurtosisMicrostructureModel

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

Bases: dipy.reconst.dki.DiffusionKurtosisModel

Class for the Diffusion Kurtosis Microstructural Model

Methods

fit(data[, mask, sphere, gtol, awf_only])

Fit method of the Diffusion Kurtosis Microstructural Model

predict(params[, S0])

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

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

Initialize a KurtosisMicrostrutureModel class instance [1].

Parameters
gtabGradientTable 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

1

Fieremans, E., Jensen, J.H., Helpern, J.A., 2011. White Matter Characterization with Diffusion Kurtosis Imaging. Neuroimage 58(1): 177-188. doi:10.1016/j.neuroimage.2011.06.006

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 definde as the intra-cellular and extra-cellular diffusion compartments respectively.

References

1

Fieremans, E., Jensen, J.H., Helpern, J.A., 2011. White Matter Characterization with Diffusion Kurtosis Imaging. Neuroimage 58(1): 177-188. doi:10.1016/j.neuroimage.2011.06.006

axial_diffusivity

dipy.reconst.dki_micro.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\]

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

1(1,2)

Fieremans E, Jensen JH, Helpern JA, 2011. White matter characterization with diffusional kurtosis imaging. Neuroimage 58(1):177-88. doi: 10.1016/j.neuroimage.2011.06.006

decompose_tensor

dipy.reconst.dki_micro.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])

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 definde as the intra-cellular and extra-cellular diffusion compartments respectively.

References

1(1,2,3)

Fieremans E, Jensen JH, Helpern JA, 2011. White matter characterization with diffusional kurtosis imaging. Neuroimage 58(1):177-88. doi: 10.1016/j.neuroimage.2011.06.006

directional_diffusion

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

Calculates 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

1(1,2)

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

directional_kurtosis

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

Calculates 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 physicaly 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

1(1,2)

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

dkimicro_prediction

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

Signal prediction given the DKI microstructure model parameters.

Parameters
paramsndarray (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

gtaba GradientTable class instance

The gradient table for this prediction

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 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 definde as the intra-cellular and extra-cellular diffusion compartments respectively.

dti_design_matrix

dipy.reconst.dki_micro.dti_design_matrix(gtab, dtype=None)

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

Parameters
gtabA 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)

from_lower_triangular

dipy.reconst.dki_micro.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

get_sphere

dipy.reconst.dki_micro.get_sphere(name='symmetric362')

provide triangulated spheres

Parameters
namestr

which sphere - one of: * ‘symmetric362’ * ‘symmetric642’ * ‘symmetric724’ * ‘repulsion724’ * ‘repulsion100’ * ‘repulsion200’

Returns
spherea dipy.core.sphere.Sphere class instance

Examples

>>> import numpy as np
>>> from dipy.data import get_sphere
>>> sphere = get_sphere('symmetric362')
>>> verts, faces = sphere.vertices, sphere.faces
>>> verts.shape == (362, 3)
True
>>> faces.shape == (720, 3)
True
>>> verts, faces = get_sphere('not a sphere name') 
Traceback (most recent call last):
    ...
DataError: No sphere called "not a sphere name"

kurtosis_maximum

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

Computes 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

lower_triangular

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

Returns the six lower triangular values of the tensor 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)

mean_diffusivity

dipy.reconst.dki_micro.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}\]

ndindex

dipy.reconst.dki_micro.ndindex(shape)

An N-dimensional iterator object to index arrays.

Given the shape of an array, an ndindex instance iterates over the N-dimensional index of the array. At each iteration a tuple of indices is returned; the last dimension is iterated over first.

Parameters
shapetuple of ints

The dimensions of the array.

Examples

>>> from dipy.core.ndindex import ndindex
>>> shape = (3, 2, 1)
>>> for index in ndindex(shape):
...     print(index)
(0, 0, 0)
(0, 1, 0)
(1, 0, 0)
(1, 1, 0)
(2, 0, 0)
(2, 1, 0)

radial_diffusivity

dipy.reconst.dki_micro.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}\]

split_dki_param

dipy.reconst.dki_micro.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

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

trace

dipy.reconst.dki_micro.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\]

vec_val_vect

dipy.reconst.dki_micro.vec_val_vect()

Vectorize vecs.diag(vals).`vecs`.T for last 2 dimensions of vecs

Parameters
vecsshape (…, M, N) array

containing tensor in last two dimensions; M, N usually equal to (3, 3)

valsshape (…, N) array

diagonal values carried in last dimension, ... shape above must match that for vecs

Returns
resshape (…, M, M) array

For all the dimensions ellided by ..., loops to get (M, N) vec matrix, and (N,) vals vector, and calculates vec.dot(np.diag(val).dot(vec.T).

Raises
ValueErrornon-matching ... dimensions of vecs, vals
ValueErrornon-matching N dimensions of vecs, vals

Examples

Make a 3D array where the first dimension is only 1

>>> vecs = np.arange(9).reshape((1, 3, 3))
>>> vals = np.arange(3).reshape((1, 3))
>>> vec_val_vect(vecs, vals)
array([[[   9.,   24.,   39.],
        [  24.,   66.,  108.],
        [  39.,  108.,  177.]]])

That’s the same as the 2D case (apart from the float casting):

>>> vecs = np.arange(9).reshape((3, 3))
>>> vals = np.arange(3)
>>> np.dot(vecs, np.dot(np.diag(vals), vecs.T))
array([[  9,  24,  39],
       [ 24,  66, 108],
       [ 39, 108, 177]])

Cache

class dipy.reconst.dsi.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)

Methods

cache_clear()

Clear the cache.

cache_get(tag, key[, default])

Retrieve a value from the cache.

cache_set(tag, key, value)

Store a value in the cache.

__init__(*args, **kwargs)
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

DiffusionSpectrumDeconvFit

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

Bases: dipy.reconst.dsi.DiffusionSpectrumFit

Methods

msd_discrete([normalized])

Calculates the mean squared displacement on the discrete propagator

odf(sphere)

Calculates the real discrete odf for a given discrete sphere

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

rtop_pdf([normalized])

Calculates the return to origin probability from the propagator, which is the propagator evaluated at zero (see Descoteaux et Al.

rtop_signal([filtering])

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

__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

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: dipy.reconst.dsi.DiffusionSpectrumModel

Methods

cache_clear()

Clear the cache.

cache_get(tag, key[, default])

Retrieve a value from the cache.

cache_set(tag, key, value)

Store a value in the cache.

fit(data[, mask])

Fit method for every voxel in data

__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
gtabGradientTable,

Gradient directions and bvalues container class

qgrid_sizeint,

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_startfloat,

ODF is sampled radially in the PDF. This parameters shows where the sampling should start.

r_endfloat,

Radial endpoint of ODF sampling

r_stepfloat,

Step size of the ODf sampling from r_start to r_end

filter_widthfloat,

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

DiffusionSpectrumFit

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

Bases: dipy.reconst.odf.OdfFit

Methods

msd_discrete([normalized])

Calculates the mean squared displacement on the discrete propagator

odf(sphere)

Calculates the real discrete odf for a given discrete sphere

pdf([normalized])

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

rtop_pdf([normalized])

Calculates the return to origin probability from the propagator, which is the propagator evaluated at zero (see Descoteaux et Al.

rtop_signal([filtering])

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

__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
normalizedboolean, optional

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

Returns
msdfloat

the mean square displacement

References

1

Wu Y. et al., “Hybrid diffusion imaging”, NeuroImage, vol 36,

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

1

Descoteaux M. et al., “Multiple q-shell diffusion propagator

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

2

Tuch D.S., “Diffusion MRI of Complex Tissue Structure”, PhD Thesis, 2002.

3

Wu Y. et al., “Computation of Diffusion Function Measures

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

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: dipy.reconst.odf.OdfModel, dipy.reconst.cache.Cache

Methods

cache_clear()

Clear the cache.

cache_get(tag, key[, default])

Retrieve a value from the cache.

cache_set(tag, key, value)

Store a value in the cache.

fit(data[, mask])

Fit method for every voxel in data

__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
gtabGradientTable,

Gradient directions and bvalues container class

qgrid_sizeint,

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_startfloat,

ODF is sampled radially in the PDF. This parameters shows where the sampling should start.

r_endfloat,

Radial endpoint of ODF sampling

r_stepfloat,

Step size of the ODf sampling from r_start to r_end

filter_widthfloat,

Strength of the hanning filter

See also

dipy.reconst.gqi.GeneralizedQSampling

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.

  1. We assume that data only one b0 volume is provided.

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
fit(data, mask=None)

Fit method for every voxel in data

OdfFit

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

Bases: dipy.reconst.base.ReconstFit

Methods

odf(sphere)

To be implemented but specific odf models

__init__(model, data)
odf(sphere)

To be implemented but specific odf models

OdfModel

class dipy.reconst.dsi.OdfModel(gtab)

Bases: dipy.reconst.base.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.

Methods

fit(data)

To be implemented by specific odf models

__init__(gtab)

Initialization of the abstract class for signal reconstruction models

Parameters
gtabGradientTable class instance
fit(data)

To be implemented by specific odf models

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

1

Biggs David S.C. et al., “Acceleration of Iterative Image Restoration Algorithms”, Applied Optics, vol. 36, No. 8, p. 1766-1775, 1997.

create_qspace

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

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

Parameters
gtabGradientTable
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
gtabGradientTable
origin(3,) ndarray

center of qspace

Returns
qtablendarray

fftn

dipy.reconst.dsi.fftn(x, shape=None, axes=None, overwrite_x=False)

Return multidimensional discrete Fourier transform.

The returned array contains:

y[j_1,..,j_d] = sum[k_1=0..n_1-1, ..., k_d=0..n_d-1]
   x[k_1,..,k_d] * prod[i=1..d] exp(-sqrt(-1)*2*pi/n_i * j_i * k_i)

where d = len(x.shape) and n = x.shape.

Parameters
xarray_like

The (N-D) array to transform.

shapeint or array_like of ints or None, optional

The shape of the result. If both shape and axes (see below) are None, shape is x.shape; if shape is None but axes is not None, then shape is numpy.take(x.shape, axes, axis=0). If shape[i] > x.shape[i], the ith dimension is padded with zeros. If shape[i] < x.shape[i], the ith dimension is truncated to length shape[i]. If any element of shape is -1, the size of the corresponding dimension of x is used.

axesint or array_like of ints or None, optional

The axes of x (y if shape is not None) along which the transform is applied. The default is over all axes.

overwrite_xbool, optional

If True, the contents of x can be destroyed. Default is False.

Returns
ycomplex-valued N-D NumPy array

The (N-D) DFT of the input array.

See also

ifftn

Notes

If x is real-valued, then y[..., j_i, ...] == y[..., n_i-j_i, ...].conjugate().

Both single and double precision routines are implemented. Half precision inputs will be converted to single precision. Non-floating-point inputs will be converted to double precision. Long-double precision inputs are not supported.

Examples

>>> from scipy.fftpack import fftn, ifftn
>>> y = (-np.arange(16), 8 - np.arange(16), np.arange(16))
>>> np.allclose(y, fftn(ifftn(y)))
True

fftshift

dipy.reconst.dsi.fftshift(x, axes=None)

Shift the zero-frequency component to the center of the spectrum.

This function swaps half-spaces for all axes listed (defaults to all). Note that y[0] is the Nyquist component only if len(x) is even.

Parameters
xarray_like

Input array.

axesint or shape tuple, optional

Axes over which to shift. Default is None, which shifts all axes.

Returns
yndarray

The shifted array.

See also

ifftshift

The inverse of fftshift.

Examples

>>> freqs = np.fft.fftfreq(10, 0.1)
>>> freqs
array([ 0.,  1.,  2., ..., -3., -2., -1.])
>>> np.fft.fftshift(freqs)
array([-5., -4., -3., -2., -1.,  0.,  1.,  2.,  3.,  4.])

Shift the zero-frequency component only along the second axis:

>>> freqs = np.fft.fftfreq(9, d=1./9).reshape(3, 3)
>>> freqs
array([[ 0.,  1.,  2.],
       [ 3.,  4., -4.],
       [-3., -2., -1.]])
>>> np.fft.fftshift(freqs, axes=(1,))
array([[ 2.,  0.,  1.],
       [-4.,  3.,  4.],
       [-1., -3., -2.]])

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.

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_dataarray, shape (X, Y, Z, 2 * W -1)
new_gtabGradientTable

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.

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
gtabGradientTable
filter_widthint
origin(3,) ndarray

center of qspace

Returns
filter(N,) ndarray

where N is the number of non-b0 gradient directions

ifftshift

dipy.reconst.dsi.ifftshift(x, axes=None)

The inverse of fftshift. Although identical for even-length x, the functions differ by one sample for odd-length x.

Parameters
xarray_like

Input array.

axesint or shape tuple, optional

Axes over which to calculate. Defaults to None, which shifts all axes.

Returns
yndarray

The shifted array.

See also

fftshift

Shift zero-frequency component to the center of the spectrum.

Examples

>>> freqs = np.fft.fftfreq(9, d=1./9).reshape(3, 3)
>>> freqs
array([[ 0.,  1.,  2.],
       [ 3.,  4., -4.],
       [-3., -2., -1.]])
>>> np.fft.ifftshift(np.fft.fftshift(freqs))
array([[ 0.,  1.,  2.],
       [ 3.,  4., -4.],
       [-3., -2., -1.]])

map_coordinates

dipy.reconst.dsi.map_coordinates(input, coordinates, output=None, order=3, mode='constant', cval=0.0, prefilter=True)

Map the input array to new coordinates by interpolation.

The array of coordinates is used to find, for each point in the output, the corresponding coordinates in the input. The value of the input at those coordinates is determined by spline interpolation of the requested order.

The shape of the output is derived from that of the coordinate array by dropping the first axis. The values of the array along the first axis are the coordinates in the input array at which the output value is found.

Parameters
inputarray_like

The input array.

coordinatesarray_like

The coordinates at which input is evaluated.

outputarray or dtype, optional

The array in which to place the output, or the dtype of the returned array. By default an array of the same dtype as input will be created.

orderint, optional

The order of the spline interpolation, default is 3. The order has to be in the range 0-5.

mode{‘reflect’, ‘grid-mirror’, ‘constant’, ‘grid-constant’, ‘nearest’, ‘mirror’, ‘grid-wrap’, ‘wrap’}, optional

The mode parameter determines how the input array is extended beyond its boundaries. Default is ‘constant’. Behavior for each valid value is as follows (see additional plots and details on boundary modes):

‘reflect’ (d c b a | a b c d | d c b a)

The input is extended by reflecting about the edge of the last pixel. This mode is also sometimes referred to as half-sample symmetric.

‘grid-mirror’

This is a synonym for ‘reflect’.

‘constant’ (k k k k | a b c d | k k k k)

The input is extended by filling all values beyond the edge with the same constant value, defined by the cval parameter. No interpolation is performed beyond the edges of the input.

‘grid-constant’ (k k k k | a b c d | k k k k)

The input is extended by filling all values beyond the edge with the same constant value, defined by the cval parameter. Interpolation occurs for samples outside the input’s extent as well.

‘nearest’ (a a a a | a b c d | d d d d)

The input is extended by replicating the last pixel.

‘mirror’ (d c b | a b c d | c b a)

The input is extended by reflecting about the center of the last pixel. This mode is also sometimes referred to as whole-sample symmetric.

‘grid-wrap’ (a b c d | a b c d | a b c d)

The input is extended by wrapping around to the opposite edge.

‘wrap’ (d b c d | a b c d | b c a b)

The input is extended by wrapping around to the opposite edge, but in a way such that the last point and initial point exactly overlap. In this case it is not well defined which sample will be chosen at the point of overlap.

cvalscalar, optional

Value to fill past edges of input if mode is ‘constant’. Default is 0.0.

prefilterbool, optional

Determines if the input array is prefiltered with spline_filter before interpolation. The default is True, which will create a temporary float64 array of filtered values if order > 1. If setting this to False, the output will be slightly blurred if order > 1, unless the input is prefiltered, i.e. it is the result of calling spline_filter on the original input.

Returns
map_coordinatesndarray

The result of transforming the input. The shape of the output is derived from that of coordinates by dropping the first axis.

See also

spline_filter, geometric_transform, scipy.interpolate

Notes

For complex-valued input, this function maps the real and imaginary components independently.

New in version 1.6.0: Complex-valued support added.

Examples

>>> from scipy import ndimage
>>> a = np.arange(12.).reshape((4, 3))
>>> a
array([[  0.,   1.,   2.],
       [  3.,   4.,   5.],
       [  6.,   7.,   8.],
       [  9.,  10.,  11.]])
>>> ndimage.map_coordinates(a, [[0.5, 2], [0.5, 1]], order=1)
array([ 2.,  7.])

Above, the interpolated value of a[0.5, 0.5] gives output[0], while a[2, 1] is output[1].

>>> inds = np.array([[0.5, 2], [0.5, 4]])
>>> ndimage.map_coordinates(a, inds, order=1, cval=-33.3)
array([  2. , -33.3])
>>> ndimage.map_coordinates(a, inds, order=1, mode='nearest')
array([ 2.,  8.])
>>> ndimage.map_coordinates(a, inds, order=1, cval=0, output=bool)
array([ True, False], dtype=bool)

multi_voxel_fit

dipy.reconst.dsi.multi_voxel_fit(single_voxel_fit)

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

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

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.

ReconstModel

class dipy.reconst.dti.ReconstModel(gtab)

Bases: object

Abstract class for signal reconstruction models

Methods

fit

__init__(gtab)

Initialization of the abstract class for signal reconstruction models

Parameters
gtabGradientTable class instance
fit(data, mask=None, **kwargs)

TensorFit

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

Bases: object

Attributes
S0_hat
directions

For tracking - return the primary direction in each voxel

evals

Returns the eigenvalues of the tensor as an array

evecs

Returns the eigenvectors of the tensor as an array, columnwise

quadratic_form

Calculates the 3x3 diffusion tensor for each voxel

shape

Methods

ad()

Axial diffusivity (AD) calculated from cached eigenvalues.

adc(sphere)

Calculate the apparent diffusion coefficient (ADC) in each direction on

color_fa()

Color fractional anisotropy of diffusion tensor

fa()

Fractional anisotropy (FA) calculated from cached eigenvalues.

ga()

Geodesic anisotropy (GA) calculated from cached eigenvalues.

linearity()

Returns

md()

Mean diffusivity (MD) calculated from cached eigenvalues.

mode()

Tensor mode calculated from cached eigenvalues.

odf(sphere)

The diffusion orientation distribution function (dODF).

planarity()

Returns

predict(gtab[, S0, step])

Given a model fit, predict the signal on the vertices of a sphere

rd()

Radial diffusivity (RD) calculated from cached eigenvalues.

sphericity()

Returns

trace()

Trace of the tensor calculated from cached eigenvalues.

lower_triangular

__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

Parameters
sphereSphere class instance
Returns
adcndarray

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

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

1

Westin C.-F., Peled S., Gubjartsson H., Kikinis R., Jolesz F., “Geometrical diffusion measures for MRI from tensor basis analysis” in Proc. 5th Annual ISMRM, 1997.

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
sphereSphere class instance.

The dODF is calculated in the vertices of this input.

Returns
odfndarray

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

1

Westin C.-F., Peled S., Gubjartsson H., Kikinis R., Jolesz F., “Geometrical diffusion measures for MRI from tensor basis analysis” in Proc. 5th Annual ISMRM, 1997.

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

Given a model fit, predict the signal on the vertices of a sphere

Parameters
gtaba GradientTable class instance

This encodes the directions for which a prediction is made

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

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.

Notes

The predicted signal is given by:

\[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

1

Westin C.-F., Peled S., Gubjartsson H., Kikinis R., Jolesz F., “Geometrical diffusion measures for MRI from tensor basis analysis” in Proc. 5th Annual ISMRM, 1997.

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

TensorModel

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

Bases: dipy.reconst.base.ReconstModel

Diffusion Tensor

Methods

fit(data[, mask])

Fit method of the DTI model class

predict(dti_params[, S0])

Predict a signal for this TensorModel class instance given parameters.

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

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

Parameters
gtabGradientTable 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

1

Basser, P.J., Mattiello, J., LeBihan, D., 1994. Estimation of the effective self-diffusion tensor from the NMR spin echo. J Magn Reson B 103, 247-254.

2

Basser, P., Pierpaoli, C., 1996. Microstructural and physiological features of tissues elucidated by quantitative diffusion-tensor MRI. Journal of Magnetic Resonance 111, 209-219.

3

Lin-Ching C., Jones D.K., Pierpaoli, C. 2005. RESTORE: Robust estimation of tensors by outlier rejection. MRM 53: 1088-1095

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

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.

auto_attr

dipy.reconst.dti.auto_attr(func)

Decorator to create OneTimeProperty attributes.

Parameters
funcmethod

The method that will be called the first time to compute a value. Afterwards, the method’s name will be a standard attribute holding the value of this computation.

Examples

>>> class MagicProp(object):
...     @auto_attr
...     def a(self):
...         return 99
...
>>> x = MagicProp()
>>> 'a' in x.__dict__
False
>>> x.a
99
>>> 'a' in x.__dict__
True

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

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

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

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

deviatoric

dipy.reconst.dti.deviatoric(q_form)

Calculate the deviatoric (anisotropic) 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_squigglendarray

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]):

\[\widetilde{A} = A - \bar{A}\]

Where \(A\) is the tensor quadratic form and \(\bar{A}\) is the anisotropic part of the tensor.

References

1(1,2,3)

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.

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.

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

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

geodesic_anisotropy

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

Geodesic anisotropy (GA) of a diffusion tensor.

Parameters
evalsarray-like

Eigenvalues of a diffusion tensor.

axisint

Axis of evals which contains 3 eigenvalues.

Returns
gaarray

Calculated GA. In the range 0 to +infinity

Notes

GA is calculated using the following equation given in [1]:

\[GA = \sqrt{\sum_{i=1}^3 \log^2{\left ( \lambda_i/<\mathbf{D}> \right )}}, \quad \textrm{where} \quad <\mathbf{D}> = (\lambda_1\lambda_2\lambda_3)^{1/3}\]

Note that the notation, \(<D>\), is often used as the mean diffusivity (MD) of the diffusion tensor and can lead to confusions in the literature (see [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(1,2,3,4)

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(1,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(1,2)

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.

get_sphere

dipy.reconst.dti.get_sphere(name='symmetric362')

provide triangulated spheres

Parameters
namestr

which sphere - one of: * ‘symmetric362’ * ‘symmetric642’ * ‘symmetric724’ * ‘repulsion724’ * ‘repulsion100’ * ‘repulsion200’

Returns
spherea dipy.core.sphere.Sphere class instance

Examples

>>> import numpy as np
>>> from dipy.data import get_sphere
>>> sphere = get_sphere('symmetric362')
>>> verts, faces = sphere.vertices, sphere.faces
>>> verts.shape == (362, 3)
True
>>> faces.shape == (720, 3)
True
>>> verts, faces = get_sphere('not a sphere name') 
Traceback (most recent call last):
    ...
DataError: No sphere called "not a sphere name"

gradient_table

dipy.reconst.dti.gradient_table(bvals, bvecs=None, big_delta=None, small_delta=None, b0_threshold=50, atol=0.01, btens=None)

A general function for creating diffusion MR gradients.

It reads, loads and prepares scanner parameters like the b-values and b-vectors so that they can be useful during the reconstruction process.

Parameters
bvalscan be any of the four options
  1. an array of shape (N,) or (1, N) or (N, 1) with the b-values.

  2. a path for the file which contains an array like the above (1).

  3. an array of shape (N, 4) or (4, N). Then this parameter is considered to be a b-table which contains both bvals and bvecs. In this case the next parameter is skipped.

  4. a path for the file which contains an array like the one at (3).

bvecscan be any of two options
  1. an array of shape (N, 3) or (3, N) with the b-vectors.

  2. a path for the file which contains an array like the previous.

big_deltafloat

acquisition pulse separation time in seconds (default None)

small_deltafloat

acquisition pulse duration time in seconds (default None)

b0_thresholdfloat

All b-values with values less than or equal to bo_threshold are considered as b0s i.e. without diffusion weighting.

atolfloat

All b-vectors need to be unit vectors up to a tolerance.

btenscan be any of three options
  1. a string specifying the shape of the encoding tensor for all volumes in data. Options: ‘LTE’, ‘PTE’, ‘STE’, ‘CTE’ corresponding to linear, planar, spherical, and “cigar-shaped” tensor encoding. Tensors are rotated so that linear and cigar tensors are aligned with the corresponding gradient direction and the planar tensor’s normal is aligned with the corresponding gradient direction. Magnitude is scaled to match the b-value.

  2. an array of strings of shape (N,), (N, 1), or (1, N) specifying encoding tensor shape for each volume separately. N corresponds to the number volumes in data. Options for elements in array: ‘LTE’, ‘PTE’, ‘STE’, ‘CTE’ corresponding to linear, planar, spherical, and “cigar-shaped” tensor encoding. Tensors are rotated so that linear and cigar tensors are aligned with the corresponding gradient direction and the planar tensor’s normal is aligned with the corresponding gradient direction. Magnitude is scaled to match the b-value.

  3. an array of shape (N,3,3) specifying the b-tensor of each volume exactly. N corresponds to the number volumes in data. No rotation or scaling is performed.

Returns
gradientsGradientTable

A GradientTable with all the gradient information.

Notes

  1. Often b0s (b-values which correspond to images without diffusion weighting) have 0 values however in some cases the scanner cannot provide b0s of an exact 0 value and it gives a bit higher values e.g. 6 or 12. This is the purpose of the b0_threshold in the __init__.

  2. We assume that the minimum number of b-values is 7.

  3. B-vectors should be unit vectors.

Examples

>>> from dipy.core.gradients import gradient_table
>>> bvals = 1500 * np.ones(7)
>>> bvals[0] = 0
>>> sq2 = np.sqrt(2) / 2
>>> bvecs = np.array([[0, 0, 0],
...                   [1, 0, 0],
...                   [0, 1, 0],
...                   [0, 0, 1],
...                   [sq2, sq2, 0],
...                   [sq2, 0, sq2],
...                   [0, sq2, sq2]])
>>> gt = gradient_table(bvals, bvecs)
>>> gt.bvecs.shape == bvecs.shape
True
>>> gt = gradient_table(bvals, bvecs.T)
>>> gt.bvecs.shape == bvecs.T.shape
False

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

1(1,2,3)

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.

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.

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

1(1,2)

Westin C.-F., Peled S., Gubjartsson H., Kikinis R., Jolesz F., “Geometrical diffusion measures for MRI from tensor basis analysis” in Proc. 5th Annual ISMRM, 1997.

lower_triangular

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

Returns the six lower triangular values of the tensor 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)

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

mode

dipy.reconst.dti.mode(q_form)

Mode (MO) of a diffusion 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
modearray

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]):

\[Mode = 3*\sqrt{6}*det(\widetilde{A}/norm(\widetilde{A}))\]

Where \(\widetilde{A}\) is the deviatoric part of the tensor quadratic form.

References

1(1,2,3)

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.

nlls_fit_tensor

dipy.reconst.dti.nlls_fit_tensor(design_matrix, data, weighting=None, sigma=None, jac=True, return_S0_hat=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.

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

voxel.

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.

See also

np.linalg.norm

Notes

The Frobenius norm is defined as:

Math

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

ols_fit_tensor

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

Computes ordinary least squares (OLS) fit to calculate self-diffusion tensor using a linear regression model [Rd310240b4eed-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

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

1(1,2,3,4,5,6,7,8,9,10,11,12)

Chung, SW., Lu, Y., Henry, R.G., 2006. Comparison of bootstrap approaches for estimation of uncertainties of DTI parameters. NeuroImage 33, 531-541.

pinv

dipy.reconst.dti.pinv(a, rcond=1e-15)

Vectorized version of numpy.linalg.pinv

If numpy version is less than 1.8, it falls back to iterating over np.linalg.pinv since there isn’t a vectorized version of np.linalg.svd available.

Parameters
aarray_like (…, M, N)

Matrix to be pseudo-inverted.

rcondfloat

Cutoff for small singular values.

Returns
Bndarray (…, N, M)

The pseudo-inverse of a.

Raises
LinAlgError

If the SVD computation does not converge.

See also

np.linalg.pinv

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

1(1,2)

Westin C.-F., Peled S., Gubjartsson H., Kikinis R., Jolesz F., “Geometrical diffusion measures for MRI from tensor basis analysis” in Proc. 5th Annual ISMRM, 1997.

quantize_evecs

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

Find the closest orientation of an evenly distributed sphere

Parameters
evecsndarray
odf_verticesNone or ndarray

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

Returns
INndarray

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

restore_fit_tensor

dipy.reconst.dti.restore_fit_tensor(design_matrix, data, sigma=None, jac=True, return_S0_hat=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

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

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.

Returns
restore_paramsan estimate of the tensor parameters in each voxel.

References

1(1,2,3)

Chang, L-C, Jones, DK and Pierpaoli, C (2005). RESTORE: robust

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

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

1(1,2)

Westin C.-F., Peled S., Gubjartsson H., Kikinis R., Jolesz F., “Geometrical diffusion measures for MRI from tensor basis analysis” in Proc. 5th Annual ISMRM, 1997.

tensor_prediction

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

Predict a signal given tensor parameters.

Parameters
dti_paramsndarray

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

gtaba GradientTable class instance

The gradient table for this prediction

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

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

vec_val_vect

dipy.reconst.dti.vec_val_vect()

Vectorize vecs.diag(vals).`vecs`.T for last 2 dimensions of vecs

Parameters
vecsshape (…, M, N) array

containing tensor in last two dimensions; M, N usually equal to (3, 3)

valsshape (…, N) array

diagonal values carried in last dimension, ... shape above must match that for vecs

Returns
resshape (…, M, M) array

For all the dimensions ellided by ..., loops to get (M, N) vec matrix, and (N,) vals vector, and calculates vec.dot(np.diag(val).dot(vec.T).

Raises
ValueErrornon-matching ... dimensions of vecs, vals
ValueErrornon-matching N dimensions of vecs, vals

Examples

Make a 3D array where the first dimension is only 1

>>> vecs = np.arange(9).reshape((1, 3, 3))
>>> vals = np.arange(3).reshape((1, 3))
>>> vec_val_vect(vecs, vals)
array([[[   9.,   24.,   39.],
        [  24.,   66.,  108.],
        [  39.,  108.,  177.]]])

That’s the same as the 2D case (apart from the float casting):

>>> vecs = np.arange(9).reshape((3, 3))
>>> vals = np.arange(3)
>>> np.dot(vecs, np.dot(np.diag(vals), vecs.T))
array([[  9,  24,  39],
       [ 24,  66, 108],
       [ 39, 108, 177]])

vector_norm

dipy.reconst.dti.vector_norm(vec, axis=- 1, keepdims=False)

Return vector Euclidean (L2) norm

See unit vector and Euclidean norm

Parameters
vecarray_like

Vectors to norm.

axisint

Axis over which to norm. By default norm over last axis. If axis is None, vec is flattened then normed.

keepdimsbool

If True, the output will have the same number of dimensions as vec, with shape 1 on axis.

Returns
normarray

Euclidean norms of vectors.

Examples

>>> import numpy as np
>>> vec = [[8, 15, 0], [0, 36, 77]]
>>> vector_norm(vec)
array([ 17.,  85.])
>>> vector_norm(vec, keepdims=True)
array([[ 17.],
       [ 85.]])
>>> vector_norm(vec, axis=0)
array([  8.,  39.,  77.])

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

1(1,2)

Chung, SW., Lu, Y., Henry, R.G., 2006. Comparison of bootstrap approaches for estimation of uncertainties of DTI parameters. NeuroImage 33, 531-541.

EuDXDirectionGetter

class dipy.reconst.eudx_direction_getter.EuDXDirectionGetter

Bases: dipy.tracking.direction_getter.DirectionGetter

Deterministic Direction Getter based on peak directions.

This class contains the cython portion of the code for PeaksAndMetrics and is not meant to be used on its own.

Attributes
ang_thr
qa_thr
total_weight

Methods

initial_direction

The best starting directions for fiber tracking from point

generate_streamline

get_direction

__init__(*args, **kwargs)
ang_thr
initial_direction()

The best starting directions for fiber tracking from point

All the valid peaks in the voxel closest to point are returned as initial directions.

qa_thr
total_weight

Cache

class dipy.reconst.forecast.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)

Methods

cache_clear()

Clear the cache.

cache_get(tag, key[, default])

Retrieve a value from the cache.

cache_set(tag, key, value)

Store a value in the cache.

__init__(*args, **kwargs)
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

ForecastFit

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

Bases: dipy.reconst.odf.OdfFit

Attributes
dpar

The parallel diffusivity

dperp

The perpendicular diffusivity

sh_coeff

The FORECAST SH coefficients

Methods

fractional_anisotropy()

Calculates the fractional anisotropy.

mean_diffusivity()

Calculates the mean diffusivity.

odf(sphere[, clip_negative])

Calculates the fODF for a given discrete sphere.

predict([gtab, S0])

Calculates the fODF for a given discrete sphere.

__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

ForecastModel

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

Bases: dipy.reconst.odf.OdfModel, dipy.reconst.cache.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]

Notes

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

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 E. et al., “A generalized SMT-based framework for Diffusion MRI microstructural model estimation”, MICCAI Workshop on Computational DIFFUSION MRI (CDMRI), 2017.

Methods

cache_clear()

Clear the cache.

cache_get(tag, key[, default])

Retrieve a value from the cache.

cache_set(tag, key, value)

Store a value in the cache.

fit(data[, mask])

Fit method for every voxel in data

__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
gtabGradientTable,

gradient directions and bvalues container class.

sh_orderunsigned int,

an even integer that represent the SH order of the basis (max 12)

lambda_lb: float,

Laplace-Beltrami regularization weight.

dec_algstr,

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

spherearray, shape (N,3),

sphere points where to enforce positivity when ‘POS’ or ‘CSD’ dec_alg are selected.

lambda_csdfloat,

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

OdfFit

class dipy.reconst.forecast.OdfFit(model, data)

Bases: dipy.reconst.base.ReconstFit

Methods

odf(sphere)

To be implemented but specific odf models

__init__(model, data)
odf(sphere)

To be implemented but specific odf models

OdfModel

class dipy.reconst.forecast.OdfModel(gtab)

Bases: dipy.reconst.base.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.

Methods

fit(data)

To be implemented by specific odf models

__init__(gtab)

Initialization of the abstract class for signal reconstruction models

Parameters
gtabGradientTable class instance
fit(data)

To be implemented by specific odf models

Version

class dipy.reconst.forecast.Version(version: str)

Bases: packaging.version._BaseVersion

Attributes
base_version
dev
epoch
is_devrelease
is_postrelease
is_prerelease
local
major
micro
minor
post
pre
public
release
__init__(version: str) None
property base_version: str
property dev: Optional[int]
property epoch: int
property is_devrelease: bool
property is_postrelease: bool
property is_prerelease: bool
property local: Optional[str]
property major: int
property micro: int
property minor: int
property post: Optional[int]
property pre: Optional[Tuple[str, int]]
property public: str
property release: Tuple[int, ...]

cart2sphere

dipy.reconst.forecast.cart2sphere(x, y, z)

Return angles for Cartesian 3D coordinates x, y, and z

See doc for sphere2cart for angle conventions and derivation of the formulae.

\(0\le\theta\mathrm{(theta)}\le\pi\) and \(-\pi\le\phi\mathrm{(phi)}\le\pi\)

Parameters
xarray_like

x coordinate in Cartesian space

yarray_like

y coordinate in Cartesian space

zarray_like

z coordinate

Returns
rarray

radius

thetaarray

inclination (polar) angle

phiarray

azimuth angle

csdeconv

dipy.reconst.forecast.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
dwsignalarray

Diffusion weighted signals to be deconvolved.

Xarray

Prediction matrix which estimates diffusion weighted signals from FOD coefficients.

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

taufloat

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.

convergenceint

Maximum number of iterations to allow the deconvolution to converge.

Pndarray

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_shndarray ((sh_order + 1)*(sh_order + 2)/2,)

Spherical harmonics coefficients of the constrained-regularized fiber ODF.

num_itint

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(1,2)

Tournier, J.D., et al. NeuroImage 2007. Robust determination of the fibre orientation distribution in diffusion MRI: Non-negativity constrained super-resolved spherical deconvolution.

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

forecast_matrix

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

Compute the FORECAST radial matrix

lb_forecast

dipy.reconst.forecast.lb_forecast(sh_order)

Returns the Laplace-Beltrami regularization matrix for FORECAST

leastsq

dipy.reconst.forecast.leastsq(func, x0, args=(), Dfun=None, full_output=0, col_deriv=0, ftol=1.49012e-08, xtol=1.49012e-08, gtol=0.0, maxfev=0, epsfcn=None, factor=100, diag=None)

Minimize the sum of squares of a set of equations.

x = arg min(sum(func(y)**2,axis=0))
         y
Parameters
funccallable

Should take at least one (possibly length N vector) argument and returns M floating point numbers. It must not return NaNs or fitting might fail. M must be greater than or equal to N.

x0ndarray

The starting estimate for the minimization.

argstuple, optional

Any extra arguments to func are placed in this tuple.

Dfuncallable, optional

A function or method to compute the Jacobian of func with derivatives across the rows. If this is None, the Jacobian will be estimated.

full_outputbool, optional

non-zero to return all optional outputs.

col_derivbool, optional

non-zero to specify that the Jacobian function computes derivatives down the columns (faster, because there is no transpose operation).

ftolfloat, optional

Relative error desired in the sum of squares.

xtolfloat, optional

Relative error desired in the approximate solution.

gtolfloat, optional

Orthogonality desired between the function vector and the columns of the Jacobian.

maxfevint, optional

The maximum number of calls to the function. If Dfun is provided, then the default maxfev is 100*(N+1) where N is the number of elements in x0, otherwise the default maxfev is 200*(N+1).

epsfcnfloat, optional

A variable used in determining a suitable step length for the forward- difference approximation of the Jacobian (for Dfun=None). Normally the actual step length will be sqrt(epsfcn)*x If epsfcn is less than the machine precision, it is assumed that the relative errors are of the order of the machine precision.

factorfloat, optional

A parameter determining the initial step bound (factor * || diag * x||). Should be in interval (0.1, 100).

diagsequence, optional

N positive entries that serve as a scale factors for the variables.

Returns
xndarray

The solution (or the result of the last iteration for an unsuccessful call).

cov_xndarray

The inverse of the Hessian. fjac and ipvt are used to construct an estimate of the Hessian. A value of None indicates a singular matrix, which means the curvature in parameters x is numerically flat. To obtain the covariance matrix of the parameters x, cov_x must be multiplied by the variance of the residuals – see curve_fit.

infodictdict

a dictionary of optional outputs with the keys:

nfev

The number of function calls

fvec

The function evaluated at the output

fjac

A permutation of the R matrix of a QR factorization of the final approximate Jacobian matrix, stored column wise. Together with ipvt, the covariance of the estimate can be approximated.

ipvt

An integer array of length N which defines a permutation matrix, p, such that fjac*p = q*r, where r is upper triangular with diagonal elements of nonincreasing magnitude. Column j of p is column ipvt(j) of the identity matrix.

qtf

The vector (transpose(q) * fvec).

mesgstr

A string message giving information about the cause of failure.

ierint

An integer flag. If it is equal to 1, 2, 3 or 4, the solution was found. Otherwise, the solution was not found. In either case, the optional output variable ‘mesg’ gives more information.

See also

least_squares

Newer interface to solve nonlinear least-squares problems with bounds on the variables. See method=='lm' in particular.

Notes

“leastsq” is a wrapper around MINPACK’s lmdif and lmder algorithms.

cov_x is a Jacobian approximation to the Hessian of the least squares objective function. This approximation assumes that the objective function is based on the difference between some observed target data (ydata) and a (non-linear) function of the parameters f(xdata, params)

func(params) = ydata - f(xdata, params)

so that the objective function is

  min   sum((ydata - f(xdata, params))**2, axis=0)
params

The solution, x, is always a 1-D array, regardless of the shape of x0, or whether x0 is a scalar.

Examples

>>> from scipy.optimize import leastsq
>>> def func(x):
...     return 2*(x-3)**2+1
>>> leastsq(func, 0)
(array([2.99999999]), 1)

multi_voxel_fit

dipy.reconst.forecast.multi_voxel_fit(single_voxel_fit)

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

optional_package

dipy.reconst.forecast.optional_package(name, trip_msg=None)

Return package-like thing and module setup for package name

Parameters
namestr

package name

trip_msgNone or str

message to give when someone tries to use the return package, but we could not import it, and have returned a TripWire object instead. Default message if None.

Returns
pkg_likemodule or TripWire instance

If we can import the package, return it. Otherwise return an object raising an error when accessed

have_pkgbool

True if import for package was successful, false otherwise

module_setupfunction

callable usually set as setup_module in calling namespace, to allow skipping tests.

Examples

Typical use would be something like this at the top of a module using an optional package:

>>> from dipy.utils.optpkg import optional_package
>>> pkg, have_pkg, setup_module = optional_package('not_a_package')

Of course in this case the package doesn’t exist, and so, in the module:

>>> have_pkg
False

and

>>> pkg.some_function() 
Traceback (most recent call last):
    ...
TripWireError: We need package not_a_package for these functions, but
``import not_a_package`` raised an ImportError

If the module does exist - we get the module

>>> pkg, _, _ = optional_package('os')
>>> hasattr(pkg, 'path')
True

Or a submodule if that’s what we asked for

>>> subpkg, _, _ = optional_package('os.path')
>>> hasattr(subpkg, 'dirname')
True

psi_l

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

real_sh_descoteaux_from_index

dipy.reconst.forecast.real_sh_descoteaux_from_index(m, n, theta, phi, legacy=True)

Compute real spherical harmonics as in Descoteaux et al. 2007 [Rded9a56186a6-1], where the real harmonic \(Y^m_n\) is defined to be:

Imag(\(Y^m_n\)) * sqrt(2) if m > 0 \(Y^0_n\) if m = 0 Real(\(Y^m_n\)) * sqrt(2) if m < 0

This may take scalar or array arguments. The inputs will be broadcasted against each other.

Parameters
mint |m| <= n

The degree of the harmonic.

nint >= 0

The order of the harmonic.

thetafloat [0, pi]

The polar (colatitudinal) coordinate.

phifloat [0, 2*pi]

The azimuthal (longitudinal) coordinate.

legacy: bool, optional

If true, uses DIPY’s legacy descoteaux07 implementation (where |m| is used for m < 0). Else, implements the basis as defined in Descoteaux et al. 2007 (without the absolute value).

Returns
real_shreal float

The real harmonic \(Y^m_n\) sampled at theta and phi.

rho_matrix

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

Compute the SH matrix \(\rho\)

warn

dipy.reconst.forecast.warn(/, message, category=None, stacklevel=1, source=None)

Issue a warning, or maybe ignore it or raise an exception.

FreeWaterTensorFit

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

Bases: dipy.reconst.dti.TensorFit

Class for fitting the Free Water Tensor Model

Attributes
S0_hat
directions

For tracking - return the primary direction in each voxel

evals

Returns the eigenvalues of the tensor as an array

evecs

Returns the eigenvectors of the tensor as an array, columnwise

f

Returns the free water diffusion volume fraction f

quadratic_form

Calculates the 3x3 diffusion tensor for each voxel

shape

Methods

ad()

Axial diffusivity (AD) calculated from cached eigenvalues.

adc(sphere)

Calculate the apparent diffusion coefficient (ADC) in each direction on

color_fa()

Color fractional anisotropy of diffusion tensor

fa()

Fractional anisotropy (FA) calculated from cached eigenvalues.

ga()

Geodesic anisotropy (GA) calculated from cached eigenvalues.

linearity()

Returns

md()

Mean diffusivity (MD) calculated from cached eigenvalues.

mode()

Tensor mode calculated from cached eigenvalues.

odf(sphere)

The diffusion orientation distribution function (dODF).

planarity()

Returns

predict(gtab[, S0])

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

rd()

Radial diffusivity (RD) calculated from cached eigenvalues.

sphericity()

Returns

trace()

Trace of the tensor calculated from cached eigenvalues.

lower_triangular

__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

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

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

FreeWaterTensorModel

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

Bases: dipy.reconst.base.ReconstModel

Class for the Free Water Elimination Diffusion Tensor Model

Methods

fit(data[, mask])

Fit method for every voxel in data

predict(fwdti_params[, S0])

Predict a signal for this TensorModel class instance given parameters.

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

Free Water Diffusion Tensor Model [1].

Parameters
gtabGradientTable class instance
fit_methodstr 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

1(1,2,3)

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

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

ReconstModel

class dipy.reconst.fwdti.ReconstModel(gtab)

Bases: object

Abstract class for signal reconstruction models

Methods

fit

__init__(gtab)

Initialization of the abstract class for signal reconstruction models

Parameters
gtabGradientTable class instance
fit(data, mask=None, **kwargs)

TensorFit

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

Bases: object

Attributes
S0_hat
directions

For tracking - return the primary direction in each voxel

evals

Returns the eigenvalues of the tensor as an array

evecs

Returns the eigenvectors of the tensor as an array, columnwise

quadratic_form

Calculates the 3x3 diffusion tensor for each voxel

shape

Methods

ad()

Axial diffusivity (AD) calculated from cached eigenvalues.

adc(sphere)

Calculate the apparent diffusion coefficient (ADC) in each direction on

color_fa()

Color fractional anisotropy of diffusion tensor

fa()

Fractional anisotropy (FA) calculated from cached eigenvalues.

ga()

Geodesic anisotropy (GA) calculated from cached eigenvalues.

linearity()

Returns

md()

Mean diffusivity (MD) calculated from cached eigenvalues.

mode()

Tensor mode calculated from cached eigenvalues.

odf(sphere)

The diffusion orientation distribution function (dODF).

planarity()

Returns

predict(gtab[, S0, step])

Given a model fit, predict the signal on the vertices of a sphere

rd()

Radial diffusivity (RD) calculated from cached eigenvalues.

sphericity()

Returns

trace()

Trace of the tensor calculated from cached eigenvalues.

lower_triangular

__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

Parameters
sphereSphere class instance
Returns
adcndarray

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

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

1

Westin C.-F., Peled S., Gubjartsson H., Kikinis R., Jolesz F., “Geometrical diffusion measures for MRI from tensor basis analysis” in Proc. 5th Annual ISMRM, 1997.

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
sphereSphere class instance.

The dODF is calculated in the vertices of this input.

Returns
odfndarray

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

1

Westin C.-F., Peled S., Gubjartsson H., Kikinis R., Jolesz F., “Geometrical diffusion measures for MRI from tensor basis analysis” in Proc. 5th Annual ISMRM, 1997.

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

Given a model fit, predict the signal on the vertices of a sphere

Parameters
gtaba GradientTable class instance

This encodes the directions for which a prediction is made

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

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.

Notes

The predicted signal is given by:

\[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

1

Westin C.-F., Peled S., Gubjartsson H., Kikinis R., Jolesz F., “Geometrical diffusion measures for MRI from tensor basis analysis” in Proc. 5th Annual ISMRM, 1997.

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

check_multi_b

dipy.reconst.fwdti.check_multi_b(gtab, n_bvals, non_zero=True, bmag=None)

Check if you have enough different b-values in your gradient table

Parameters
gtabGradientTable class instance.
n_bvalsint

The number of different b-values you are checking for.

non_zerobool

Whether to check only non-zero bvalues. In this case, we will require at least n_bvals non-zero b-values (where non-zero is defined depending on the gtab object’s b0_threshold attribute)

bmagint

The order of magnitude of the b-values used. The function will normalize the b-values relative \(10^{bmag}\). Default: derive this value from the maximal b-value provided: \(bmag=log_{10}(max(bvals)) - 1\).

Returns
boolWhether there are at least n_bvals different b-values in the
gradient table used.

cholesky_to_lower_triangular

dipy.reconst.fwdti.cholesky_to_lower_triangular(R)

Convert Cholesky decompostion 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

1

Koay, C.G., Carew, J.D., Alexander, A.L., Basser, P.J., Meyerand, M.E., 2006. Investigation of anomalous estimates of tensor-derived quantities in diffusion tensor imaging. Magnetic Resonance in Medicine, 55(4), 930-936. doi:10.1002/mrm.20832

decompose_tensor

dipy.reconst.fwdti.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.fwdti.design_matrix(gtab, dtype=None)

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

Parameters
gtabA 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)

from_lower_triangular

dipy.reconst.fwdti.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

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.

gtaba GradientTable class instance

The gradient table for this prediction

S0float or ndarray

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

Disofloat, 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

lower_triangular

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

Returns the six lower triangular values of the tensor 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)

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

1

Koay, C.G., Carew, J.D., Alexander, A.L., Basser, P.J., Meyerand, M.E., 2006. Investigation of anomalous estimates of tensor-derived quantities in diffusion tensor imaging. Magnetic Resonance in Medicine, 55(4), 930-936. doi:10.1002/mrm.20832

multi_voxel_fit

dipy.reconst.fwdti.multi_voxel_fit(single_voxel_fit)

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

ndindex

dipy.reconst.fwdti.ndindex(shape)

An N-dimensional iterator object to index arrays.

Given the shape of an array, an ndindex instance iterates over the N-dimensional index of the array. At each iteration a tuple of indices is returned; the last dimension is iterated over first.

Parameters
shapetuple of ints

The dimensions of the array.

Examples

>>> from dipy.core.ndindex import ndindex
>>> shape = (3, 2, 1)
>>> for index in ndindex(shape):
...     print(index)
(0, 0, 0)
(0, 1, 0)
(1, 0, 0)
(1, 1, 0)
(2, 0, 0)
(2, 1, 0)

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
gtaba GradientTable class instance

The gradient table containing diffusion acquisition parameters.

datandarray ([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.

maskarray, optional

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

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

mdregfloat, 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_signalfloat

The minimum signal value. Needs to be a strictly positive number. Default: 1.0e-6.

f_transformbool, 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

choleskybool, optional

If true it uses Cholesky decomposition to insure that diffusion tensor is positive define. Default: False

jacbool

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

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_matrixarray (g, 7)

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

sigarray (g, )

Diffusion-weighted signal for a single voxel data.

S0float

Non diffusion weighted signal (i.e. signal for b-value=0).

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

mdregfloat, 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_signalfloat

The minimum signal value. Needs to be a strictly positive number.

choleskybool, optional

If true it uses Cholesky decomposition to insure that diffusion tensor is positive define. Default: False

f_transformbool, 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

jacbool

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.

vec_val_vect

dipy.reconst.fwdti.vec_val_vect()

Vectorize vecs.diag(vals).`vecs`.T for last 2 dimensions of vecs

Parameters
vecsshape (…, M, N) array

containing tensor in last two dimensions; M, N usually equal to (3, 3)

valsshape (…, N) array

diagonal values carried in last dimension, ... shape above must match that for vecs

Returns
resshape (…, M, M) array

For all the dimensions ellided by ..., loops to get (M, N) vec matrix, and (N,) vals vector, and calculates vec.dot(np.diag(val).dot(vec.T).

Raises
ValueErrornon-matching ... dimensions of vecs, vals
ValueErrornon-matching N dimensions of vecs, vals

Examples

Make a 3D array where the first dimension is only 1

>>> vecs = np.arange(9).reshape((1, 3, 3))
>>> vals = np.arange(3).reshape((1, 3))
>>> vec_val_vect(vecs, vals)
array([[[   9.,   24.,   39.],
        [  24.,   66.,  108.],
        [  39.,  108.,  177.]]])

That’s the same as the 2D case (apart from the float casting):

>>> vecs = np.arange(9).reshape((3, 3))
>>> vals = np.arange(3)
>>> np.dot(vecs, np.dot(np.diag(vals), vecs.T))
array([[  9,  24,  39],
       [ 24,  66, 108],
       [ 39, 108, 177]])

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
gtaba GradientTable class instance

The gradient table containing diffusion acquisition parameters.

datandarray ([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.

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

maskarray, optional

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

min_signalfloat

The minimum signal value. Needs to be a strictly positive number. Default: 1.0e-6.

piterationsinter, optional

Number of iterations used to refine the precision of f. Default is set to 3 corresponding to a precision of 0.01.

mdregfloat, 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_paramsndarray (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(1,2)

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_matrixarray (g, 7)

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

sigarray (g, )

Diffusion-weighted signal for a single voxel data.

S0float

Non diffusion weighted signal (i.e. signal for b-value=0).

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

mdregfloat, 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_signalfloat

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

piterationsinter, 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

Cache

class dipy.reconst.gqi.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)

Methods

cache_clear()

Clear the cache.

cache_get(tag, key[, default])

Retrieve a value from the cache.

cache_set(tag, key, value)

Store a value in the cache.

__init__(*args, **kwargs)
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

GeneralizedQSamplingFit

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

Bases: dipy.reconst.odf.OdfFit

Methods

odf(sphere)

Calculates the discrete ODF for a given discrete sphere.

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

GeneralizedQSamplingModel

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

Bases: dipy.reconst.odf.OdfModel, dipy.reconst.cache.Cache

Methods

cache_clear()

Clear the cache.

cache_get(tag, key[, default])

Retrieve a value from the cache.

cache_set(tag, key, value)

Store a value in the cache.

fit(data[, mask])

Fit method for every voxel in data

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

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

References

1(1,2,3)

Yeh F-C et al., “Generalized Q-Sampling Imaging”, IEEE TMI, 2010

2(1,2)

Garyfallidis E, “Towards an accurate brain tractography”, PhD

thesis, University of Cambridge, 2012.

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)
fit(data, mask=None)

Fit method for every voxel in data

OdfFit

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

Bases: dipy.reconst.base.ReconstFit

Methods

odf(sphere)

To be implemented but specific odf models

__init__(model, data)
odf(sphere)

To be implemented but specific odf models

OdfModel

class dipy.reconst.gqi.OdfModel(gtab)

Bases: dipy.reconst.base.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.

Methods

fit(data)

To be implemented by specific odf models

__init__(gtab)

Initialization of the abstract class for signal reconstruction models

Parameters
gtabGradientTable class instance
fit(data)

To be implemented by specific odf models

equatorial_maximum

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

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

multi_voxel_fit

dipy.reconst.gqi.multi_voxel_fit(single_voxel_fit)

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

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.

npa

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

non-parametric anisotropy

Nimmo-Smith et al. ISMRM 2011

odf_sum

dipy.reconst.gqi.odf_sum(odf)

patch_maximum

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

patch_sum

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

patch_vertices

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

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

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

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

triple_odf_maxima

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

upper_hemi_map

dipy.reconst.gqi.upper_hemi_map(v)

maps a 3-vector into the z-upper hemisphere

IvimFit

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

Bases: object

Attributes
D
D_star
S0_predicted
perfusion_fraction
shape

Methods

predict(gtab[, S0])

Given a model fit, predict the signal.

__init__(model, model_params)

Initialize a IvimFit class instance.

Parameters
modelModel 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

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: dipy.reconst.base.ReconstModel

Ivim model

Methods

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.

estimate_linear_fit(data, split_b[, less_than])

Estimate a linear fit by taking log of data.

fit(data[, mask])

Fit method for every voxel in data

predict(ivim_params, gtab[, S0])

Predict a signal for this IvimModel class instance given parameters.

__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, 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

1

Le Bihan, Denis, et al. “Separation of diffusion and perfusion in intravoxel incoherent motion MR imaging.” Radiology 168.2 (1988): 497-505.

2

Federau, Christian, et al. “Quantitative measurement of brain perfusion with intravoxel incoherent motion MR imaging.” Radiology 265.3 (2012): 874-881.

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: dipy.reconst.base.ReconstModel

Methods

cvx_fit(signal, phi)

Performs the constrained search for the linear parameters f after the estimation of x is done.

fit(data[, mask])

Fit method for every voxel in data

ivim_mix_cost_one(phi, signal)

Constructs the objective for the :func: stoc_search_cost.

nlls_cost(x_f, signal)

Cost function for the least square problem.

phi(x)

Creates a structure for the combining the diffusion and pseudo- diffusion by multipling with the bvals and then exponentiating each of the two components for fitting as per the IVIM- two compartment model.

stoc_search_cost(x, signal)

Cost function for differential evolution algorithm.

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.

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.

__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

1

Le Bihan, Denis, et al. “Separation of diffusion and perfusion in intravoxel incoherent motion MR imaging.” Radiology 168.2 (1988): 497-505.

2

Federau, Christian, et al. “Quantitative measurement of brain perfusion with intravoxel incoherent motion MR imaging.” Radiology 265.3 (2012): 874-881.

3

Fadnavis, Shreyas et.al. “MicroLearn: Framework for machine learning, reconstruction, optimization and microstructure modeling, Proceedings of: International Society of Magnetic Resonance in Medicine (ISMRM), Montreal, Canada, 2019.

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

1

Fadnavis, Shreyas et.al. “MicroLearn: Framework for machine learning, reconstruction, optimization and microstructure modeling, Proceedings of: International Society of Magnetic Resonance in Medicine (ISMRM), Montreal, Canada, 2019.

2

Farooq, Hamza, et al. “Microstructure Imaging of Crossing (MIX) White Matter Fibers from diffusion MRI.” Scientific reports 6 (2016).

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 multipling 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 funtion 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

Splitted 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

Splitted parameters into two separate arrays

ReconstModel

class dipy.reconst.ivim.ReconstModel(gtab)

Bases: object

Abstract class for signal reconstruction models

Methods

fit

__init__(gtab)

Initialization of the abstract class for signal reconstruction models

Parameters
gtabGradientTable class instance
fit(data, mask=None, **kwargs)

Version

class dipy.reconst.ivim.Version(version: str)

Bases: packaging.version._BaseVersion

Attributes
base_version
dev
epoch
is_devrelease
is_postrelease
is_prerelease
local
major
micro
minor
post
pre
public
release
__init__(version: str) None
property base_version: str
property dev: Optional[int]
property epoch: int
property is_devrelease: bool
property is_postrelease: bool
property is_prerelease: bool
property local: Optional[str]
property major: int
property micro: int
property minor: int
property post: Optional[int]
property pre: Optional[Tuple[str, int]]
property public: str
property release: Tuple[int, ...]

IvimModel

dipy.reconst.ivim.IvimModel(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

differential_evolution

dipy.reconst.ivim.differential_evolution(func, bounds, args=(), strategy='best1bin', maxiter=1000, popsize=15, tol=0.01, mutation=(0.5, 1), recombination=0.7, seed=None, callback=None, disp=False, polish=True, init='latinhypercube', atol=0, updating='immediate', workers=1, constraints=(), x0=None)

Finds the global minimum of a multivariate function.

Differential Evolution is stochastic in nature (does not use gradient methods) to find the minimum, and can search large areas of candidate space, but often requires larger numbers of function evaluations than conventional gradient-based techniques.

The algorithm is due to Storn and Price [1].

Parameters
funccallable

The objective function to be minimized. Must be in the form f(x, *args), where x is the argument in the form of a 1-D array and args is a tuple of any additional fixed parameters needed to completely specify the function.

boundssequence or Bounds

Bounds for variables. There are two ways to specify the bounds: 1. Instance of Bounds class. 2. (min, max) pairs for each element in x, defining the finite lower and upper bounds for the optimizing argument of func. It is required to have len(bounds) == len(x). len(bounds) is used to determine the number of parameters in x.

argstuple, optional

Any additional fixed parameters needed to completely specify the objective function.

strategystr, optional

The differential evolution strategy to use. Should be one of:

  • ‘best1bin’

  • ‘best1exp’

  • ‘rand1exp’

  • ‘randtobest1exp’

  • ‘currenttobest1exp’

  • ‘best2exp’

  • ‘rand2exp’

  • ‘randtobest1bin’

  • ‘currenttobest1bin’

  • ‘best2bin’

  • ‘rand2bin’

  • ‘rand1bin’

The default is ‘best1bin’.

maxiterint, optional

The maximum number of generations over which the entire population is evolved. The maximum number of function evaluations (with no polishing) is: (maxiter + 1) * popsize * len(x)

popsizeint, optional

A multiplier for setting the total population size. The population has popsize * len(x) individuals. This keyword is overridden if an initial population is supplied via the init keyword. When using init='sobol' the population size is calculated as the next power of 2 after popsize * len(x).

tolfloat, optional

Relative tolerance for convergence, the solving stops when np.std(pop) <= atol + tol * np.abs(np.mean(population_energies)), where and atol and tol are the absolute and relative tolerance respectively.

mutationfloat or tuple(float, float), optional

The mutation constant. In the literature this is also known as differential weight, being denoted by F. If specified as a float it should be in the range [0, 2]. If specified as a tuple (min, max) dithering is employed. Dithering randomly changes the mutation constant on a generation by generation basis. The mutation constant for that generation is taken from U[min, max). Dithering can help speed convergence significantly. Increasing the mutation constant increases the search radius, but will slow down convergence.

recombinationfloat, optional

The recombination constant, should be in the range [0, 1]. In the literature this is also known as the crossover probability, being denoted by CR. Increasing this value allows a larger number of mutants to progress into the next generation, but at the risk of population stability.

seed{None, int, numpy.random.Generator,

numpy.random.RandomState}, optional

If seed is None (or np.random), the numpy.random.RandomState singleton is used. If seed is an int, a new RandomState instance is used, seeded with seed. If seed is already a Generator or RandomState instance then that instance is used. Specify seed for repeatable minimizations.

dispbool, optional

Prints the evaluated func at every iteration.

callbackcallable, callback(xk, convergence=val), optional

A function to follow the progress of the minimization. xk is the current value of x0. val represents the fractional value of the population convergence. When val is greater than one the function halts. If callback returns True, then the minimization is halted (any polishing is still carried out).

polishbool, optional

If True (default), then scipy.optimize.minimize with the L-BFGS-B method is used to polish the best population member at the end, which can improve the minimization slightly. If a constrained problem is being studied then the trust-constr method is used instead.

initstr or array-like, optional

Specify which type of population initialization is performed. Should be one of:

  • ‘latinhypercube’

  • ‘sobol’

  • ‘halton’

  • ‘random’

  • array specifying the initial population. The array should have shape (M, len(x)), where M is the total population size and len(x) is the number of parameters. init is clipped to bounds before use.

The default is ‘latinhypercube’. Latin Hypercube sampling tries to maximize coverage of the available parameter space.

‘sobol’ and ‘halton’ are superior alternatives and maximize even more the parameter space. ‘sobol’ will enforce an initial population size which is calculated as the next power of 2 after popsize * len(x). ‘halton’ has no requirements but is a bit less efficient. See scipy.stats.qmc for more details.

‘random’ initializes the population randomly - this has the drawback that clustering can occur, preventing the whole of parameter space being covered. Use of an array to specify a population could be used, for example, to create a tight bunch of initial guesses in an location where the solution is known to exist, thereby reducing time for convergence.

atolfloat, optional

Absolute tolerance for convergence, the solving stops when np.std(pop) <= atol + tol * np.abs(np.mean(population_energies)), where and atol and tol are the absolute and relative tolerance respectively.

updating{‘immediate’, ‘deferred’}, optional

If 'immediate', the best solution vector is continuously updated within a single generation [4]. This can lead to faster convergence as trial vectors can take advantage of continuous improvements in the best solution. With 'deferred', the best solution vector is updated once per generation. Only 'deferred' is compatible with parallelization, and the workers keyword can over-ride this option.

New in version 1.2.0.

workersint or map-like callable, optional

If workers is an int the population is subdivided into workers sections and evaluated in parallel (uses multiprocessing.Pool <multiprocessing>). Supply -1 to use all available CPU cores. Alternatively supply a map-like callable, such as multiprocessing.Pool.map for evaluating the population in parallel. This evaluation is carried out as workers(func, iterable). This option will override the updating keyword to updating='deferred' if workers != 1. Requires that func be pickleable.

New in version 1.2.0.

constraints{NonLinearConstraint, LinearConstraint, Bounds}

Constraints on the solver, over and above those applied by the bounds kwd. Uses the approach by Lampinen [5].

New in version 1.4.0.

x0None or array-like, optional

Provides an initial guess to the minimization. Once the population has been initialized this vector replaces the first (best) member. This replacement is done even if init is given an initial population.

New in version 1.7.0.

Returns
resOptimizeResult

The optimization result represented as a OptimizeResult object. Important attributes are: x the solution array, success a Boolean flag indicating if the optimizer exited successfully and message which describes the cause of the termination. See OptimizeResult for a description of other attributes. If polish was employed, and a lower minimum was obtained by the polishing, then OptimizeResult also contains the jac attribute. If the eventual solution does not satisfy the applied constraints success will be False.

Notes

Differential evolution is a stochastic population based method that is useful for global optimization problems. At each pass through the population the algorithm mutates each candidate solution by mixing with other candidate solutions to create a trial candidate. There are several strategies [2] for creating trial candidates, which suit some problems more than others. The ‘best1bin’ strategy is a good starting point for many systems. In this strategy two members of the population are randomly chosen. Their difference is used to mutate the best member (the ‘best’ in ‘best1bin’), \(b_0\), so far:

\[b' = b_0 + mutation * (population[rand0] - population[rand1])\]

A trial vector is then constructed. Starting with a randomly chosen ith parameter the trial is sequentially filled (in modulo) with parameters from b' or the original candidate. The choice of whether to use b' or the original candidate is made with a binomial distribution (the ‘bin’ in ‘best1bin’) - a random number in [0, 1) is generated. If this number is less than the recombination constant then the parameter is loaded from b', otherwise it is loaded from the original candidate. The final parameter is always loaded from b'. Once the trial candidate is built its fitness is assessed. If the trial is better than the original candidate then it takes its place. If it is also better than the best overall candidate it also replaces that. To improve your chances of finding a global minimum use higher popsize values, with higher mutation and (dithering), but lower recombination values. This has the effect of widening the search radius, but slowing convergence. By default the best solution vector is updated continuously within a single iteration (updating='immediate'). This is a modification [4] of the original differential evolution algorithm which can lead to faster convergence as trial vectors can immediately benefit from improved solutions. To use the original Storn and Price behaviour, updating the best solution once per iteration, set updating='deferred'.

New in version 0.15.0.

References

1

Storn, R and Price, K, Differential Evolution - a Simple and Efficient Heuristic for Global Optimization over Continuous Spaces, Journal of Global Optimization, 1997, 11, 341 - 359.

2

http://www1.icsi.berkeley.edu/~storn/code.html

3

http://en.wikipedia.org/wiki/Differential_evolution

4(1,2)

Wormington, M., Panaccione, C., Matney, K. M., Bowen, D. K., - Characterization of structures from X-ray scattering data using genetic algorithms, Phil. Trans. R. Soc. Lond. A, 1999, 357, 2827-2848

5

Lampinen, J., A constraint handling approach for the differential evolution algorithm. Proceedings of the 2002 Congress on Evolutionary Computation. CEC’02 (Cat. No. 02TH8600). Vol. 2. IEEE, 2002.

Examples

Let us consider the problem of minimizing the Rosenbrock function. This function is implemented in rosen in scipy.optimize.

>>> from scipy.optimize import rosen, differential_evolution
>>> bounds = [(0,2), (0, 2), (0, 2), (0, 2), (0, 2)]
>>> result = differential_evolution(rosen, bounds)
>>> result.x, result.fun
(array([1., 1., 1., 1., 1.]), 1.9216496320061384e-19)

Now repeat, but with parallelization.

>>> bounds = [(0,2), (0, 2), (0, 2), (0, 2), (0, 2)]
>>> result = differential_evolution(rosen, bounds, updating='deferred',
...                                 workers=2)
>>> result.x, result.fun
(array([1., 1., 1., 1., 1.]), 1.9216496320061384e-19)

Let’s try and do a constrained minimization

>>> from scipy.optimize import NonlinearConstraint, Bounds
>>> def constr_f(x):
...     return np.array(x[0] + x[1])
>>>
>>> # the sum of x[0] and x[1] must be less than 1.9
>>> nlc = NonlinearConstraint(constr_f, -np.inf, 1.9)
>>> # specify limits using a `Bounds` object.
>>> bounds = Bounds([0., 0.], [2., 2.])
>>> result = differential_evolution(rosen, bounds, constraints=(nlc),
...                                 seed=1)
>>> result.x, result.fun
(array([0.96633867, 0.93363577]), 0.0011361355854792312)

Next find the minimum of the Ackley function (https://en.wikipedia.org/wiki/Test_functions_for_optimization).

>>> from scipy.optimize import differential_evolution
>>> import numpy as np
>>> def ackley(x):
...     arg1 = -0.2 * np.sqrt(0.5 * (x[0] ** 2 + x[1] ** 2))
...     arg2 = 0.5 * (np.cos(2. * np.pi * x[0]) + np.cos(2. * np.pi * x[1]))
...     return -20. * np.exp(arg1) - np.exp(arg2) + 20. + np.e
>>> bounds = [(-5, 5), (-5, 5)]
>>> result = differential_evolution(ackley, bounds)
>>> result.x, result.fun
(array([ 0.,  0.]), 4.4408920985006262e-16)

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.

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.

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

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.

least_squares

dipy.reconst.ivim.least_squares(fun, x0, jac='2-point', bounds=(- inf, inf), method='trf', ftol=1e-08, xtol=1e-08, gtol=1e-08, x_scale=1.0, loss='linear', f_scale=1.0, diff_step=None, tr_solver=None, tr_options={}, jac_sparsity=None, max_nfev=None, verbose=0, args=(), kwargs={})

Solve a nonlinear least-squares problem with bounds on the variables.

Given the residuals f(x) (an m-D real function of n real variables) and the loss function rho(s) (a scalar function), least_squares finds a local minimum of the cost function F(x):

minimize F(x) = 0.5 * sum(rho(f_i(x)**2), i = 0, ..., m - 1)
subject to lb <= x <= ub

The purpose of the loss function rho(s) is to reduce the influence of outliers on the solution.

Parameters
funcallable

Function which computes the vector of residuals, with the signature fun(x, *args, **kwargs), i.e., the minimization proceeds with respect to its first argument. The argument x passed to this function is an ndarray of shape (n,) (never a scalar, even for n=1). It must allocate and return a 1-D array_like of shape (m,) or a scalar. If the argument x is complex or the function fun returns complex residuals, it must be wrapped in a real function of real arguments, as shown at the end of the Examples section.

x0array_like with shape (n,) or float

Initial guess on independent variables. If float, it will be treated as a 1-D array with one element.

jac{‘2-point’, ‘3-point’, ‘cs’, callable}, optional

Method of computing the Jacobian matrix (an m-by-n matrix, where element (i, j) is the partial derivative of f[i] with respect to x[j]). The keywords select a finite difference scheme for numerical estimation. The scheme ‘3-point’ is more accurate, but requires twice as many operations as ‘2-point’ (default). The scheme ‘cs’ uses complex steps, and while potentially the most accurate, it is applicable only when fun correctly handles complex inputs and can be analytically continued to the complex plane. Method ‘lm’ always uses the ‘2-point’ scheme. If callable, it is used as jac(x, *args, **kwargs) and should return a good approximation (or the exact value) for the Jacobian as an array_like (np.atleast_2d is applied), a sparse matrix (csr_matrix preferred for performance) or a scipy.sparse.linalg.LinearOperator.

bounds2-tuple of array_like, optional

Lower and upper bounds on independent variables. Defaults to no bounds. Each array must match the size of x0 or be a scalar, in the latter case a bound will be the same for all variables. Use np.inf with an appropriate sign to disable bounds on all or some variables.

method{‘trf’, ‘dogbox’, ‘lm’}, optional

Algorithm to perform minimization.

  • ‘trf’ : Trust Region Reflective algorithm, particularly suitable for large sparse problems with bounds. Generally robust method.

  • ‘dogbox’ : dogleg algorithm with rectangular trust regions, typical use case is small problems with bounds. Not recommended for problems with rank-deficient Jacobian.

  • ‘lm’ : Levenberg-Marquardt algorithm as implemented in MINPACK. Doesn’t handle bounds and sparse Jacobians. Usually the most efficient method for small unconstrained problems.

Default is ‘trf’. See Notes for more information.

ftolfloat or None, optional

Tolerance for termination by the change of the cost function. Default is 1e-8. The optimization process is stopped when dF < ftol * F, and there was an adequate agreement between a local quadratic model and the true model in the last step.

If None and ‘method’ is not ‘lm’, the termination by this condition is disabled. If ‘method’ is ‘lm’, this tolerance must be higher than machine epsilon.

xtolfloat or None, optional

Tolerance for termination by the change of the independent variables. Default is 1e-8. The exact condition depends on the method used:

  • For ‘trf’ and ‘dogbox’ : norm(dx) < xtol * (xtol + norm(x)).

  • For ‘lm’ : Delta < xtol * norm(xs), where Delta is a trust-region radius and xs is the value of x scaled according to x_scale parameter (see below).

If None and ‘method’ is not ‘lm’, the termination by this condition is disabled. If ‘method’ is ‘lm’, this tolerance must be higher than machine epsilon.

gtolfloat or None, optional

Tolerance for termination by the norm of the gradient. Default is 1e-8. The exact condition depends on a method used:

  • For ‘trf’ : norm(g_scaled, ord=np.inf) < gtol, where g_scaled is the value of the gradient scaled to account for the presence of the bounds [STIR].

  • For ‘dogbox’ : norm(g_free, ord=np.inf) < gtol, where g_free is the gradient with respect to the variables which are not in the optimal state on the boundary.

  • For ‘lm’ : the maximum absolute value of the cosine of angles between columns of the Jacobian and the residual vector is less than gtol, or the residual vector is zero.

If None and ‘method’ is not ‘lm’, the termination by this condition is disabled. If ‘method’ is ‘lm’, this tolerance must be higher than machine epsilon.

x_scalearray_like or ‘jac’, optional

Characteristic scale of each variable. Setting x_scale is equivalent to reformulating the problem in scaled variables xs = x / x_scale. An alternative view is that the size of a trust region along jth dimension is proportional to x_scale[j]. Improved convergence may be achieved by setting x_scale such that a step of a given size along any of the scaled variables has a similar effect on the cost function. If set to ‘jac’, the scale is iteratively updated using the inverse norms of the columns of the Jacobian matrix (as described in [JJMore]).

lossstr or callable, optional

Determines the loss function. The following keyword values are allowed:

  • ‘linear’ (default) : rho(z) = z. Gives a standard least-squares problem.

  • ‘soft_l1’ : rho(z) = 2 * ((1 + z)**0.5 - 1). The smooth approximation of l1 (absolute value) loss. Usually a good choice for robust least squares.

  • ‘huber’ : rho(z) = z if z <= 1 else 2*z**0.5 - 1. Works similarly to ‘soft_l1’.

  • ‘cauchy’ : rho(z) = ln(1 + z). Severely weakens outliers influence, but may cause difficulties in optimization process.

  • ‘arctan’ : rho(z) = arctan(z). Limits a maximum loss on a single residual, has properties similar to ‘cauchy’.

If callable, it must take a 1-D ndarray z=f**2 and return an array_like with shape (3, m) where row 0 contains function values, row 1 contains first derivatives and row 2 contains second derivatives. Method ‘lm’ supports only ‘linear’ loss.

f_scalefloat, optional

Value of soft margin between inlier and outlier residuals, default is 1.0. The loss function is evaluated as follows rho_(f**2) = C**2 * rho(f**2 / C**2), where C is f_scale, and rho is determined by loss parameter. This parameter has no effect with loss='linear', but for other loss values it is of crucial importance.

max_nfevNone or int, optional

Maximum number of function evaluations before the termination. If None (default), the value is chosen automatically:

  • For ‘trf’ and ‘dogbox’ : 100 * n.

  • For ‘lm’ : 100 * n if jac is callable and 100 * n * (n + 1) otherwise (because ‘lm’ counts function calls in Jacobian estimation).

diff_stepNone or array_like, optional

Determines the relative step size for the finite difference approximation of the Jacobian. The actual step is computed as x * diff_step. If None (default), then diff_step is taken to be a conventional “optimal” power of machine epsilon for the finite difference scheme used [NR].

tr_solver{None, ‘exact’, ‘lsmr’}, optional

Method for solving trust-region subproblems, relevant only for ‘trf’ and ‘dogbox’ methods.

  • ‘exact’ is suitable for not very large problems with dense Jacobian matrices. The computational complexity per iteration is comparable to a singular value decomposition of the Jacobian matrix.

  • ‘lsmr’ is suitable for problems with sparse and large Jacobian matrices. It uses the iterative procedure scipy.sparse.linalg.lsmr for finding a solution of a linear least-squares problem and only requires matrix-vector product evaluations.

If None (default), the solver is chosen based on the type of Jacobian returned on the first iteration.

tr_optionsdict, optional

Keyword options passed to trust-region solver.

  • tr_solver='exact': tr_options are ignored.

  • tr_solver='lsmr': options for scipy.sparse.linalg.lsmr. Additionally, method='trf' supports ‘regularize’ option (bool, default is True), which adds a regularization term to the normal equation, which improves convergence if the Jacobian is rank-deficient [Byrd] (eq. 3.4).

jac_sparsity{None, array_like, sparse matrix}, optional

Defines the sparsity structure of the Jacobian matrix for finite difference estimation, its shape must be (m, n). If the Jacobian has only few non-zero elements in each row, providing the sparsity structure will greatly speed up the computations [Curtis]. A zero entry means that a corresponding element in the Jacobian is identically zero. If provided, forces the use of ‘lsmr’ trust-region solver. If None (default), then dense differencing will be used. Has no effect for ‘lm’ method.

verbose{0, 1, 2}, optional

Level of algorithm’s verbosity:

  • 0 (default) : work silently.

  • 1 : display a termination report.

  • 2 : display progress during iterations (not supported by ‘lm’ method).

args, kwargstuple and dict, optional

Additional arguments passed to fun and jac. Both empty by default. The calling signature is fun(x, *args, **kwargs) and the same for jac.

Returns
resultOptimizeResult

OptimizeResult with the following fields defined:

xndarray, shape (n,)

Solution found.

costfloat

Value of the cost function at the solution.

funndarray, shape (m,)

Vector of residuals at the solution.

jacndarray, sparse matrix or LinearOperator, shape (m, n)

Modified Jacobian matrix at the solution, in the sense that J^T J is a Gauss-Newton approximation of the Hessian of the cost function. The type is the same as the one used by the algorithm.

gradndarray, shape (m,)

Gradient of the cost function at the solution.

optimalityfloat

First-order optimality measure. In unconstrained problems, it is always the uniform norm of the gradient. In constrained problems, it is the quantity which was compared with gtol during iterations.

active_maskndarray of int, shape (n,)

Each component shows whether a corresponding constraint is active (that is, whether a variable is at the bound):

  • 0 : a constraint is not active.

  • -1 : a lower bound is active.

  • 1 : an upper bound is active.

Might be somewhat arbitrary for ‘trf’ method as it generates a sequence of strictly feasible iterates and active_mask is determined within a tolerance threshold.

nfevint

Number of function evaluations done. Methods ‘trf’ and ‘dogbox’ do not count function calls for numerical Jacobian approximation, as opposed to ‘lm’ method.

njevint or None

Number of Jacobian evaluations done. If numerical Jacobian approximation is used in ‘lm’ method, it is set to None.

statusint

The reason for algorithm termination:

  • -1 : improper input parameters status returned from MINPACK.

  • 0 : the maximum number of function evaluations is exceeded.

  • 1 : gtol termination condition is satisfied.

  • 2 : ftol termination condition is satisfied.

  • 3 : xtol termination condition is satisfied.

  • 4 : Both ftol and xtol termination conditions are satisfied.

messagestr

Verbal description of the termination reason.

successbool

True if one of the convergence criteria is satisfied (status > 0).

See also

leastsq

A legacy wrapper for the MINPACK implementation of the Levenberg-Marquadt algorithm.

curve_fit

Least-squares minimization applied to a curve-fitting problem.

Notes

Method ‘lm’ (Levenberg-Marquardt) calls a wrapper over least-squares algorithms implemented in MINPACK (lmder, lmdif). It runs the Levenberg-Marquardt algorithm formulated as a trust-region type algorithm. The implementation is based on paper [JJMore], it is very robust and efficient with a lot of smart tricks. It should be your first choice for unconstrained problems. Note that it doesn’t support bounds. Also, it doesn’t work when m < n.

Method ‘trf’ (Trust Region Reflective) is motivated by the process of solving a system of equations, which constitute the first-order optimality condition for a bound-constrained minimization problem as formulated in [STIR]. The algorithm iteratively solves trust-region subproblems augmented by a special diagonal quadratic term and with trust-region shape determined by the distance from the bounds and the direction of the gradient. This enhancements help to avoid making steps directly into bounds and efficiently explore the whole space of variables. To further improve convergence, the algorithm considers search directions reflected from the bounds. To obey theoretical requirements, the algorithm keeps iterates strictly feasible. With dense Jacobians trust-region subproblems are solved by an exact method very similar to the one described in [JJMore] (and implemented in MINPACK). The difference from the MINPACK implementation is that a singular value decomposition of a Jacobian matrix is done once per iteration, instead of a QR decomposition and series of Givens rotation eliminations. For large sparse Jacobians a 2-D subspace approach of solving trust-region subproblems is used [STIR], [Byrd]. The subspace is spanned by a scaled gradient and an approximate Gauss-Newton solution delivered by scipy.sparse.linalg.lsmr. When no constraints are imposed the algorithm is very similar to MINPACK and has generally comparable performance. The algorithm works quite robust in unbounded and bounded problems, thus it is chosen as a default algorithm.

Method ‘dogbox’ operates in a trust-region framework, but considers rectangular trust regions as opposed to conventional ellipsoids [Voglis]. The intersection of a current trust region and initial bounds is again rectangular, so on each iteration a quadratic minimization problem subject to bound constraints is solved approximately by Powell’s dogleg method [NumOpt]. The required Gauss-Newton step can be computed exactly for dense Jacobians or approximately by scipy.sparse.linalg.lsmr for large sparse Jacobians. The algorithm is likely to exhibit slow convergence when the rank of Jacobian is less than the number of variables. The algorithm often outperforms ‘trf’ in bounded problems with a small number of variables.

Robust loss functions are implemented as described in [BA]. The idea is to modify a residual vector and a Jacobian matrix on each iteration such that computed gradient and Gauss-Newton Hessian approximation match the true gradient and Hessian approximation of the cost function. Then the algorithm proceeds in a normal way, i.e., robust loss functions are implemented as a simple wrapper over standard least-squares algorithms.

New in version 0.17.0.

References

STIR(1,2,3)

M. A. Branch, T. F. Coleman, and Y. Li, “A Subspace, Interior, and Conjugate Gradient Method for Large-Scale Bound-Constrained Minimization Problems,” SIAM Journal on Scientific Computing, Vol. 21, Number 1, pp 1-23, 1999.

NR

William H. Press et. al., “Numerical Recipes. The Art of Scientific Computing. 3rd edition”, Sec. 5.7.

Byrd(1,2)

R. H. Byrd, R. B. Schnabel and G. A. Shultz, “Approximate solution of the trust region problem by minimization over two-dimensional subspaces”, Math. Programming, 40, pp. 247-263, 1988.

Curtis

A. Curtis, M. J. D. Powell, and J. Reid, “On the estimation of sparse Jacobian matrices”, Journal of the Institute of Mathematics and its Applications, 13, pp. 117-120, 1974.

JJMore(1,2,3)

J. J. More, “The Levenberg-Marquardt Algorithm: Implementation and Theory,” Numerical Analysis, ed. G. A. Watson, Lecture Notes in Mathematics 630, Springer Verlag, pp. 105-116, 1977.

Voglis

C. Voglis and I. E. Lagaris, “A Rectangular Trust Region Dogleg Approach for Unconstrained and Bound Constrained Nonlinear Optimization”, WSEAS International Conference on Applied Mathematics, Corfu, Greece, 2004.

NumOpt

J. Nocedal and S. J. Wright, “Numerical optimization, 2nd edition”, Chapter 4.

BA

B. Triggs et. al., “Bundle Adjustment - A Modern Synthesis”, Proceedings of the International Workshop on Vision Algorithms: Theory and Practice, pp. 298-372, 1999.

Examples

In this example we find a minimum of the Rosenbrock function without bounds on independent variables.

>>> def fun_rosenbrock(x):
...     return np.array([10 * (x[1] - x[0]**2), (1 - x[0])])

Notice that we only provide the vector of the residuals. The algorithm constructs the cost function as a sum of squares of the residuals, which gives the Rosenbrock function. The exact minimum is at x = [1.0, 1.0].

>>> from scipy.optimize import least_squares
>>> x0_rosenbrock = np.array([2, 2])
>>> res_1 = least_squares(fun_rosenbrock, x0_rosenbrock)
>>> res_1.x
array([ 1.,  1.])
>>> res_1.cost
9.8669242910846867e-30
>>> res_1.optimality
8.8928864934219529e-14

We now constrain the variables, in such a way that the previous solution becomes infeasible. Specifically, we require that x[1] >= 1.5, and x[0] left unconstrained. To this end, we specify the bounds parameter to least_squares in the form bounds=([-np.inf, 1.5], np.inf).

We also provide the analytic Jacobian:

>>> def jac_rosenbrock(x):
...     return np.array([
...         [-20 * x[0], 10],
...         [-1, 0]])

Putting this all together, we see that the new solution lies on the bound:

>>> res_2 = least_squares(fun_rosenbrock, x0_rosenbrock, jac_rosenbrock,
...                       bounds=([-np.inf, 1.5], np.inf))
>>> res_2.x
array([ 1.22437075,  1.5       ])
>>> res_2.cost
0.025213093946805685
>>> res_2.optimality
1.5885401433157753e-07

Now we solve a system of equations (i.e., the cost function should be zero at a minimum) for a Broyden tridiagonal vector-valued function of 100000 variables:

>>> def fun_broyden(x):
...     f = (3 - x) * x + 1
...     f[1:] -= x[:-1]
...     f[:-1] -= 2 * x[1:]
...     return f

The corresponding Jacobian matrix is sparse. We tell the algorithm to estimate it by finite differences and provide the sparsity structure of Jacobian to significantly speed up this process.

>>> from scipy.sparse import lil_matrix
>>> def sparsity_broyden(n):
...     sparsity = lil_matrix((n, n), dtype=int)
...     i = np.arange(n)
...     sparsity[i, i] = 1
...     i = np.arange(1, n)
...     sparsity[i, i - 1] = 1
...     i = np.arange(n - 1)
...     sparsity[i, i + 1] = 1
...     return sparsity
...
>>> n = 100000
>>> x0_broyden = -np.ones(n)
...
>>> res_3 = least_squares(fun_broyden, x0_broyden,
...                       jac_sparsity=sparsity_broyden(n))
>>> res_3.cost
4.5687069299604613e-23
>>> res_3.optimality
1.1650454296851518e-11

Let’s also solve a curve fitting problem using robust loss function to take care of outliers in the data. Define the model function as y = a + b * exp(c * t), where t is a predictor variable, y is an observation and a, b, c are parameters to estimate.

First, define the function which generates the data with noise and outliers, define the model parameters, and generate data:

>>> from numpy.random import default_rng
>>> rng = default_rng()
>>> def gen_data(t, a, b, c, noise=0., n_outliers=0, seed=None):
...     rng = default_rng(seed)
...
...     y = a + b * np.exp(t * c)
...
...     error = noise * rng.standard_normal(t.size)
...     outliers = rng.integers(0, t.size, n_outliers)
...     error[outliers] *= 10
...
...     return y + error
...
>>> a = 0.5
>>> b = 2.0
>>> c = -1
>>> t_min = 0
>>> t_max = 10
>>> n_points = 15
...
>>> t_train = np.linspace(t_min, t_max, n_points)
>>> y_train = gen_data(t_train, a, b, c, noise=0.1, n_outliers=3)

Define function for computing residuals and initial estimate of parameters.

>>> def fun(x, t, y):
...     return x[0] + x[1] * np.exp(x[2] * t) - y
...
>>> x0 = np.array([1.0, 1.0, 0.0])

Compute a standard least-squares solution:

>>> res_lsq = least_squares(fun, x0, args=(t_train, y_train))

Now compute two solutions with two different robust loss functions. The parameter f_scale is set to 0.1, meaning that inlier residuals should not significantly exceed 0.1 (the noise level used).

>>> res_soft_l1 = least_squares(fun, x0, loss='soft_l1', f_scale=0.1,
...                             args=(t_train, y_train))
>>> res_log = least_squares(fun, x0, loss='cauchy', f_scale=0.1,
...                         args=(t_train, y_train))

And, finally, plot all the curves. We see that by selecting an appropriate loss we can get estimates close to optimal even in the presence of strong outliers. But keep in mind that generally it is recommended to try ‘soft_l1’ or ‘huber’ losses first (if at all necessary) as the other two options may cause difficulties in optimization process.

>>> t_test = np.linspace(t_min, t_max, n_points * 10)
>>> y_true = gen_data(t_test, a, b, c)
>>> y_lsq = gen_data(t_test, *res_lsq.x)
>>> y_soft_l1 = gen_data(t_test, *res_soft_l1.x)
>>> y_log = gen_data(t_test, *res_log.x)
...
>>> import matplotlib.pyplot as plt
>>> plt.plot(t_train, y_train, 'o')
>>> plt.plot(t_test, y_true, 'k', linewidth=2, label='true')
>>> plt.plot(t_test, y_lsq, label='linear loss')
>>> plt.plot(t_test, y_soft_l1, label='soft_l1 loss')
>>> plt.plot(t_test, y_log, label='cauchy loss')
>>> plt.xlabel("t")
>>> plt.ylabel("y")
>>> plt.legend()
>>> plt.show()

In the next example, we show how complex-valued residual functions of complex variables can be optimized with least_squares(). Consider the following function:

>>> def f(z):
...     return z - (0.5 + 0.5j)

We wrap it into a function of real variables that returns real residuals by simply handling the real and imaginary parts as independent variables:

>>> def f_wrap(x):
...     fx = f(x[0] + 1j*x[1])
...     return np.array([fx.real, fx.imag])

Thus, instead of the original m-D complex function of n complex variables we optimize a 2m-D real function of 2n real variables:

>>> from scipy.optimize import least_squares
>>> res_wrapped = least_squares(f_wrap, (0.1, 0.1), bounds=([0, 0], [1, 1]))
>>> z = res_wrapped.x[0] + res_wrapped.x[1]*1j
>>> z
(0.49999999999925893+0.49999999999925893j)

multi_voxel_fit

dipy.reconst.ivim.multi_voxel_fit(single_voxel_fit)

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

optional_package

dipy.reconst.ivim.optional_package(name, trip_msg=None)

Return package-like thing and module setup for package name

Parameters
namestr

package name

trip_msgNone or str

message to give when someone tries to use the return package, but we could not import it, and have returned a TripWire object instead. Default message if None.

Returns
pkg_likemodule or TripWire instance

If we can import the package, return it. Otherwise return an object raising an error when accessed

have_pkgbool

True if import for package was successful, false otherwise

module_setupfunction

callable usually set as setup_module in calling namespace, to allow skipping tests.

Examples

Typical use would be something like this at the top of a module using an optional package:

>>> from dipy.utils.optpkg import optional_package
>>> pkg, have_pkg, setup_module = optional_package('not_a_package')

Of course in this case the package doesn’t exist, and so, in the module:

>>> have_pkg
False

and

>>> pkg.some_function() 
Traceback (most recent call last):
    ...
TripWireError: We need package not_a_package for these functions, but
``import not_a_package`` raised an ImportError

If the module does exist - we get the module

>>> pkg, _, _ = optional_package('os')
>>> hasattr(pkg, 'path')
True

Or a submodule if that’s what we asked for

>>> subpkg, _, _ = optional_package('os.path')
>>> hasattr(subpkg, 'dirname')
True

Cache

class dipy.reconst.mapmri.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)

Methods

cache_clear()

Clear the cache.

cache_get(tag, key[, default])

Retrieve a value from the cache.

cache_set(tag, key, value)

Store a value in the cache.

__init__(*args, **kwargs)
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

MapmriFit

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

Bases: dipy.reconst.base.ReconstFit

Attributes
mapmri_R

The MAPMRI rotation matrix

mapmri_coeff

The MAPMRI coefficients

mapmri_mu

The MAPMRI scale factors

Methods

fitted_signal([gtab])

Recovers the fitted signal for the given gradient table.

msd()

Calculates the analytical Mean Squared Displacement (MSD).

ng()

Calculates the analytical non-Gaussiannity (NG) [1].

ng_parallel()

Calculates the analytical parallel non-Gaussiannity (NG) [1].

ng_perpendicular()

Calculates the analytical perpendicular non-Gaussiannity (NG) [1].

norm_of_laplacian_signal()

Calculates the norm of the laplacian of the fitted signal [Rf7f23918a7e7-1].

odf(sphere[, s])

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

odf_sh([s])

Calculates the real analytical odf for a given discrete sphere.

pdf(r_points)

Diffusion propagator on a given set of real points.

predict(qvals_or_gtab[, S0])

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

qiv()

Calculates the analytical Q-space Inverse Variance (QIV).

rtap()

Calculates the analytical return to the axis probability (RTAP) [1] eq.

rtop()

Calculates the analytical return to the origin probability (RTOP) [1] eq.

rtpp()

Calculates the analytical return to the plane probability (RTPP) [1] eq.

__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 [R53ed4361a122-2] eq. (C13, D1).

References

1

Cheng, J., 2014. Estimation and Processing of Ensemble Average

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

1(1,2)

Ozarslan E. et al., “Mean apparent propagator (MAP) MRI: A novel

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

2

Avram et al. “Clinical feasibility of using mean apparent

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

1(1,2)

Ozarslan E. et al., “Mean apparent propagator (MAP) MRI: A novel

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

2

Avram et al. “Clinical feasibility of using mean apparent

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

1(1,2)

Ozarslan E. et al., “Mean apparent propagator (MAP) MRI: A novel

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

2

Avram et al. “Clinical feasibility of using mean apparent

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 [Rf7f23918a7e7-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

1(1,2)

Ozarslan E. et al., “Mean apparent propagator (MAP) MRI: A novel

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

1

Ozarslan E. et al., “Mean apparent propagator (MAP) MRI: A novel

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 [Rd3765a80e128-2] eq. (C14, D2).

References

1

Hosseinbor et al. “Bessel fourier orientation reconstruction

(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 [R6f4b363492da-2] eq. (C11).

References

1(1,2)

Ozarslan E. et al., “Mean apparent propagator (MAP) MRI: A novel

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 [Re6f1062fb760-2] eq. (C11).

References

1(1,2)

Ozarslan E. et al., “Mean apparent propagator (MAP) MRI: A novel

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 [Rf9cced748cc9-2] eq. (C11).

References

1(1,2)

Ozarslan E. et al., “Mean apparent propagator (MAP) MRI: A novel

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

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

MapmriModel

class dipy.reconst.mapmri.MapmriModel(gtab, radial_order=6, laplacian_regularization=True, laplacian_weighting=0.2, positivity_constraint=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: dipy.reconst.base.ReconstModel, dipy.reconst.cache.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

1(1,2)

Ozarslan E. et al., “Mean apparent propagator (MAP) MRI: A novel diffusion imaging method for mapping tissue microstructure”, NeuroImage, 2013.

2

Ozarslan E. et al., “Simple harmonic oscillator based reconstruction and estimation for one-dimensional q-space magnetic resonance 1D-SHORE)”, eapoc Intl Soc Mag Reson Med, vol. 16, p. 35., 2008.

3(1,2)

Merlet S. et al., “Continuous diffusion signal, EAP and ODF estimation via Compressive Sensing in diffusion MRI”, Medical Image Analysis, 2013.

4

Fick, Rutger HJ, et al. “MAPL: Tissue microstructure estimation using Laplacian-regularized MAP-MRI and its application to HCP data.” NeuroImage (2016).

5

Cheng, J., 2014. Estimation and Processing of Ensemble Average Propagator and Its Features in Diffusion MRI. Ph.D. Thesis.

6

Hosseinbor et al. “Bessel fourier orientation reconstruction (bfor): An analytical diffusion propagator reconstruction for hybrid diffusion imaging and computation of q-space indices”. NeuroImage 64, 2013, 650-670.

7

Craven et al. “Smoothing Noisy Data with Spline Functions.” NUMER MATH 31.4 (1978): 377-403.

8

Avram et al. “Clinical feasibility of using mean apparent propagator (MAP) MRI to characterize brain tissue microstructure”. NeuroImage 2015, in press.

Methods

cache_clear()

Clear the cache.

cache_get(tag, key[, default])

Retrieve a value from the cache.

cache_set(tag, key, value)

Store a value in the cache.

fit(data[, mask])

Fit method for every voxel in data

__init__(gtab, radial_order=6, laplacian_regularization=True, laplacian_weighting=0.2, positivity_constraint=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] and/or the laplacian regularization proposed in [4].

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

pos_gridinteger,

The number of points in the grid that is used in the positivity constraint.

pos_radiusfloat or string,

If set to a float, the maximum distance the the 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

1(1,2)

Ozarslan E. et al., “Mean apparent propagator (MAP) MRI: A novel diffusion imaging method for mapping tissue microstructure”, NeuroImage, 2013.

2

Ozarslan E. et al., “Simple harmonic oscillator based reconstruction and estimation for one-dimensional q-space magnetic resonance 1D-SHORE)”, Proc Intl Soc Mag Reson Med, vol. 16, p. 35., 2008.

3(1,2,3)

Ozarslan E. et al., “Simple harmonic oscillator based reconstruction and estimation for three-dimensional q-space mri”, ISMRM 2009.

4(1,2)

Fick, Rutger HJ, et al. “MAPL: Tissue microstructure estimation using Laplacian-regularized MAP-MRI and its application to HCP data.” NeuroImage (2016).

5

Merlet S. et al., “Continuous diffusion signal, EAP and ODF estimation via Compressive Sensing in diffusion MRI”, Medical Image Analysis, 2013.

Examples

In this example, where the data, gradient table and sphere tessellation used for reconstruction are provided, we model the diffusion signal with respect to the SHORE basis and compute the real and analytical ODF.

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

Optimizer

class dipy.reconst.mapmri.Optimizer(fun, x0, args=(), method='L-BFGS-B', jac=None, hess=None, hessp=None, bounds=None, constraints=(), tol=None, callback=None, options=None, evolution=False)

Bases: object

Attributes
evolution
fopt
message
nfev
nit
xopt

Methods

print_summary

__init__(fun, x0, args=(), method='L-BFGS-B', jac=None, hess=None, hessp=None, bounds=None, constraints=(), tol=None, callback=None, options=None, evolution=False)

A class for handling minimization of scalar function of one or more variables.

Parameters
funcallable

Objective function.

x0ndarray

Initial guess.

argstuple, optional

Extra arguments passed to the objective function and its derivatives (Jacobian, Hessian).

methodstr, optional

Type of solver. Should be one of

  • ‘Nelder-Mead’

  • ‘Powell’

  • ‘CG’

  • ‘BFGS’

  • ‘Newton-CG’

  • ‘Anneal’

  • ‘L-BFGS-B’

  • ‘TNC’

  • ‘COBYLA’

  • ‘SLSQP’

  • ‘dogleg’

  • ‘trust-ncg’

jacbool or callable, optional

Jacobian of objective function. Only for CG, BFGS, Newton-CG, dogleg, trust-ncg. If jac is a Boolean and is True, fun is assumed to return the value of Jacobian along with the objective function. If False, the Jacobian will be estimated numerically. jac can also be a callable returning the Jacobian of the objective. In this case, it must accept the same arguments as fun.

hess, hesspcallable, optional

Hessian of objective function or Hessian of objective function times an arbitrary vector p. Only for Newton-CG, dogleg, trust-ncg. Only one of hessp or hess needs to be given. If hess is provided, then hessp will be ignored. If neither hess nor hessp is provided, then the hessian product will be approximated using finite differences on jac. hessp must compute the Hessian times an arbitrary vector.

boundssequence, optional

Bounds for variables (only for L-BFGS-B, TNC and SLSQP). (min, max) pairs for each element in x, defining the bounds on that parameter. Use None for one of min or max when there is no bound in that direction.

constraintsdict or sequence of dict, optional

Constraints definition (only for COBYLA and SLSQP). Each constraint is defined in a dictionary with fields:

typestr

Constraint type: ‘eq’ for equality, ‘ineq’ for inequality.

funcallable

The function defining the constraint.

jaccallable, optional

The Jacobian of fun (only for SLSQP).

argssequence, optional

Extra arguments to be passed to the function and Jacobian.

Equality constraint means that the constraint function result is to be zero whereas inequality means that it is to be non-negative. Note that COBYLA only supports inequality constraints.

tolfloat, optional

Tolerance for termination. For detailed control, use solver-specific options.

callbackcallable, optional

Called after each iteration, as callback(xk), where xk is the current parameter vector. Only available using Scipy >= 0.12.

optionsdict, optional

A dictionary of solver options. All methods accept the following generic options:

maxiterint

Maximum number of iterations to perform.

dispbool

Set to True to print convergence messages.

For method-specific options, see show_options(‘minimize’, method).

evolutionbool, optional

save history of x for each iteration. Only available using Scipy >= 0.12.

See also

scipy.optimize.minimize
property evolution
property fopt
property message
property nfev
property nit
print_summary()
property xopt

ReconstFit

class dipy.reconst.mapmri.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)

ReconstModel

class dipy.reconst.mapmri.ReconstModel(gtab)

Bases: object

Abstract class for signal reconstruction models

Methods

fit

__init__(gtab)

Initialization of the abstract class for signal reconstruction models

Parameters
gtabGradientTable class instance
fit(data, mask=None, **kwargs)

Version

class dipy.reconst.mapmri.Version(version: str)

Bases: packaging.version._BaseVersion

Attributes
base_version
dev
epoch
is_devrelease
is_postrelease
is_prerelease
local
major
micro
minor
post
pre
public
release
__init__(version: str) None
property base_version: str
property dev: Optional[int]
property epoch: int
property is_devrelease: bool
property is_postrelease: bool
property is_prerelease: bool
property local: Optional[str]
property major: int
property micro: int
property minor: int
property post: Optional[int]
property pre: Optional[Tuple[str, int]]
property public: str
property release: Tuple[int, ...]

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

1(1,2)

Ozarslan E. et al., “Mean apparent propagator (MAP) MRI: A novel

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

1(1,2)

Ozarslan E. et al., “Mean apparent propagator (MAP) MRI: A novel

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

binomialfloat

dipy.reconst.mapmri.binomialfloat(n, k)

Custom Binomial function

cart2sphere

dipy.reconst.mapmri.cart2sphere(x, y, z)

Return angles for Cartesian 3D coordinates x, y, and z

See doc for sphere2cart for angle conventions and derivation of the formulae.

\(0\le\theta\mathrm{(theta)}\le\pi\) and \(-\pi\le\phi\mathrm{(phi)}\le\pi\)

Parameters
xarray_like

x coordinate in Cartesian space

yarray_like

y coordinate in Cartesian space

zarray_like

z coordinate

Returns
rarray

radius

thetaarray

inclination (polar) angle

phiarray

azimuth angle

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)

factorial2

dipy.reconst.mapmri.factorial2(n, exact=False)

Double factorial.

This is the factorial with every second value skipped. E.g., 7!! = 7 * 5 * 3 * 1. It can be approximated numerically as:

n!! = special.gamma(n/2+1)*2**((m+1)/2)/sqrt(pi)  n odd
    = 2**(n/2) * (n/2)!                           n even
Parameters
nint or array_like

Calculate n!!. Arrays are only supported with exact set to False. If n < 0, the return value is 0.

exactbool, optional

The result can be approximated rapidly using the gamma-formula above (default). If exact is set to True, calculate the answer exactly using integer arithmetic.

Returns
nfffloat or int

Double factorial of n, as an int or a float depending on exact.

Examples

>>> from scipy.special import factorial2
>>> factorial2(7, exact=False)
array(105.00000000000001)
>>> factorial2(7, exact=True)
105

gcv_cost_function

dipy.reconst.mapmri.gcv_cost_function(weight, args)

The GCV cost function that is iterated [4].

generalized_crossvalidation

dipy.reconst.mapmri.generalized_crossvalidation(data, M, LR, gcv_startpoint=0.05)

Generalized Cross Validation Function [Rb690cd738504-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

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

genlaguerre

dipy.reconst.mapmri.genlaguerre(n, alpha, monic=False)

Generalized (associated) Laguerre polynomial.

Defined to be the solution of

\[x\frac{d^2}{dx^2}L_n^{(\alpha)} + (\alpha + 1 - x)\frac{d}{dx}L_n^{(\alpha)} + nL_n^{(\alpha)} = 0,\]

where \(\alpha > -1\); \(L_n^{(\alpha)}\) is a polynomial of degree \(n\).

Parameters
nint

Degree of the polynomial.

alphafloat

Parameter, must be greater than -1.

monicbool, optional

If True, scale the leading coefficient to be 1. Default is False.

Returns
Lorthopoly1d

Generalized Laguerre polynomial.

See also

laguerre

Laguerre polynomial.

Notes

For fixed \(\alpha\), the polynomials \(L_n^{(\alpha)}\) are orthogonal over \([0, \infty)\) with weight function \(e^{-x}x^\alpha\).

The Laguerre polynomials are the special case where \(\alpha = 0\).

gradient_table

dipy.reconst.mapmri.gradient_table(bvals, bvecs=None, big_delta=None, small_delta=None, b0_threshold=50, atol=0.01, btens=None)

A general function for creating diffusion MR gradients.

It reads, loads and prepares scanner parameters like the b-values and b-vectors so that they can be useful during the reconstruction process.

Parameters
bvalscan be any of the four options
  1. an array of shape (N,) or (1, N) or (N, 1) with the b-values.

  2. a path for the file which contains an array like the above (1).

  3. an array of shape (N, 4) or (4, N). Then this parameter is considered to be a b-table which contains both bvals and bvecs. In this case the next parameter is skipped.

  4. a path for the file which contains an array like the one at (3).

bvecscan be any of two options
  1. an array of shape (N, 3) or (3, N) with the b-vectors.

  2. a path for the file which contains an array like the previous.

big_deltafloat

acquisition pulse separation time in seconds (default None)

small_deltafloat

acquisition pulse duration time in seconds (default None)

b0_thresholdfloat

All b-values with values less than or equal to bo_threshold are considered as b0s i.e. without diffusion weighting.

atolfloat

All b-vectors need to be unit vectors up to a tolerance.

btenscan be any of three options
  1. a string specifying the shape of the encoding tensor for all volumes in data. Options: ‘LTE’, ‘PTE’, ‘STE’, ‘CTE’ corresponding to linear, planar, spherical, and “cigar-shaped” tensor encoding. Tensors are rotated so that linear and cigar tensors are aligned with the corresponding gradient direction and the planar tensor’s normal is aligned with the corresponding gradient direction. Magnitude is scaled to match the b-value.

  2. an array of strings of shape (N,), (N, 1), or (1, N) specifying encoding tensor shape for each volume separately. N corresponds to the number volumes in data. Options for elements in array: ‘LTE’, ‘PTE’, ‘STE’, ‘CTE’ corresponding to linear, planar, spherical, and “cigar-shaped” tensor encoding. Tensors are rotated so that linear and cigar tensors are aligned with the corresponding gradient direction and the planar tensor’s normal is aligned with the corresponding gradient direction. Magnitude is scaled to match the b-value.

  3. an array of shape (N,3,3) specifying the b-tensor of each volume exactly. N corresponds to the number volumes in data. No rotation or scaling is performed.

Returns
gradientsGradientTable

A GradientTable with all the gradient information.

Notes

  1. Often b0s (b-values which correspond to images without diffusion weighting) have 0 values however in some cases the scanner cannot provide b0s of an exact 0 value and it gives a bit higher values e.g. 6 or 12. This is the purpose of the b0_threshold in the __init__.

  2. We assume that the minimum number of b-values is 7.

  3. B-vectors should be unit vectors.

Examples

>>> from dipy.core.gradients import gradient_table
>>> bvals = 1500 * np.ones(7)
>>> bvals[0] = 0
>>> sq2 = np.sqrt(2) / 2
>>> bvecs = np.array([[0, 0, 0],
...                   [1, 0, 0],
...                   [0, 1, 0],
...                   [0, 0, 1],
...                   [sq2, sq2, 0],
...                   [sq2, 0, sq2],
...                   [0, sq2, sq2]])
>>> gt = gradient_table(bvals, bvecs)
>>> gt.bvecs.shape == bvecs.shape
True
>>> gt = gradient_table(bvals, bvecs.T)
>>> gt.bvecs.shape == bvecs.T.shape
False

hermite

dipy.reconst.mapmri.hermite(n, monic=False)

Physicist’s Hermite polynomial.

Defined by

\[H_n(x) = (-1)^ne^{x^2}\frac{d^n}{dx^n}e^{-x^2};\]

\(H_n\) is a polynomial of degree \(n\).

Parameters
nint

Degree of the polynomial.

monicbool, optional

If True, scale the leading coefficient to be 1. Default is False.

Returns
Horthopoly1d

Hermite polynomial.

Notes

The polynomials \(H_n\) are orthogonal over \((-\infty, \infty)\) with weight function \(e^{-x^2}\).

Examples

>>> from scipy import special
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> p_monic = special.hermite(3, monic=True)
>>> p_monic
poly1d([ 1. ,  0. , -1.5,  0. ])
>>> p_monic(1)
-0.49999999999999983
>>> x = np.linspace(-3, 3, 400)
>>> y = p_monic(x)
>>> plt.plot(x, y)
>>> plt.title("Monic Hermite polynomial of degree 3")
>>> plt.xlabel("x")
>>> plt.ylabel("H_3(x)")
>>> plt.show()

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

1

Ozarslan E. et al., “Mean apparent propagator (MAP) MRI: A novel

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

map_laplace_s

dipy.reconst.mapmri.map_laplace_s(n, m)

R(m,n) static matrix for Laplacian regularization [R932dd40ca52e-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).

map_laplace_t

dipy.reconst.mapmri.map_laplace_t(n, m)

L(m, n) static matrix for Laplacian regularization [Reb78d789d6c4-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_u

dipy.reconst.mapmri.map_laplace_u(n, m)

S(n, m) static matrix for Laplacian regularization [Rb93dd9dab8c9-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).

mapmri_STU_reg_matrices

dipy.reconst.mapmri.mapmri_STU_reg_matrices(radial_order)

Generate the static portions of the Laplacian regularization matrix according to [R1d585103467a-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_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

1(1,2)

Ozarslan E. et al., “Mean apparent propagator (MAP) MRI: A novel

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

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.

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

1(1,2)

Ozarslan E. et al., “Mean apparent propagator (MAP) MRI: A novel

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

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 [R156f27ca005f-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 [Rdcc29394f577-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_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 [Rf7e027186c88-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

1(1,2,3)

Ozarslan E. et al., “Mean apparent propagator (MAP) MRI: A novel

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 [R18e181ea8d0c-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

1(1,2,3)

Ozarslan E. et al., “Mean apparent propagator (MAP) MRI: A novel

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

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

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

1(1,2)

Ozarslan E. et al., “Mean apparent propagator (MAP) MRI: A novel

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

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

1(1,2)

Ozarslan E. et al., “Mean apparent propagator (MAP) MRI: A novel

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

1(1,2)

Ozarslan E. et al., “Mean apparent propagator (MAP) MRI: A novel

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

1(1,2)

Ozarslan E. et al., “Mean apparent propagator (MAP) MRI: A novel

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

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

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

1(1,2)

Ozarslan E. et al., “Mean apparent propagator (MAP) MRI: A novel

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

1(1,2)

Ozarslan E. et al., “Mean apparent propagator (MAP) MRI: A novel

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

1(1,2)

Ozarslan E. et al., “Mean apparent propagator (MAP) MRI: A novel

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

1(1,2)

Ozarslan E. et al., “Mean apparent propagator (MAP) MRI: A novel

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

1(1,2)

Ozarslan E. et al., “Mean apparent propagator (MAP) MRI: A novel

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

mfactorial

dipy.reconst.mapmri.mfactorial(x, /)

Find x!.

Raise a ValueError if x is negative or non-integral.

multi_voxel_fit

dipy.reconst.mapmri.multi_voxel_fit(single_voxel_fit)

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

optional_package

dipy.reconst.mapmri.optional_package(name, trip_msg=None)

Return package-like thing and module setup for package name

Parameters
namestr

package name

trip_msgNone or str

message to give when someone tries to use the return package, but we could not import it, and have returned a TripWire object instead. Default message if None.

Returns
pkg_likemodule or TripWire instance

If we can import the package, return it. Otherwise return an object raising an error when accessed

have_pkgbool

True if import for package was successful, false otherwise

module_setupfunction

callable usually set as setup_module in calling namespace, to allow skipping tests.

Examples

Typical use would be something like this at the top of a module using an optional package:

>>> from dipy.utils.optpkg import optional_package
>>> pkg, have_pkg, setup_module = optional_package('not_a_package')

Of course in this case the package doesn’t exist, and so, in the module:

>>> have_pkg
False

and

>>> pkg.some_function() 
Traceback (most recent call last):
    ...
TripWireError: We need package not_a_package for these functions, but
``import not_a_package`` raised an ImportError

If the module does exist - we get the module

>>> pkg, _, _ = optional_package('os')
>>> hasattr(pkg, 'path')
True

Or a submodule if that’s what we asked for

>>> subpkg, _, _ = optional_package('os.path')
>>> hasattr(subpkg, 'dirname')
True

real_sh_descoteaux_from_index

dipy.reconst.mapmri.real_sh_descoteaux_from_index(m, n, theta, phi, legacy=True)

Compute real spherical harmonics as in Descoteaux et al. 2007 [R85c991cbd5ae-1], where the real harmonic \(Y^m_n\) is defined to be:

Imag(\(Y^m_n\)) * sqrt(2) if m > 0 \(Y^0_n\) if m = 0 Real(\(Y^m_n\)) * sqrt(2) if m < 0

This may take scalar or array arguments. The inputs will be broadcasted against each other.

Parameters
mint |m| <= n

The degree of the harmonic.

nint >= 0

The order of the harmonic.

thetafloat [0, pi]

The polar (colatitudinal) coordinate.

phifloat [0, 2*pi]

The azimuthal (longitudinal) coordinate.

legacy: bool, optional

If true, uses DIPY’s legacy descoteaux07 implementation (where |m| is used for m < 0). Else, implements the basis as defined in Descoteaux et al. 2007 (without the absolute value).

Returns
real_shreal float

The real harmonic \(Y^m_n\) sampled at theta and phi.

sfactorial

dipy.reconst.mapmri.sfactorial(n, exact=False)

The factorial of a number or array of numbers.

The factorial of non-negative integer n is the product of all positive integers less than or equal to n:

n! = n * (n - 1) * (n - 2) * ... * 1
Parameters
nint or array_like of ints

Input values. If n < 0, the return value is 0.

exactbool, optional

If True, calculate the answer exactly using long integer arithmetic. If False, result is approximated in floating point rapidly using the gamma function. Default is False.

Returns
nffloat or int or ndarray

Factorial of n, as integer or float depending on exact.

Notes

For arrays with exact=True, the factorial is computed only once, for the largest input, with each other result computed in the process. The output dtype is increased to int64 or object if necessary.

With exact=False the factorial is approximated using the gamma function:

\[n! = \Gamma(n+1)\]

Examples

>>> from scipy.special import factorial
>>> arr = np.array([3, 4, 5])
>>> factorial(arr, exact=False)
array([   6.,   24.,  120.])
>>> factorial(arr, exact=True)
array([  6,  24, 120])
>>> factorial(5, exact=True)
120

sph_harm_ind_list

dipy.reconst.mapmri.sph_harm_ind_list(sh_order, full_basis=False)

Returns the degree (m) and order (n) of all the symmetric spherical harmonics of degree less then or equal to sh_order. The results, m_list and n_list are kx1 arrays, where k depends on sh_order. They can be passed to real_sh_descoteaux_from_index() and :func:real_sh_tournier_from_index.

Parameters
sh_orderint

even int > 0, max order to return

full_basis: bool, optional

True for SH basis with even and odd order terms

Returns
m_listarray

degrees of even spherical harmonics

n_listarray

orders of even spherical harmonics

See also

shm.real_sh_descoteaux_from_index, shm.real_sh_tournier_from_index

warn

dipy.reconst.mapmri.warn(/, message, category=None, stacklevel=1, source=None)

Issue a warning, or maybe ignore it or raise an exception.

GradientTable

class dipy.reconst.mcsd.GradientTable(gradients, big_delta=None, small_delta=None, b0_threshold=50, btens=None)

Bases: object

Diffusion gradient information

Parameters
gradientsarray_like (N, 3)

Diffusion gradients. The direction of each of these vectors corresponds to the b-vector, and the length corresponds to the b-value.

b0_thresholdfloat

Gradients with b-value less than or equal to b0_threshold are considered as b0s i.e. without diffusion weighting.

See also

gradient_table

Notes

The GradientTable object is immutable. Do NOT assign attributes. If you have your gradient table in a bval & bvec format, we recommend using the factory function gradient_table

Attributes
gradients(N,3) ndarray

diffusion gradients

bvals(N,) ndarray

The b-value, or magnitude, of each gradient direction.

qvals: (N,) ndarray

The q-value for each gradient direction. Needs big and small delta.

bvecs(N,3) ndarray

The direction, represented as a unit vector, of each gradient.

b0s_mask(N,) ndarray

Boolean array indicating which gradients have no diffusion weighting, ie b-value is close to 0.

b0_thresholdfloat

Gradients with b-value less than or equal to b0_threshold are considered to not have diffusion weighting.

btens(N,3,3) ndarray

The b-tensor of each gradient direction.

Methods

b0s_mask

bvals

bvecs

gradient_strength

qvals

tau

__init__(gradients, big_delta=None, small_delta=None, b0_threshold=50, btens=None)

Constructor for GradientTable class

b0s_mask()
bvals()
bvecs()
gradient_strength()
property info
qvals()
tau()

MSDeconvFit

class dipy.reconst.mcsd.MSDeconvFit(model, coeff, mask)

Bases: dipy.reconst.shm.SphHarmFit

Attributes
all_shm_coeff
shape
shm_coeff

The spherical harmonic coefficients of the odf

volume_fractions

Methods

odf(sphere)

Samples the odf function on the points of a sphere

predict([gtab, S0])

Predict the diffusion signal from the model coefficients.

gfa

__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 usecase for modifying the coefficients we can add a setter or expose the coefficients more directly

property volume_fractions

MultiShellDeconvModel

class dipy.reconst.mcsd.MultiShellDeconvModel(gtab, response, reg_sphere=<dipy.core.sphere.HemiSphere object>, sh_order=8, iso=2)

Bases: dipy.reconst.shm.SphHarmModel

Methods

cache_clear()

Clear the cache.

cache_get(tag, key[, default])

Retrieve a value from the cache.

cache_set(tag, key, value)

Store a value in the cache.

fit(data[, mask])

Fit method for every voxel in data

predict(params[, gtab, S0])

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

sampling_matrix(sphere)

The matrix needed to sample ODFs from coefficients of the model.

__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
gtabGradientTable
responsendarray 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

1

Jeurissen, B., et al. NeuroImage 2014. Multi-tissue constrained spherical deconvolution for improved analysis of multi-shell diffusion MRI data

2(1,2,3)

Tournier, J.D., et al. NeuroImage 2007. Robust determination of the fibre orientation distribution in diffusion MRI: Non-negativity constrained super-resolved spherical deconvolution

3

Tournier, J.D, et al. Imaging Systems and Technology 2012. MRtrix: Diffusion Tractography in Crossing Fiber Regions

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.

MultiShellResponse

class dipy.reconst.mcsd.MultiShellResponse(response, sh_order, shells, S0=None)

Bases: object

Attributes
iso
__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 refered 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

QpFitter

class dipy.reconst.mcsd.QpFitter(X, reg)

Bases: object

Methods

__call__(signal)

Call self as a function.

__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

TensorModel

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

Bases: dipy.reconst.base.ReconstModel

Diffusion Tensor

Methods

fit(data[, mask])

Fit method of the DTI model class

predict(dti_params[, S0])

Predict a signal for this TensorModel class instance given parameters.

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

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

Parameters
gtabGradientTable 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

1

Basser, P.J., Mattiello, J., LeBihan, D., 1994. Estimation of the effective self-diffusion tensor from the NMR spin echo. J Magn Reson B 103, 247-254.

2

Basser, P., Pierpaoli, C., 1996. Microstructural and physiological features of tissues elucidated by quantitative diffusion-tensor MRI. Journal of Magnetic Resonance 111, 209-219.

3

Lin-Ching C., Jones D.K., Pierpaoli, C. 2005. RESTORE: Robust estimation of tensors by outlier rejection. MRM 53: 1088-1095

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

Version

class dipy.reconst.mcsd.Version(version: str)

Bases: packaging.version._BaseVersion

Attributes
base_version
dev
epoch
is_devrelease
is_postrelease
is_prerelease
local
major
micro
minor
post
pre
public
release
__init__(version: str) None
property base_version: str
property dev: Optional[int]
property epoch: int
property is_devrelease: bool
property is_postrelease: bool
property is_prerelease: bool
property local: Optional[str]
property major: int
property micro: int
property minor: int
property post: Optional[int]
property pre: Optional[Tuple[str, int]]
property public: str
property release: Tuple[int, ...]

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
gtabGradientTable
datandarray

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

fractional_anisotropy

dipy.reconst.mcsd.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}}\]

get_bval_indices

dipy.reconst.mcsd.get_bval_indices(bvals, bval, tol=20)

Get indices where the b-value is bval

Parameters
bvals: ndarray

Array containing the b-values

bval: float or int

b-value to extract indices

tol: int

The tolerated gap between the b-values to extract and the actual b-values.

Returns
Array of indices where the b-value is bval

gradient_table

dipy.reconst.mcsd.gradient_table(bvals, bvecs=None, big_delta=None, small_delta=None, b0_threshold=50, atol=0.01, btens=None)

A general function for creating diffusion MR gradients.

It reads, loads and prepares scanner parameters like the b-values and b-vectors so that they can be useful during the reconstruction process.

Parameters
bvalscan be any of the four options
  1. an array of shape (N,) or (1, N) or (N, 1) with the b-values.

  2. a path for the file which contains an array like the above (1).

  3. an array of shape (N, 4) or (4, N). Then this parameter is considered to be a b-table which contains both bvals and bvecs. In this case the next parameter is skipped.

  4. a path for the file which contains an array like the one at (3).

bvecscan be any of two options
  1. an array of shape (N, 3) or (3, N) with the b-vectors.

  2. a path for the file which contains an array like the previous.

big_deltafloat

acquisition pulse separation time in seconds (default None)

small_deltafloat

acquisition pulse duration time in seconds (default None)

b0_thresholdfloat

All b-values with values less than or equal to bo_threshold are considered as b0s i.e. without diffusion weighting.

atolfloat

All b-vectors need to be unit vectors up to a tolerance.

btenscan be any of three options
  1. a string specifying the shape of the encoding tensor for all volumes in data. Options: ‘LTE’, ‘PTE’, ‘STE’, ‘CTE’ corresponding to linear, planar, spherical, and “cigar-shaped” tensor encoding. Tensors are rotated so that linear and cigar tensors are aligned with the corresponding gradient direction and the planar tensor’s normal is aligned with the corresponding gradient direction. Magnitude is scaled to match the b-value.

  2. an array of strings of shape (N,), (N, 1), or (1, N) specifying encoding tensor shape for each volume separately. N corresponds to the number volumes in data. Options for elements in array: ‘LTE’, ‘PTE’, ‘STE’, ‘CTE’ corresponding to linear, planar, spherical, and “cigar-shaped” tensor encoding. Tensors are rotated so that linear and cigar tensors are aligned with the corresponding gradient direction and the planar tensor’s normal is aligned with the corresponding gradient direction. Magnitude is scaled to match the b-value.

  3. an array of shape (N,3,3) specifying the b-tensor of each volume exactly. N corresponds to the number volumes in data. No rotation or scaling is performed.

Returns
gradientsGradientTable

A GradientTable with all the gradient information.

Notes

  1. Often b0s (b-values which correspond to images without diffusion weighting) have 0 values however in some cases the scanner cannot provide b0s of an exact 0 value and it gives a bit higher values e.g. 6 or 12. This is the purpose of the b0_threshold in the __init__.

  2. We assume that the minimum number of b-values is 7.

  3. B-vectors should be unit vectors.

Examples

>>> from dipy.core.gradients import gradient_table
>>> bvals = 1500 * np.ones(7)
>>> bvals[0] = 0
>>> sq2 = np.sqrt(2) / 2
>>> bvecs = np.array([[0, 0, 0],
...                   [1, 0, 0],
...                   [0, 1, 0],
...                   [0, 0, 1],
...                   [sq2, sq2, 0],
...                   [sq2, 0, sq2],
...                   [0, sq2, sq2]])
>>> gt = gradient_table(bvals, bvecs)
>>> gt.bvecs.shape == bvecs.shape
True
>>> gt = gradient_table(bvals, bvecs.T)
>>> gt.bvecs.shape == bvecs.T.shape
False

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
gtabGradientTable
datandarray

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.

mean_diffusivity

dipy.reconst.mcsd.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}\]

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

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

multi_voxel_fit

dipy.reconst.mcsd.multi_voxel_fit(single_voxel_fit)

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

optional_package

dipy.reconst.mcsd.optional_package(name, trip_msg=None)

Return package-like thing and module setup for package name

Parameters
namestr

package name

trip_msgNone or str

message to give when someone tries to use the return package, but we could not import it, and have returned a TripWire object instead. Default message if None.

Returns
pkg_likemodule or TripWire instance

If we can import the package, return it. Otherwise return an object raising an error when accessed

have_pkgbool

True if import for package was successful, false otherwise

module_setupfunction

callable usually set as setup_module in calling namespace, to allow skipping tests.

Examples

Typical use would be something like this at the top of a module using an optional package:

>>> from dipy.utils.optpkg import optional_package
>>> pkg, have_pkg, setup_module = optional_package('not_a_package')

Of course in this case the package doesn’t exist, and so, in the module:

>>> have_pkg
False

and

>>> pkg.some_function() 
Traceback (most recent call last):
    ...
TripWireError: We need package not_a_package for these functions, but
``import not_a_package`` raised an ImportError

If the module does exist - we get the module

>>> pkg, _, _ = optional_package('os')
>>> hasattr(pkg, 'path')
True

Or a submodule if that’s what we asked for

>>> subpkg, _, _ = optional_package('os.path')
>>> hasattr(subpkg, 'dirname')
True

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
gtabGradientTable
datandarray

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.

response_from_mask_ssst

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

function from a given mask.

Parameters
gtabGradientTable
datandarray

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[Ra8b305330c9c-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

1

Tournier, J.D., et al. NeuroImage 2004. Direct estimation of the

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

single_tensor

dipy.reconst.mcsd.single_tensor(gtab, S0=1, evals=None, evecs=None, snr=None)

Simulate diffusion-weighted signals with a single tensor.

Parameters
gtabGradientTable

Table with information of b-values and gradient directions g. Note that if gtab has a btens attribute, simulations will be performed according to the given b-tensor B information.

S0double,

Strength of signal in the presence of no diffusion gradient (also called the b=0 value).

evals(3,) ndarray

Eigenvalues of the diffusion tensor. By default, values typical for prolate white matter are used.

evecs(3, 3) ndarray

Eigenvectors of the tensor. You can also think of this as a rotation matrix that transforms the direction of the tensor. The eigenvectors need to be column wise.

snrfloat

Signal to noise ratio, assuming Rician noise. None implies no noise.

Returns
S(N,) ndarray
Simulated signal:

S(b, g) = S_0 e^(-b g^T R D R.T g), if gtab.tens=None S(B) = S_0 e^(-B:D), if gtab.tens information is given

References

1

M. Descoteaux, “High Angular Resolution Diffusion MRI: from Local Estimation to Segmentation and Tractography”, PhD thesis, University of Nice-Sophia Antipolis, p. 42, 2008.

2

E. Stejskal and J. Tanner, “Spin diffusion measurements: spin echos in the presence of a time-dependent field gradient”, Journal of Chemical Physics, nr. 42, pp. 288–292, 1965.

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.

unique_bvals_tolerance

dipy.reconst.mcsd.unique_bvals_tolerance(bvals, tol=20)

Gives the unique b-values of the data, within a tolerance gap

The b-values must be regrouped in clusters easily separated by a distance greater than the tolerance gap. If all the b-values of a cluster fit within the tolerance gap, the highest b-value is kept.

Parameters
bvalsndarray

Array containing the b-values

tolint

The tolerated gap between the b-values to extract and the actual b-values.

Returns
ubvalsndarray

Array containing the unique b-values using the median value for each cluster

MeanDiffusionKurtosisFit

class dipy.reconst.msdki.MeanDiffusionKurtosisFit(model, model_params, model_S0=None)

Bases: object

Attributes
S0_hat

Methods

msd()

Mean signal diffusitivity (MSD) calculated from the mean signal Diffusion Kurtosis Model.

msk()

Mean signal kurtosis (MSK) calculated from the mean signal Diffusion Kurtosis Model.

predict(gtab[, S0])

Given a mean signal diffusion kurtosis model fit, predict the signal on the vertices of a sphere

smt2di()

Computes the intrisic diffusivity from the mean signal diffusional kurtosis parameters assuming the 2-compartmental spherical mean technique model [1], [2]

smt2f()

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

smt2uFA()

Computes the microscopic fractional anisotropy from the mean signal diffusional kurtosis parameters assuming the 2-compartmental spherical mean technique model [1], [2]

__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

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

msk()

Mean signal kurtosis (MSK) calculated from the mean signal Diffusion Kurtosis Model.

Returns
mskndarray

Calculated signal mean 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

predict(gtab, S0=1.0)

Given a mean signal diffusion kurtosis model fit, predict the signal on the vertices of a sphere

Parameters
gtaba GradientTable class instance

This encodes the directions for which a prediction is made

S0float 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

Intrisic diffusivity computed by converting MSDKI to SMT2.

Notes

Computes the intrinsic diffusivity using equation 16 of [1]

References

1(1,2,3)

Neto Henriques R, Jespersen SN, Shemesh N (2019). Microscopic anisotropy misestimation in spherical‐mean single diffusion encoding MRI. Magnetic Resonance in Medicine (In press). doi: 10.1002/mrm.27606

2(1,2)

Kaden E, Kelm ND, Carson RP, et al. (2016) Multi‐compartment microscopic diffusion imaging. Neuroimage 139:346–359.

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

1(1,2,3)

Neto Henriques R, Jespersen SN, Shemesh N (2019). Microscopic anisotropy misestimation in spherical‐mean single diffusion encoding MRI. Magnetic Resonance in Medicine (In press). doi: 10.1002/mrm.27606

2(1,2)

Kaden E, Kelm ND, Carson RP, et al. (2016) Multi‐compartment microscopic diffusion imaging. Neuroimage 139:346–359.

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

1(1,2,3)

Neto Henriques R, Jespersen SN, Shemesh N (2019). Microscopic anisotropy misestimation in spherical‐mean single diffusion encoding MRI. Magnetic Resonance in Medicine (In press). doi: 10.1002/mrm.27606

2(1,2)

Kaden E, Kelm ND, Carson RP, et al. (2016) Multi‐compartment microscopic diffusion imaging. Neuroimage 139:346–359.

MeanDiffusionKurtosisModel

class dipy.reconst.msdki.MeanDiffusionKurtosisModel(gtab, bmag=None, return_S0_hat=False, *args, **kwargs)

Bases: dipy.reconst.base.ReconstModel

Mean signal Diffusion Kurtosis Model

Methods

fit(data[, mask])

Fit method of the MSDKI model class

predict(msdki_params[, S0])

Predict a signal for this MeanDiffusionKurtosisModel class instance given parameters.

__init__(gtab, bmag=None, return_S0_hat=False, *args, **kwargs)

Mean Signal Diffusion Kurtosis Model [1].

Parameters
gtabGradientTable class instance
bmagint

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_hatbool

If True, also return S0 values for the fit.

args, kwargsarguments 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_paramsndarray

The parameters of the mean signal diffusion kurtosis model

S0float 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

ReconstModel

class dipy.reconst.msdki.ReconstModel(gtab)

Bases: object

Abstract class for signal reconstruction models

Methods

fit

__init__(gtab)

Initialization of the abstract class for signal reconstruction models

Parameters
gtabGradientTable class instance
fit(data, mask=None, **kwargs)

auto_attr

dipy.reconst.msdki.auto_attr(func)

Decorator to create OneTimeProperty attributes.

Parameters
funcmethod

The method that will be called the first time to compute a value. Afterwards, the method’s name will be a standard attribute holding the value of this computation.

Examples

>>> class MagicProp(object):
...     @auto_attr
...     def a(self):
...         return 99
...
>>> x = MagicProp()
>>> 'a' in x.__dict__
False
>>> x.a
99
>>> 'a' in x.__dict__
True

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

1(1,2,3)

Neto Henriques R, Jespersen SN, Shemesh N (2019). Microscopic anisotropy misestimation in spherical‐mean single diffusion encoding MRI. Magnetic Resonance in Medicine (In press). doi: 10.1002/mrm.27606

2(1,2)

Kaden E, Kelm ND, Carson RP, et al. (2016) Multi‐compartment microscopic diffusion imaging. Neuroimage 139:346–359.

check_multi_b

dipy.reconst.msdki.check_multi_b(gtab, n_bvals, non_zero=True, bmag=None)

Check if you have enough different b-values in your gradient table

Parameters
gtabGradientTable class instance.
n_bvalsint

The number of different b-values you are checking for.

non_zerobool

Whether to check only non-zero bvalues. In this case, we will require at least n_bvals non-zero b-values (where non-zero is defined depending on the gtab object’s b0_threshold attribute)

bmagint

The order of magnitude of the b-values used. The function will normalize the b-values relative \(10^{bmag}\). Default: derive this value from the maximal b-value provided: \(bmag=log_{10}(max(bvals)) - 1\).

Returns
boolWhether there are at least n_bvals different b-values in the
gradient table used.

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)

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
datandarray ([X, Y, Z, …], g)

ndarray containing the data signals in its last dimension.

gtaba GradientTable class instance

The gradient table containing diffusion acquisition parameters.

bmagThe 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
msignalndarray ([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.

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

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
paramsndarray ([X, Y, Z, …], 2)

Array containing the mean signal diffusivity and mean signal kurtosis in its last axis

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

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

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

1

Neto Henriques R, Jespersen SN, Shemesh N (2019). Microscopic anisotropy misestimation in spherical‐mean single diffusion encoding MRI. Magnetic Resonance in Medicine (In press). doi: 10.1002/mrm.27606

ndindex

dipy.reconst.msdki.ndindex(shape)

An N-dimensional iterator object to index arrays.

Given the shape of an array, an ndindex instance iterates over the N-dimensional index of the array. At each iteration a tuple of indices is returned; the last dimension is iterated over first.

Parameters
shapetuple of ints

The dimensions of the array.

Examples

>>> from dipy.core.ndindex import ndindex
>>> shape = (3, 2, 1)
>>> for index in ndindex(shape):
...     print(index)
(0, 0, 0)
(0, 1, 0)
(1, 0, 0)
(1, 1, 0)
(2, 0, 0)
(2, 1, 0)

round_bvals

dipy.reconst.msdki.round_bvals(bvals, bmag=None)

“This function rounds the b-values

Parameters
bvalsndarray

Array containing the b-values

bmagint

The order of magnitude to round the b-values. If not given b-values will be rounded relative to the order of magnitude \(bmag = (bmagmax - 1)\), where bmaxmag is the magnitude order of the larger b-value.

Returns
rbvalsndarray

Array containing the rounded b-values

unique_bvals_magnitude

dipy.reconst.msdki.unique_bvals_magnitude(bvals, bmag=None, rbvals=False)

This function gives the unique rounded b-values of the data

Parameters
bvalsndarray

Array containing the b-values

bmagint

The order of magnitude that the bvalues have to differ to be considered an unique b-value. B-values are also rounded up to this order of magnitude. Default: derive this value from the maximal b-value provided: \(bmag=log_{10}(max(bvals)) - 1\).

rbvalsbool, optional

If True function also returns all individual rounded b-values. Default: False

Returns
ubvalsndarray

Array containing the rounded unique b-values

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

1(1,2)

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

CallableArray

class dipy.reconst.multi_voxel.CallableArray

Bases: numpy.ndarray

An array which can be called like a function

Attributes
T

The transposed array.

base

Base object if memory is from some other object.

ctypes

An object to simplify the interaction of the array with the ctypes module.

data

Python buffer object pointing to the start of the array’s data.

dtype

Data-type of the array’s elements.

flags

Information about the memory layout of the array.

flat

A 1-D iterator over the array.

imag

The imaginary part of the array.

itemsize

Length of one array element in bytes.

nbytes

Total bytes consumed by the elements of the array.

ndim

Number of array dimensions.

real

The real part of the array.

shape

Tuple of array dimensions.

size

Number of elements in the array.

strides

Tuple of bytes to step in each dimension when traversing an array.

Methods

__call__(*args, **kwargs)

Call self as a function.

all([axis, out, keepdims, where])

Returns True if all elements evaluate to True.

any([axis, out, keepdims, where])

Returns True if any of the elements of a evaluate to True.

argmax([axis, out])

Return indices of the maximum values along the given axis.

argmin([axis, out])

Return indices of the minimum values along the given axis.

argpartition(kth[, axis, kind, order])

Returns the indices that would partition this array.

argsort([axis, kind, order])

Returns the indices that would sort this array.

astype(dtype[, order, casting, subok, copy])

Copy of the array, cast to a specified type.

byteswap([inplace])

Swap the bytes of the array elements

choose(choices[, out, mode])

Use an index array to construct a new array from a set of choices.

clip([min, max, out])

Return an array whose values are limited to [min, max].

compress(condition[, axis, out])

Return selected slices of this array along given axis.

conj()

Complex-conjugate all elements.

conjugate()

Return the complex conjugate, element-wise.

copy([order])

Return a copy of the array.

cumprod([axis, dtype, out])

Return the cumulative product of the elements along the given axis.

cumsum([axis, dtype, out])

Return the cumulative sum of the elements along the given axis.

diagonal([offset, axis1, axis2])

Return specified diagonals.

dump(file)

Dump a pickle of the array to the specified file.

dumps()

Returns the pickle of the array as a string.

fill(value)

Fill the array with a scalar value.

flatten([order])

Return a copy of the array collapsed into one dimension.

getfield(dtype[, offset])

Returns a field of the given array as a certain type.

item(*args)

Copy an element of an array to a standard Python scalar and return it.

itemset(*args)

Insert scalar into an array (scalar is cast to array's dtype, if possible)

max([axis, out, keepdims, initial, where])

Return the maximum along a given axis.

mean([axis, dtype, out, keepdims, where])

Returns the average of the array elements along given axis.

min([axis, out, keepdims, initial, where])

Return the minimum along a given axis.

newbyteorder([new_order])

Return the array with the same data viewed with a different byte order.

nonzero()

Return the indices of the elements that are non-zero.

partition(kth[, axis, kind, order])

Rearranges the elements in the array in such a way that the value of the element in kth position is in the position it would be in a sorted array.

prod([axis, dtype, out, keepdims, initial, ...])

Return the product of the array elements over the given axis

ptp([axis, out, keepdims])

Peak to peak (maximum - minimum) value along a given axis.

put(indices, values[, mode])

Set a.flat[n] = values[n] for all n in indices.

ravel([order])

Return a flattened array.

repeat(repeats[, axis])

Repeat elements of an array.

reshape(shape[, order])

Returns an array containing the same data with a new shape.

resize(new_shape[, refcheck])

Change shape and size of array in-place.

round([decimals, out])

Return a with each element rounded to the given number of decimals.

searchsorted(v[, side, sorter])

Find indices where elements of v should be inserted in a to maintain order.

setfield(val, dtype[, offset])

Put a value into a specified place in a field defined by a data-type.

setflags([write, align, uic])

Set array flags WRITEABLE, ALIGNED, (WRITEBACKIFCOPY and UPDATEIFCOPY), respectively.

sort([axis, kind, order])

Sort an array in-place.

squeeze([axis])

Remove axes of length one from a.

std([axis, dtype, out, ddof, keepdims, where])

Returns the standard deviation of the array elements along given axis.

sum([axis, dtype, out, keepdims, initial, where])

Return the sum of the array elements over the given axis.

swapaxes(axis1, axis2)

Return a view of the array with axis1 and axis2 interchanged.

take(indices[, axis, out, mode])

Return an array formed from the elements of a at the given indices.

tobytes([order])

Construct Python bytes containing the raw data bytes in the array.

tofile(fid[, sep, format])

Write array to a file as text or binary (default).

tolist()

Return the array as an a.ndim-levels deep nested list of Python scalars.

tostring([order])

A compatibility alias for tobytes, with exactly the same behavior.

trace([offset, axis1, axis2, dtype, out])

Return the sum along diagonals of the array.

transpose(*axes)

Returns a view of the array with axes transposed.

var([axis, dtype, out, ddof, keepdims, where])

Returns the variance of the array elements, along given axis.

view([dtype][, type])

New view of array with the same data.

dot

__init__(*args, **kwargs)

MultiVoxelFit

class dipy.reconst.multi_voxel.MultiVoxelFit(model, fit_array, mask)

Bases: dipy.reconst.base.ReconstFit

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

Attributes
shape

Methods

predict(*args, **kwargs)

Predict for the multi-voxel object using each single-object's prediction API, with S0 provided from an array.

__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

ReconstFit

class dipy.reconst.multi_voxel.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)

tqdm

class dipy.reconst.multi_voxel.tqdm(*_, **__)

Bases: tqdm.utils.Comparable

Decorate an iterable object, returning an iterator which acts exactly like the original iterable, but prints a dynamically updating progressbar every time a value is requested.

Attributes
format_dict

Public API for read-only member access.

monitor

Methods

clear([nolock])

Clear current bar display.

close()

Cleanup and (if leave=False) close the progressbar.

display([msg, pos])

Use self.sp to display msg in the specified pos.

external_write_mode([file, nolock])

Disable tqdm within context and refresh tqdm when exits.

format_interval(t)

Formats a number of seconds as a clock time, [H:]MM:SS

format_meter(n, total, elapsed[, ncols, ...])

Return a string-based progress bar given some parameters

format_num(n)

Intelligent scientific notation (.3g).

format_sizeof(num[, suffix, divisor])

Formats a number (greater than unity) with SI Order of Magnitude prefixes.

get_lock()

Get the global lock.

pandas(**tqdm_kwargs)

Registers the current tqdm class with

refresh([nolock, lock_args])

Force refresh the display of this bar.

reset([total])

Resets to 0 iterations for repeated use.

set_description([desc, refresh])

Set/modify description of the progress bar.

set_description_str([desc, refresh])

Set/modify description without ': ' appended.

set_lock(lock)

Set the global lock.

set_postfix([ordered_dict, refresh])

Set/modify postfix (additional stats) with automatic formatting based on datatype.

set_postfix_str([s, refresh])

Postfix without dictionary expansion, similar to prefix handling.

status_printer(file)

Manage the printing and in-place updating of a line of characters.

unpause()

Restart tqdm timer from last print time.

update([n])

Manually update the progress bar, useful for streams such as reading files.

wrapattr(stream, method[, total, bytes])

stream : file-like object. method : str, "read" or "write". The result of read() and the first argument of write() should have a len().

write(s[, file, end, nolock])

Print a message via tqdm (without overlap with bars).

moveto

__init__(iterable=None, desc=None, total=None, leave=True, file=None, ncols=None, mininterval=0.1, maxinterval=10.0, miniters=None, ascii=None, disable=False, unit='it', unit_scale=False, dynamic_ncols=False, smoothing=0.3, bar_format=None, initial=0, position=None, postfix=None, unit_divisor=1000, write_bytes=None, lock_args=None, nrows=None, colour=None, delay=0, gui=False, **kwargs)
Parameters
iterableiterable, optional

Iterable to decorate with a progressbar. Leave blank to manually manage the updates.

descstr, optional

Prefix for the progressbar.

totalint or float, optional

The number of expected iterations. If unspecified, len(iterable) is used if possible. If float(“inf”) or as a last resort, only basic progress statistics are displayed (no ETA, no progressbar). If gui is True and this parameter needs subsequent updating, specify an initial arbitrary large positive number, e.g. 9e9.

leavebool, optional

If [default: True], keeps all traces of the progressbar upon termination of iteration. If None, will leave only if position is 0.

fileio.TextIOWrapper or io.StringIO, optional

Specifies where to output the progress messages (default: sys.stderr). Uses file.write(str) and file.flush() methods. For encoding, see write_bytes.

ncolsint, optional

The width of the entire output message. If specified, dynamically resizes the progressbar to stay within this bound. If unspecified, attempts to use environment width. The fallback is a meter width of 10 and no limit for the counter and statistics. If 0, will not print any meter (only stats).

minintervalfloat, optional

Minimum progress display update interval [default: 0.1] seconds.

maxintervalfloat, optional

Maximum progress display update interval [default: 10] seconds. Automatically adjusts miniters to correspond to mininterval after long display update lag. Only works if dynamic_miniters or monitor thread is enabled.

minitersint or float, optional

Minimum progress display update interval, in iterations. If 0 and dynamic_miniters, will automatically adjust to equal mininterval (more CPU efficient, good for tight loops). If > 0, will skip display of specified number of iterations. Tweak this and mininterval to get very efficient loops. If your progress is erratic with both fast and slow iterations (network, skipping items, etc) you should set miniters=1.

asciibool or str, optional

If unspecified or False, use unicode (smooth blocks) to fill the meter. The fallback is to use ASCII characters ” 123456789#”.

disablebool, optional

Whether to disable the entire progressbar wrapper [default: False]. If set to None, disable on non-TTY.

unitstr, optional

String that will be used to define the unit of each iteration [default: it].

unit_scalebool or int or float, optional

If 1 or True, the number of iterations will be reduced/scaled automatically and a metric prefix following the International System of Units standard will be added (kilo, mega, etc.) [default: False]. If any other non-zero number, will scale total and n.

dynamic_ncolsbool, optional

If set, constantly alters ncols and nrows to the environment (allowing for window resizes) [default: False].

smoothingfloat, optional

Exponential moving average smoothing factor for speed estimates (ignored in GUI mode). Ranges from 0 (average speed) to 1 (current/instantaneous speed) [default: 0.3].

bar_formatstr, optional

Specify a custom bar string formatting. May impact performance. [default: ‘{l_bar}{bar}{r_bar}’], where l_bar=’{desc}: {percentage:3.0f}%|’ and r_bar=’| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, ‘

‘{rate_fmt}{postfix}]’

Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt,

percentage, elapsed, elapsed_s, ncols, nrows, desc, unit, rate, rate_fmt, rate_noinv, rate_noinv_fmt, rate_inv, rate_inv_fmt, postfix, unit_divisor, remaining, remaining_s, eta.

Note that a trailing “: ” is automatically removed after {desc} if the latter is empty.

initialint or float, optional

The initial counter value. Useful when restarting a progress bar [default: 0]. If using float, consider specifying {n:.3f} or similar in bar_format, or specifying unit_scale.

positionint, optional

Specify the line offset to print this bar (starting from 0) Automatic if unspecified. Useful to manage multiple bars at once (eg, from threads).

postfixdict or *, optional

Specify additional stats to display at the end of the bar. Calls set_postfix(**postfix) if possible (dict).

unit_divisorfloat, optional

[default: 1000], ignored unless unit_scale is True.

write_bytesbool, optional

If (default: None) and file is unspecified, bytes will be written in Python 2. If True will also write bytes. In all other cases will default to unicode.

lock_argstuple, optional

Passed to refresh for intermediate output (initialisation, iterating, and updating).

nrowsint, optional

The screen height. If specified, hides nested bars outside this bound. If unspecified, attempts to use environment height. The fallback is 20.

colourstr, optional

Bar colour (e.g. ‘green’, ‘#00ff00’).

delayfloat, optional

Don’t display until [default: 0] seconds have elapsed.

guibool, optional

WARNING: internal parameter - do not use. Use tqdm.gui.tqdm(…) instead. If set, will attempt to use matplotlib animations for a graphical output [default: False].

Returns
outdecorated iterator.
clear(nolock=False)

Clear current bar display.

close()

Cleanup and (if leave=False) close the progressbar.

display(msg=None, pos=None)

Use self.sp to display msg in the specified pos.

Consider overloading this function when inheriting to use e.g.: self.some_frontend(**self.format_dict) instead of self.sp.

Parameters
msgstr, optional. What to display (default: repr(self)).
posint, optional. Position to moveto

(default: abs(self.pos)).

classmethod external_write_mode(file=None, nolock=False)

Disable tqdm within context and refresh tqdm when exits. Useful when writing to standard output stream

property format_dict

Public API for read-only member access.

static format_interval(t)

Formats a number of seconds as a clock time, [H:]MM:SS

Parameters
tint

Number of seconds.

Returns
outstr

[H:]MM:SS

static format_meter(n, total, elapsed, ncols=None, prefix='', ascii=False, unit='it', unit_scale=False, rate=None, bar_format=None, postfix=None, unit_divisor=1000, initial=0, colour=None, **extra_kwargs)

Return a string-based progress bar given some parameters

Parameters
nint or float

Number of finished iterations.

totalint or float

The expected total number of iterations. If meaningless (None), only basic progress statistics are displayed (no ETA).

elapsedfloat

Number of seconds passed since start.

ncolsint, optional

The width of the entire output message. If specified, dynamically resizes {bar} to stay within this bound [default: None]. If 0, will not print any bar (only stats). The fallback is {bar:10}.

prefixstr, optional

Prefix message (included in total width) [default: ‘’]. Use as {desc} in bar_format string.

asciibool, optional or str, optional

If not set, use unicode (smooth blocks) to fill the meter [default: False]. The fallback is to use ASCII characters ” 123456789#”.

unitstr, optional

The iteration unit [default: ‘it’].

unit_scalebool or int or float, optional

If 1 or True, the number of iterations will be printed with an appropriate SI metric prefix (k = 10^3, M = 10^6, etc.) [default: False]. If any other non-zero number, will scale total and n.

ratefloat, optional

Manual override for iteration rate. If [default: None], uses n/elapsed.

bar_formatstr, optional

Specify a custom bar string formatting. May impact performance. [default: ‘{l_bar}{bar}{r_bar}’], where l_bar=’{desc}: {percentage:3.0f}%|’ and r_bar=’| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, ‘

‘{rate_fmt}{postfix}]’

Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt,

percentage, elapsed, elapsed_s, ncols, nrows, desc, unit, rate, rate_fmt, rate_noinv, rate_noinv_fmt, rate_inv, rate_inv_fmt, postfix, unit_divisor, remaining, remaining_s, eta.

Note that a trailing “: ” is automatically removed after {desc} if the latter is empty.

postfix*, optional

Similar to prefix, but placed at the end (e.g. for additional stats). Note: postfix is usually a string (not a dict) for this method, and will if possible be set to postfix = ‘, ‘ + postfix. However other types are supported (#382).

unit_divisorfloat, optional

[default: 1000], ignored unless unit_scale is True.

initialint or float, optional

The initial counter value [default: 0].

colourstr, optional

Bar colour (e.g. ‘green’, ‘#00ff00’).

Returns
outFormatted meter and stats, ready to display.
static format_num(n)

Intelligent scientific notation (.3g).

Parameters
nint or float or Numeric

A Number.

Returns
outstr

Formatted number.

static format_sizeof(num, suffix='', divisor=1000)

Formats a number (greater than unity) with SI Order of Magnitude prefixes.

Parameters
numfloat

Number ( >= 1) to format.

suffixstr, optional

Post-postfix [default: ‘’].

divisorfloat, optional

Divisor between prefixes [default: 1000].

Returns
outstr

Number with Order of Magnitude SI unit postfix.

classmethod get_lock()

Get the global lock. Construct it if it does not exist.

monitor = None
monitor_interval = 10
moveto(n)
classmethod pandas(**tqdm_kwargs)
Registers the current tqdm class with

pandas.core. ( frame.DataFrame | series.Series | groupby.(generic.)DataFrameGroupBy | groupby.(generic.)SeriesGroupBy ).progress_apply

A new instance will be create every time progress_apply is called, and each instance will automatically close() upon completion.

Parameters
tqdm_kwargsarguments for the tqdm instance

References

<https://stackoverflow.com/questions/18603270/ progress-indicator-during-pandas-operations-python>

Examples

>>> import pandas as pd
>>> import numpy as np
>>> from tqdm import tqdm
>>> from tqdm.gui import tqdm as tqdm_gui
>>>
>>> df = pd.DataFrame(np.random.randint(0, 100, (100000, 6)))
>>> tqdm.pandas(ncols=50)  # can use tqdm_gui, optional kwargs, etc
>>> # Now you can use `progress_apply` instead of `apply`
>>> df.groupby(0).progress_apply(lambda x: x**2)
refresh(nolock=False, lock_args=None)

Force refresh the display of this bar.

Parameters
nolockbool, optional

If True, does not lock. If [default: False]: calls acquire() on internal lock.

lock_argstuple, optional

Passed to internal lock’s acquire(). If specified, will only display() if acquire() returns True.

reset(total=None)

Resets to 0 iterations for repeated use.

Consider combining with leave=True.

Parameters
totalint or float, optional. Total to use for the new bar.
set_description(desc=None, refresh=True)

Set/modify description of the progress bar.

Parameters
descstr, optional
refreshbool, optional

Forces refresh [default: True].

set_description_str(desc=None, refresh=True)

Set/modify description without ‘: ‘ appended.

classmethod set_lock(lock)

Set the global lock.

set_postfix(ordered_dict=None, refresh=True, **kwargs)

Set/modify postfix (additional stats) with automatic formatting based on datatype.

Parameters
ordered_dictdict or OrderedDict, optional
refreshbool, optional

Forces refresh [default: True].

kwargsdict, optional
set_postfix_str(s='', refresh=True)

Postfix without dictionary expansion, similar to prefix handling.

static status_printer(file)

Manage the printing and in-place updating of a line of characters. Note that if the string is longer than a line, then in-place updating may not work (it will print a new line at each refresh).

unpause()

Restart tqdm timer from last print time.

update(n=1)

Manually update the progress bar, useful for streams such as reading files. E.g.: >>> t = tqdm(total=filesize) # Initialise >>> for current_buffer in stream: … … … t.update(len(current_buffer)) >>> t.close() The last line is highly recommended, but possibly not necessary if t.update() will be called in such a way that filesize will be exactly reached and printed.

Parameters
nint or float, optional

Increment to add to the internal counter of iterations [default: 1]. If using float, consider specifying {n:.3f} or similar in bar_format, or specifying unit_scale.

Returns
outbool or None

True if a display() was triggered.

classmethod wrapattr(stream, method, total=None, bytes=True, **tqdm_kwargs)

stream : file-like object. method : str, “read” or “write”. The result of read() and

the first argument of write() should have a len().

>>> with tqdm.wrapattr(file_obj, "read", total=file_obj.size) as fobj:
...     while True:
...         chunk = fobj.read(chunk_size)
...         if not chunk:
...             break
classmethod write(s, file=None, end='\n', nolock=False)

Print a message via tqdm (without overlap with bars).

as_strided

dipy.reconst.multi_voxel.as_strided(x, shape=None, strides=None, subok=False, writeable=True)

Create a view into the array with the given shape and strides.

Warning

This function has to be used with extreme care, see notes.

Parameters
xndarray

Array to create a new.

shapesequence of int, optional

The shape of the new array. Defaults to x.shape.

stridessequence of int, optional

The strides of the new array. Defaults to x.strides.

subokbool, optional

New in version 1.10.

If True, subclasses are preserved.

writeablebool, optional

New in version 1.12.

If set to False, the returned array will always be readonly. Otherwise it will be writable if the original array was. It is advisable to set this to False if possible (see Notes).

Returns
viewndarray

See also

broadcast_to

broadcast an array to a given shape.

reshape

reshape an array.

lib.stride_tricks.sliding_window_view

userfriendly and safe function for the creation of sliding window views.

Notes

as_strided creates a view into the array given the exact strides and shape. This means it manipulates the internal data structure of ndarray and, if done incorrectly, the array elements can point to invalid memory and can corrupt results or crash your program. It is advisable to always use the original x.strides when calculating new strides to avoid reliance on a contiguous memory layout.

Furthermore, arrays created with this function often contain self overlapping memory, so that two elements are identical. Vectorized write operations on such arrays will typically be unpredictable. They may even give different results for small, large, or transposed arrays. Since writing to these arrays has to be tested and done with great care, you may want to use writeable=False to avoid accidental write operations.

For these reasons it is advisable to avoid as_strided when possible.

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

ndindex

dipy.reconst.multi_voxel.ndindex(shape)

An N-dimensional iterator object to index arrays.

Given the shape of an array, an ndindex instance iterates over the N-dimensional index of the array. At each iteration a tuple of indices is returned; the last dimension is iterated over first.

Parameters
shapetuple of ints

The dimensions of the array.

Examples

>>> from dipy.core.ndindex import ndindex
>>> shape = (3, 2, 1)
>>> for index in ndindex(shape):
...     print(index)
(0, 0, 0)
(0, 1, 0)
(1, 0, 0)
(1, 1, 0)
(2, 0, 0)
(2, 1, 0)

OdfFit

class dipy.reconst.odf.OdfFit(model, data)

Bases: dipy.reconst.base.ReconstFit

Methods

odf(sphere)

To be implemented but specific odf models

__init__(model, data)
odf(sphere)

To be implemented but specific odf models

OdfModel

class dipy.reconst.odf.OdfModel(gtab)

Bases: dipy.reconst.base.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.

Methods

fit(data)

To be implemented by specific odf models

__init__(gtab)

Initialization of the abstract class for signal reconstruction models

Parameters
gtabGradientTable class instance
fit(data)

To be implemented by specific odf models

ReconstFit

class dipy.reconst.odf.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)

ReconstModel

class dipy.reconst.odf.ReconstModel(gtab)

Bases: object

Abstract class for signal reconstruction models

Methods

fit

__init__(gtab)

Initialization of the abstract class for signal reconstruction models

Parameters
gtabGradientTable class instance
fit(data, mask=None, **kwargs)

gfa

dipy.reconst.odf.gfa(samples)

The general fractional anisotropy of a function evaluated on the unit sphere

Parameters
samplesndarray

Values of data on the unit sphere.

Returns
gfandarray

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.

Cache

class dipy.reconst.qtdmri.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)

Methods

cache_clear()

Clear the cache.

cache_get(tag, key[, default])

Retrieve a value from the cache.

cache_set(tag, key, value)

Store a value in the cache.

__init__(*args, **kwargs)
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

QtdmriFit

class dipy.reconst.qtdmri.QtdmriFit(model, qtdmri_coef, us, ut, tau_scaling, R, lopt, alpha, cvxpy_solution_optimal)

Bases: object

Methods

fitted_signal([gtab])

Recovers the fitted signal for the given gradient table.

msd(tau)

Calculates the analytical Mean Squared Displacement (MSD) for a given diffusion time tau.

norm_of_laplacian_signal()

Calculates the norm of the laplacian of the fitted signal [Re930b800cbc4-1].

odf(sphere, tau[, s])

Calculates the analytical Orientation Distribution Function (ODF) for a given diffusion time tau from the signal, [1] Eq.

odf_sh(tau[, s])

Calculates the real analytical odf for a given discrete sphere.

pdf(rt_points)

Diffusion propagator on a given set of real points.

predict(qvals_or_gtab[, S0])

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

qiv(tau)

Calculates the analytical Q-space Inverse Variance (QIV) for given diffusion time tau.

qtdmri_to_mapmri_coef(tau)

This function converts the qtdmri coefficients to mapmri coefficients for a given tau [1].

rtap(tau)

Calculates the analytical return to the axis probability (RTAP) for a given diffusion time tau, [1] eq.

rtop(tau)

Calculates the analytical return to the origin probability (RTOP) for a given diffusion time tau [1] eq.

rtpp(tau)

Calculates the analytical return to the plane probability (RTPP) for a given diffusion time tau, [1] eq.

sparsity_abs([threshold])

As a measure of sparsity, calculates the number of largest coefficients needed to absolute sum up to 99% of the total absolute sum of all coefficients

sparsity_density([threshold])

As a measure of sparsity, calculates the number of largest coefficients needed to squared sum up to 99% of the total squared sum of all coefficients

__init__(model, qtdmri_coef, us, ut, tau_scaling, R, lopt, alpha, cvxpy_solution_optimal)

Calculates diffusion properties for a single voxel

Parameters
modelobject,

AnalyticalModel

qtdmri_coef1d ndarray,

qtdmri coefficients

usarray, 3 x 1

spatial scaling factors

utfloat

temporal scaling factor

tau_scalingfloat,

the temporal scaling that used to scale tau to the size of us

R3x3 numpy array,

tensor eigenvectors

loptfloat,

laplacian regularization weight

alphafloat,

the l1 regularization weight

cvxpy_solution_optimal: bool,

indicates whether the cvxpy coefficient estimation reach an optimal solution

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.

msd(tau)

Calculates the analytical Mean Squared Displacement (MSD) for a given diffusion time tau. It is defined as the Laplacian of the origin of the estimated signal [1]. The analytical formula for the MAP-MRI basis was derived in [R9ee09c2d0d0c-2] eq. (C13, D1). The qtdmri coefficients are first converted to mapmri coefficients following [3].

Parameters
taufloat

diffusion time (big_delta - small_delta / 3.) in seconds

References

1

Cheng, J., 2014. Estimation and Processing of Ensemble Average Propagator and Its Features in Diffusion MRI. Ph.D. Thesis.

3

Fick, Rutger HJ, et al. “Non-Parametric GraphNet-Regularized Representation of dMRI in Space and Time”, Medical Image Analysis, 2017.

norm_of_laplacian_signal()

Calculates the norm of the laplacian of the fitted signal [Re930b800cbc4-1]. This information could be useful to assess if the extrapolation of the fitted signal contains spurious oscillations. A high laplacian norm may indicate that these are present, and any q-space indices that use integrals of the signal may be corrupted (e.g. RTOP, RTAP, RTPP, QIV). In contrast to [1], the Laplacian now describes oscillations in the 4-dimensional qt-signal [2].

References

2

Fick, Rutger HJ, et al. “Non-Parametric GraphNet-Regularized Representation of dMRI in Space and Time”, Medical Image Analysis, 2017.

odf(sphere, tau, s=2)

Calculates the analytical Orientation Distribution Function (ODF) for a given diffusion time tau from the signal, [1] Eq. (32). The qtdmri coefficients are first converted to mapmri coefficients following [2].

Parameters
spheredipy sphere object

sphere object with vertice orientations to compute the ODF on.

taufloat

diffusion time (big_delta - small_delta / 3.) in seconds

sunsigned int

radial moment of the ODF

References

1(1,2)

Ozarslan E. et. al, “Mean apparent propagator (MAP) MRI: A novel diffusion imaging method for mapping tissue microstructure”, NeuroImage, 2013.

2

Fick, Rutger HJ, et al. “Non-Parametric GraphNet-Regularized Representation of dMRI in Space and Time”, Medical Image Analysis, 2017.

odf_sh(tau, 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 [R0a1decd741db-2] eq. (C8). The qtdmri coefficients are first converted to mapmri coefficients following [3].

Parameters
taufloat

diffusion time (big_delta - small_delta / 3.) in seconds

sunsigned int

radial moment of the ODF

References

1

Ozarslan E. et. al, “Mean apparent propagator (MAP) MRI: A novel diffusion imaging method for mapping tissue microstructure”, NeuroImage, 2013.

3

Fick, Rutger HJ, et al. “Non-Parametric GraphNet-Regularized Representation of dMRI in Space and Time”, Medical Image Analysis, 2017.

pdf(rt_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=1.0)

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

qiv(tau)

Calculates the analytical Q-space Inverse Variance (QIV) for given diffusion time tau. It is defined as the inverse of the Laplacian of the origin of the estimated propagator [1] eq. (22). The analytical formula for the MAP-MRI basis was derived in [R1e32c9d7d6dc-2] eq. (C14, D2). The qtdmri coefficients are first converted to mapmri coefficients following [3].

Parameters
taufloat

diffusion time (big_delta - small_delta / 3.) in seconds

References

1

Hosseinbor et al. “Bessel fourier orientation reconstruction (bfor): An analytical diffusion propagator reconstruction for hybrid diffusion imaging and computation of q-space indices. NeuroImage 64, 2013, 650–670.

3

Fick, Rutger HJ, et al. “Non-Parametric GraphNet-Regularized Representation of dMRI in Space and Time”, Medical Image Analysis, 2017.

qtdmri_to_mapmri_coef(tau)

This function converts the qtdmri coefficients to mapmri coefficients for a given tau [1]. The conversion is performed by a matrix multiplication that evaluates the time-depenent part of the basis and multiplies it with the coefficients, after which coefficients with the same spatial orders are summed up, resulting in mapmri coefficients.

Parameters
taufloat

diffusion time (big_delta - small_delta / 3.) in seconds

References

1(1,2)

Fick, Rutger HJ, et al. “Non-Parametric GraphNet-Regularized Representation of dMRI in Space and Time”, Medical Image Analysis, 2017.

rtap(tau)

Calculates the analytical return to the axis probability (RTAP) for a given diffusion time tau, [1] eq. (40, 44a). The analytical formula for the isotropic MAP-MRI basis was derived in [Rb426f7ff6c1f-2] eq. (C11). The qtdmri coefficients are first converted to mapmri coefficients following [3].

Parameters
taufloat

diffusion time (big_delta - small_delta / 3.) in seconds

References

1(1,2)

Ozarslan E. et. al, “Mean apparent propagator (MAP) MRI: A novel diffusion imaging method for mapping tissue microstructure”, NeuroImage, 2013.

3

Fick, Rutger HJ, et al. “Non-Parametric GraphNet-Regularized Representation of dMRI in Space and Time”, Medical Image Analysis, 2017.

rtop(tau)

Calculates the analytical return to the origin probability (RTOP) for a given diffusion time tau [1] eq. (36, 43). The analytical formula for the isotropic MAP-MRI basis was derived in [Rae9ef6a2072f-2] eq. (C11). The qtdmri coefficients are first converted to mapmri coefficients following [3].

Parameters
taufloat

diffusion time (big_delta - small_delta / 3.) in seconds

References

1(1,2)

Ozarslan E. et. al, “Mean apparent propagator (MAP) MRI: A novel diffusion imaging method for mapping tissue microstructure”, NeuroImage, 2013.

3

Fick, Rutger HJ, et al. “Non-Parametric GraphNet-Regularized Representation of dMRI in Space and Time”, Medical Image Analysis, 2017.

rtpp(tau)

Calculates the analytical return to the plane probability (RTPP) for a given diffusion time tau, [1] eq. (42). The analytical formula for the isotropic MAP-MRI basis was derived in [R0ef534f1e9fc-2] eq. (C11). The qtdmri coefficients are first converted to mapmri coefficients following [3].

Parameters
taufloat

diffusion time (big_delta - small_delta / 3.) in seconds

References

1(1,2)

Ozarslan E. et. al, “Mean apparent propagator (MAP) MRI: A novel diffusion imaging method for mapping tissue microstructure”, NeuroImage, 2013.

3

Fick, Rutger HJ, et al. “Non-Parametric GraphNet-Regularized Representation of dMRI in Space and Time”, Medical Image Analysis, 2017.

sparsity_abs(threshold=0.99)

As a measure of sparsity, calculates the number of largest coefficients needed to absolute sum up to 99% of the total absolute sum of all coefficients

sparsity_density(threshold=0.99)

As a measure of sparsity, calculates the number of largest coefficients needed to squared sum up to 99% of the total squared sum of all coefficients

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: dipy.reconst.cache.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 funcions, \(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
gtabGradientTable,

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_orderunsigned int,

an even integer representing the spatial/radial order of the basis.

time_orderunsigned int,

an integer larger or equal than zero representing the time order of the basis.

laplacian_regularizationbool,

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_regularizationbool,

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.

cartesianbool

Whether to use the Cartesian or spherical implementation of the qt-dMRI basis, which we first explored in [4].

anisotropic_scalingbool

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.

normalizationbool

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_q0bool

whether to constrain the q0 point to unity along the tau-space. This is necessary to ensure that \(E(0,\tau)=1\).

bval_thresholdfloat

the threshold b-value to be used, such that only data points below that threshold are used when estimating the scale factors.

eigenvalue_thresholdfloat,

Sets the minimum of the tensor eigenvalues in order to avoid stability problem.

cvxpy_solverstr, optional

cvxpy solver name. Optionally optimize the positivity constraint with a particular cvxpy solver. See See http://www.cvxpy.org/ for details. Default: ECOS.

References

1

Fick, Rutger HJ, et al. “Non-Parametric GraphNet-Regularized Representation of dMRI in Space and Time”, Medical Image Analysis, 2017.

2

Ozarslan E. et al., “Mean apparent propagator (MAP) MRI: A novel diffusion imaging method for mapping tissue microstructure”, NeuroImage, 2013.

3

Craven et al. “Smoothing Noisy Data with Spline Functions.” NUMER MATH 31.4 (1978): 377-403.

4

Fick, Rutger HJ, et al. “A unifying framework for spatial and temporal diffusion in diffusion mri.” International Conference on Information Processing in Medical Imaging. Springer, Cham, 2015.

Methods

cache_clear()

Clear the cache.

cache_get(tag, key[, default])

Retrieve a value from the cache.

cache_set(tag, key, value)

Store a value in the cache.

fit(data[, mask])

Fit method for every voxel in data

__init__(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')
fit(data, mask=None)

Fit method for every voxel in data

Version

class dipy.reconst.qtdmri.Version(version: str)

Bases: packaging.version._BaseVersion

Attributes
base_version
dev
epoch
is_devrelease
is_postrelease
is_prerelease
local
major
micro
minor
post
pre
public
release
__init__(version: str) None
property base_version: str
property dev: Optional[int]
property epoch: int
property is_devrelease: bool
property is_postrelease: bool
property is_prerelease: bool
property local: Optional[str]
property major: int
property micro: int
property minor: int
property post: Optional[int]
property pre: Optional[Tuple[str, int]]
property public: str
property release: Tuple[int, ...]

GCV_cost_function

dipy.reconst.qtdmri.GCV_cost_function(weight, arguments)

Generalized Cross Validation Function that is iterated [1].

References

1

Craven et al. “Smoothing Noisy Data with Spline Functions.” NUMER MATH 31.4 (1978): 377-403.

H

dipy.reconst.qtdmri.H(value)

Step function of H(x)=1 if x>=0 and zero otherwise. Used for the temporal laplacian matrix.

angular_basis_EAP_opt

dipy.reconst.qtdmri.angular_basis_EAP_opt(j, l, m, r, theta, phi)

angular_basis_opt

dipy.reconst.qtdmri.angular_basis_opt(l, m, q, theta, phi)

Angular basis independent of spatial scaling factor us. Though it includes q, it is independent of the data and can be precomputed.

cart2sphere

dipy.reconst.qtdmri.cart2sphere(x, y, z)

Return angles for Cartesian 3D coordinates x, y, and z

See doc for sphere2cart for angle conventions and derivation of the formulae.

\(0\le\theta\mathrm{(theta)}\le\pi\) and \(-\pi\le\phi\mathrm{(phi)}\le\pi\)

Parameters
xarray_like

x coordinate in Cartesian space

yarray_like

y coordinate in Cartesian space

zarray_like

z coordinate

Returns
rarray

radius

thetaarray

inclination (polar) angle

phiarray

azimuth angle

create_rt_space_grid

dipy.reconst.qtdmri.create_rt_space_grid(grid_size_r, max_radius_r, grid_size_tau, min_radius_tau, max_radius_tau)

Generates EAP grid (for potential positivity constraint).

design_matrix_spatial

dipy.reconst.qtdmri.design_matrix_spatial(bvecs, qvals)

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

Parameters
bvecsarray (N x 3)

unit b-vectors of the acquisition.

qvalsarray (N,)

corresponding q-values in 1/mm

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)

elastic_crossvalidation

dipy.reconst.qtdmri.elastic_crossvalidation(b0s_mask, E, M, L, lopt, weight_array=array([0., 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1, 0.11, 0.12, 0.13, 0.14, 0.15, 0.16, 0.17, 0.18, 0.19, 0.2]))

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

factorial

dipy.reconst.qtdmri.factorial(n, exact=False)

The factorial of a number or array of numbers.

The factorial of non-negative integer n is the product of all positive integers less than or equal to n:

n! = n * (n - 1) * (n - 2) * ... * 1
Parameters
nint or array_like of ints

Input values. If n < 0, the return value is 0.

exactbool, optional

If True, calculate the answer exactly using long integer arithmetic. If False, result is approximated in floating point rapidly using the gamma function. Default is False.

Returns
nffloat or int or ndarray

Factorial of n, as integer or float depending on exact.

Notes

For arrays with exact=True, the factorial is computed only once, for the largest input, with each other result computed in the process. The output dtype is increased to int64 or object if necessary.

With exact=False the factorial is approximated using the gamma function:

\[n! = \Gamma(n+1)\]

Examples

>>> from scipy.special import factorial
>>> arr = np.array([3, 4, 5])
>>> factorial(arr, exact=False)
array([   6.,   24.,  120.])
>>> factorial(arr, exact=True)
array([  6,  24, 120])
>>> factorial(5, exact=True)
120

factorial2

dipy.reconst.qtdmri.factorial2(n, exact=False)

Double factorial.

This is the factorial with every second value skipped. E.g., 7!! = 7 * 5 * 3 * 1. It can be approximated numerically as:

n!! = special.gamma(n/2+1)*2**((m+1)/2)/sqrt(pi)  n odd
    = 2**(n/2) * (n/2)!                           n even
Parameters
nint or array_like

Calculate n!!. Arrays are only supported with exact set to False. If n < 0, the return value is 0.

exactbool, optional

The result can be approximated rapidly using the gamma-formula above (default). If exact is set to True, calculate the answer exactly using integer arithmetic.

Returns
nfffloat or int

Double factorial of n, as an int or a float depending on exact.

Examples

>>> from scipy.special import factorial2
>>> factorial2(7, exact=False)
array(105.00000000000001)
>>> factorial2(7, exact=True)
105

fmin_l_bfgs_b

dipy.reconst.qtdmri.fmin_l_bfgs_b(func, x0, fprime=None, args=(), approx_grad=0, bounds=None, m=10, factr=10000000.0, pgtol=1e-05, epsilon=1e-08, iprint=- 1, maxfun=15000, maxiter=15000, disp=None, callback=None, maxls=20)

Minimize a function func using the L-BFGS-B algorithm.

Parameters
funccallable f(x,*args)

Function to minimize.

x0ndarray

Initial guess.

fprimecallable fprime(x,*args), optional

The gradient of func. If None, then func returns the function value and the gradient (f, g = func(x, *args)), unless approx_grad is True in which case func returns only f.

argssequence, optional

Arguments to pass to func and fprime.

approx_gradbool, optional

Whether to approximate the gradient numerically (in which case func returns only the function value).

boundslist, optional

(min, max) pairs for each element in x, defining the bounds on that parameter. Use None or +-inf for one of min or max when there is no bound in that direction.

mint, optional

The maximum number of variable metric corrections used to define the limited memory matrix. (The limited memory BFGS method does not store the full hessian but uses this many terms in an approximation to it.)

factrfloat, optional

The iteration stops when (f^k - f^{k+1})/max{|f^k|,|f^{k+1}|,1} <= factr * eps, where eps is the machine precision, which is automatically generated by the code. Typical values for factr are: 1e12 for low accuracy; 1e7 for moderate accuracy; 10.0 for extremely high accuracy. See Notes for relationship to ftol, which is exposed (instead of factr) by the scipy.optimize.minimize interface to L-BFGS-B.

pgtolfloat, optional

The iteration will stop when max{|proj g_i | i = 1, ..., n} <= pgtol where pg_i is the i-th component of the projected gradient.

epsilonfloat, optional

Step size used when approx_grad is True, for numerically calculating the gradient

iprintint, optional

Controls the frequency of output. iprint < 0 means no output; iprint = 0 print only one line at the last iteration; 0 < iprint < 99 print also f and |proj g| every iprint iterations; iprint = 99 print details of every iteration except n-vectors; iprint = 100 print also the changes of active set and final x; iprint > 100 print details of every iteration including x and g.

dispint, optional

If zero, then no output. If a positive number, then this over-rides iprint (i.e., iprint gets the value of disp).

maxfunint, optional

Maximum number of function evaluations.

maxiterint, optional

Maximum number of iterations.

callbackcallable, optional

Called after each iteration, as callback(xk), where xk is the current parameter vector.

maxlsint, optional

Maximum number of line search steps (per iteration). Default is 20.

Returns
xarray_like

Estimated position of the minimum.

ffloat

Value of func at the minimum.

ddict

Information dictionary.

  • d[‘warnflag’] is

    • 0 if converged,

    • 1 if too many function evaluations or too many iterations,

    • 2 if stopped for another reason, given in d[‘task’]

  • d[‘grad’] is the gradient at the minimum (should be 0 ish)

  • d[‘funcalls’] is the number of function calls made.

  • d[‘nit’] is the number of iterations.

See also

minimize

Interface to minimization algorithms for multivariate functions. See the ‘L-BFGS-B’ method in particular. Note that the ftol option is made available via that interface, while factr is provided via this interface, where factr is the factor multiplying the default machine floating-point precision to arrive at ftol: ftol = factr * numpy.finfo(float).eps.

Notes

License of L-BFGS-B (FORTRAN code):

The version included here (in fortran code) is 3.0 (released April 25, 2011). It was written by Ciyou Zhu, Richard Byrd, and Jorge Nocedal <nocedal@ece.nwu.edu>. It carries the following condition for use:

This software is freely available, but we expect that all publications describing work using this software, or all commercial products using it, quote at least one of the references given below. This software is released under the BSD License.

References

  • R. H. Byrd, P. Lu and J. Nocedal. A Limited Memory Algorithm for Bound Constrained Optimization, (1995), SIAM Journal on Scientific and Statistical Computing, 16, 5, pp. 1190-1208.

  • C. Zhu, R. H. Byrd and J. Nocedal. L-BFGS-B: Algorithm 778: L-BFGS-B, FORTRAN routines for large scale bound constrained optimization (1997), ACM Transactions on Mathematical Software, 23, 4, pp. 550 - 560.

  • J.L. Morales and J. Nocedal. L-BFGS-B: Remark on Algorithm 778: L-BFGS-B, FORTRAN routines for large scale bound constrained optimization (2011), ACM Transactions on Mathematical Software, 38, 1.

generalized_crossvalidation

dipy.reconst.qtdmri.generalized_crossvalidation(data, M, LR, startpoint=0.0005)

Generalized Cross Validation Function [1].

References

1

Craven et al. “Smoothing Noisy Data with Spline Functions.” NUMER MATH 31.4 (1978): 377-403.

genlaguerre

dipy.reconst.qtdmri.genlaguerre(n, alpha, monic=False)

Generalized (associated) Laguerre polynomial.

Defined to be the solution of

\[x\frac{d^2}{dx^2}L_n^{(\alpha)} + (\alpha + 1 - x)\frac{d}{dx}L_n^{(\alpha)} + nL_n^{(\alpha)} = 0,\]

where \(\alpha > -1\); \(L_n^{(\alpha)}\) is a polynomial of degree \(n\).

Parameters
nint

Degree of the polynomial.

alphafloat

Parameter, must be greater than -1.

monicbool, optional

If True, scale the leading coefficient to be 1. Default is False.

Returns
Lorthopoly1d

Generalized Laguerre polynomial.

See also

laguerre

Laguerre polynomial.

Notes

For fixed \(\alpha\), the polynomials \(L_n^{(\alpha)}\) are orthogonal over \([0, \infty)\) with weight function \(e^{-x}x^\alpha\).

The Laguerre polynomials are the special case where \(\alpha = 0\).

gradient_table_from_gradient_strength_bvecs

dipy.reconst.qtdmri.gradient_table_from_gradient_strength_bvecs(gradient_strength, bvecs, big_delta, small_delta, b0_threshold=50, atol=0.01)

A general function for creating diffusion MR gradients.

It reads, loads and prepares scanner parameters like the b-values and b-vectors so that they can be useful during the reconstruction process.

Parameters
gradient_strengthan array of shape (N,),

gradient strength given in T/mm

bvecscan be any of two options
  1. an array of shape (N, 3) or (3, N) with the b-vectors.

  2. a path for the file which contains an array like the previous.

big_deltafloat or array of shape (N,)

acquisition pulse separation time in seconds

small_deltafloat

acquisition pulse duration time in seconds

b0_thresholdfloat

All b-values with values less than or equal to bo_threshold are considered as b0s i.e. without diffusion weighting.

atolfloat

All b-vectors need to be unit vectors up to a tolerance.

Returns
gradientsGradientTable

A GradientTable with all the gradient information.

Notes

  1. Often b0s (b-values which correspond to images without diffusion weighting) have 0 values however in some cases the scanner cannot provide b0s of an exact 0 value and it gives a bit higher values e.g. 6 or 12. This is the purpose of the b0_threshold in the __init__.

  2. We assume that the minimum number of b-values is 7.

  3. B-vectors should be unit vectors.

Examples

>>> from dipy.core.gradients import (
...    gradient_table_from_gradient_strength_bvecs)
>>> gradient_strength = .03e-3 * np.ones(7)  # clinical strength at 30 mT/m
>>> big_delta = .03  # pulse separation of 30ms
>>> small_delta = 0.01  # pulse duration of 10ms
>>> gradient_strength[0] = 0
>>> sq2 = np.sqrt(2) / 2
>>> bvecs = np.array([[0, 0, 0],
...                   [1, 0, 0],
...                   [0, 1, 0],
...                   [0, 0, 1],
...                   [sq2, sq2, 0],
...                   [sq2, 0, sq2],
...                   [0, sq2, sq2]])
>>> gt = gradient_table_from_gradient_strength_bvecs(
...     gradient_strength, bvecs, big_delta, small_delta)

l1_crossvalidation

dipy.reconst.qtdmri.l1_crossvalidation(b0s_mask, E, M, weight_array=array([0., 0.02, 0.04, 0.06, 0.08, 0.1, 0.12, 0.14, 0.16, 0.18, 0.2, 0.22, 0.24, 0.26, 0.28, 0.3, 0.32, 0.34, 0.36, 0.38, 0.4]))

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

multi_voxel_fit

dipy.reconst.qtdmri.multi_voxel_fit(single_voxel_fit)

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

optional_package

dipy.reconst.qtdmri.optional_package(name, trip_msg=None)

Return package-like thing and module setup for package name

Parameters
namestr

package name

trip_msgNone or str

message to give when someone tries to use the return package, but we could not import it, and have returned a TripWire object instead. Default message if None.

Returns
pkg_likemodule or TripWire instance

If we can import the package, return it. Otherwise return an object raising an error when accessed

have_pkgbool

True if import for package was successful, false otherwise

module_setupfunction

callable usually set as setup_module in calling namespace, to allow skipping tests.

Examples

Typical use would be something like this at the top of a module using an optional package:

>>> from dipy.utils.optpkg import optional_package
>>> pkg, have_pkg, setup_module = optional_package('not_a_package')

Of course in this case the package doesn’t exist, and so, in the module:

>>> have_pkg
False

and

>>> pkg.some_function() 
Traceback (most recent call last):
    ...
TripWireError: We need package not_a_package for these functions, but
``import not_a_package`` raised an ImportError

If the module does exist - we get the module

>>> pkg, _, _ = optional_package('os')
>>> hasattr(pkg, 'path')
True

Or a submodule if that’s what we asked for

>>> subpkg, _, _ = optional_package('os.path')
>>> hasattr(subpkg, 'dirname')
True

part1_reg_matrix_tau

dipy.reconst.qtdmri.part1_reg_matrix_tau(ind_mat, ut)

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

References

1

Fick, Rutger HJ, et al. “Non-Parametric GraphNet-Regularized Representation of dMRI in Space and Time”, Medical Image Analysis, 2017.

part23_iso_reg_matrix_q

dipy.reconst.qtdmri.part23_iso_reg_matrix_q(ind_mat, us)

Partial spherical spatial Laplacian regularization matrix following the equation below Eq. (C4) in [1].

References

1

Fick, Rutger HJ, et al. “Non-Parametric GraphNet-Regularized Representation of dMRI in Space and Time”, Medical Image Analysis, 2017.

part23_reg_matrix_q

dipy.reconst.qtdmri.part23_reg_matrix_q(ind_mat, U_mat, T_mat, us)

Partial cartesian spatial Laplacian regularization matrix following second line of Eq. (B2) in [1].

References

1

Fick, Rutger HJ, et al. “Non-Parametric GraphNet-Regularized Representation of dMRI in Space and Time”, Medical Image Analysis, 2017.

part23_reg_matrix_tau

dipy.reconst.qtdmri.part23_reg_matrix_tau(ind_mat, ut)

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

References

1

Fick, Rutger HJ, et al. “Non-Parametric GraphNet-Regularized Representation of dMRI in Space and Time”, Medical Image Analysis, 2017.

part4_iso_reg_matrix_q

dipy.reconst.qtdmri.part4_iso_reg_matrix_q(ind_mat, us)

Partial spherical spatial Laplacian regularization matrix following the equation below Eq. (C4) in [1].

References

1

Fick, Rutger HJ, et al. “Non-Parametric GraphNet-Regularized Representation of dMRI in Space and Time”, Medical Image Analysis, 2017.

part4_reg_matrix_q

dipy.reconst.qtdmri.part4_reg_matrix_q(ind_mat, U_mat, us)

Partial cartesian spatial Laplacian regularization matrix following equation Eq. (B2) in [1].

References

1

Fick, Rutger HJ, et al. “Non-Parametric GraphNet-Regularized Representation of dMRI in Space and Time”, Medical Image Analysis, 2017.

part4_reg_matrix_tau

dipy.reconst.qtdmri.part4_reg_matrix_tau(ind_mat, ut)

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

References

1

Fick, Rutger HJ, et al. “Non-Parametric GraphNet-Regularized Representation of dMRI in Space and Time”, Medical Image Analysis, 2017.

qtdmri_anisotropic_scaling

dipy.reconst.qtdmri.qtdmri_anisotropic_scaling(data, q, bvecs, tau)

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

qtdmri_eap_matrix

dipy.reconst.qtdmri.qtdmri_eap_matrix(radial_order, time_order, us, ut, grid)

Constructs the design matrix as a product of 3 separated radial, angular and temporal design matrices. It precomputes the relevant basis orders for each one and finally puts them together according to the index matrix

qtdmri_eap_matrix_

dipy.reconst.qtdmri.qtdmri_eap_matrix_(radial_order, time_order, us, ut, grid, normalization=False)

qtdmri_index_matrix

dipy.reconst.qtdmri.qtdmri_index_matrix(radial_order, time_order)

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

qtdmri_isotropic_eap_matrix

dipy.reconst.qtdmri.qtdmri_isotropic_eap_matrix(radial_order, time_order, us, ut, grid)

Constructs the design matrix as a product of 3 separated radial, angular and temporal design matrices. It precomputes the relevant basis orders for each one and finally puts them together according to the index matrix

qtdmri_isotropic_eap_matrix_

dipy.reconst.qtdmri.qtdmri_isotropic_eap_matrix_(radial_order, time_order, us, ut, grid, normalization=False)

qtdmri_isotropic_index_matrix

dipy.reconst.qtdmri.qtdmri_isotropic_index_matrix(radial_order, time_order)

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

qtdmri_isotropic_laplacian_reg_matrix

dipy.reconst.qtdmri.qtdmri_isotropic_laplacian_reg_matrix(ind_mat, us, ut, part1_uq_iso_precomp=None, part1_ut_precomp=None, part23_ut_precomp=None, part4_ut_precomp=None, normalization=False)

Computes the spherical qt-dMRI Laplacian regularization matrix. If given, uses precomputed matrices for temporal and spatial regularization matrices to speed up computation. Follows the the formulation of Appendix C in [1].

References

1

Fick, Rutger HJ, et al. “Non-Parametric GraphNet-Regularized Representation of dMRI in Space and Time”, Medical Image Analysis, 2017.

qtdmri_isotropic_scaling

dipy.reconst.qtdmri.qtdmri_isotropic_scaling(data, q, tau)

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

qtdmri_isotropic_signal_matrix

dipy.reconst.qtdmri.qtdmri_isotropic_signal_matrix(radial_order, time_order, us, ut, q, tau)

qtdmri_isotropic_signal_matrix_

dipy.reconst.qtdmri.qtdmri_isotropic_signal_matrix_(radial_order, time_order, us, ut, q, tau, normalization=False)

qtdmri_isotropic_to_mapmri_matrix

dipy.reconst.qtdmri.qtdmri_isotropic_to_mapmri_matrix(radial_order, time_order, ut, tau)

Generates the matrix that maps the spherical qtdmri coefficients to MAP-MRI coefficients. The conversion is done by only evaluating the time basis for a diffusion time tau and summing up coefficients with the same spatial basis orders [1].

Parameters
radial_orderunsigned int,

an even integer representing the spatial/radial order of the basis.

time_orderunsigned int,

an integer larger or equal than zero representing the time order of the basis.

utfloat

temporal scaling factor

taufloat

diffusion time (big_delta - small_delta / 3.) in seconds

References

1

Fick, Rutger HJ, et al. “Non-Parametric GraphNet-Regularized Representation of dMRI in Space and Time”, Medical Image Analysis, 2017.

qtdmri_laplacian_reg_matrix

dipy.reconst.qtdmri.qtdmri_laplacian_reg_matrix(ind_mat, us, ut, S_mat=None, T_mat=None, U_mat=None, part1_ut_precomp=None, part23_ut_precomp=None, part4_ut_precomp=None, normalization=False)

Computes the cartesian qt-dMRI Laplacian regularization matrix. If given, uses precomputed matrices for temporal and spatial regularization matrices to speed up computation. Follows the the formulation of Appendix B in [1].

References

1

Fick, Rutger HJ, et al. “Non-Parametric GraphNet-Regularized Representation of dMRI in Space and Time”, Medical Image Analysis, 2017.

qtdmri_mapmri_isotropic_normalization

dipy.reconst.qtdmri.qtdmri_mapmri_isotropic_normalization(j, l, u0)

Normalization factor for Spherical MAP-MRI basis. The normalization for a basis function with orders [j,l,m] depends only on orders j,l and the isotropic scale factor.

qtdmri_mapmri_normalization

dipy.reconst.qtdmri.qtdmri_mapmri_normalization(mu)

Normalization factor for Cartesian MAP-MRI basis. The scaling is the same for every basis function depending only on the spatial scaling mu.

qtdmri_number_of_coefficients

dipy.reconst.qtdmri.qtdmri_number_of_coefficients(radial_order, time_order)

Computes the total number of coefficients of the qtdmri basis given a radial and temporal order. Equation given below Eq (9) in [1].

References

1

Fick, Rutger HJ, et al. “Non-Parametric GraphNet-Regularized Representation of dMRI in Space and Time”, Medical Image Analysis, 2017.

qtdmri_signal_matrix

dipy.reconst.qtdmri.qtdmri_signal_matrix(radial_order, time_order, us, ut, q, tau)

Constructs the design matrix as a product of 3 separated radial, angular and temporal design matrices. It precomputes the relevant basis orders for each one and finally puts them together according to the index matrix

qtdmri_signal_matrix_

dipy.reconst.qtdmri.qtdmri_signal_matrix_(radial_order, time_order, us, ut, q, tau, normalization=False)

Function to generate the qtdmri signal basis.

qtdmri_temporal_normalization

dipy.reconst.qtdmri.qtdmri_temporal_normalization(ut)

Normalization factor for the temporal basis

qtdmri_to_mapmri_matrix

dipy.reconst.qtdmri.qtdmri_to_mapmri_matrix(radial_order, time_order, ut, tau)

Generates the matrix that maps the qtdmri coefficients to MAP-MRI coefficients. The conversion is done by only evaluating the time basis for a diffusion time tau and summing up coefficients with the same spatial basis orders [1].

Parameters
radial_orderunsigned int,

an even integer representing the spatial/radial order of the basis.

time_orderunsigned int,

an integer larger or equal than zero representing the time order of the basis.

utfloat

temporal scaling factor

taufloat

diffusion time (big_delta - small_delta / 3.) in seconds

References

1

Fick, Rutger HJ, et al. “Non-Parametric GraphNet-Regularized Representation of dMRI in Space and Time”, Medical Image Analysis, 2017.

radial_basis_EAP_opt

dipy.reconst.qtdmri.radial_basis_EAP_opt(j, l, us, r)

radial_basis_opt

dipy.reconst.qtdmri.radial_basis_opt(j, l, us, q)

Spatial basis dependent on spatial scaling factor us

real_sh_descoteaux_from_index

dipy.reconst.qtdmri.real_sh_descoteaux_from_index(m, n, theta, phi, legacy=True)

Compute real spherical harmonics as in Descoteaux et al. 2007 [R6e399bd6d05a-1], where the real harmonic \(Y^m_n\) is defined to be:

Imag(\(Y^m_n\)) * sqrt(2) if m > 0 \(Y^0_n\) if m = 0 Real(\(Y^m_n\)) * sqrt(2) if m < 0

This may take scalar or array arguments. The inputs will be broadcasted against each other.

Parameters
mint |m| <= n

The degree of the harmonic.

nint >= 0

The order of the harmonic.

thetafloat [0, pi]

The polar (colatitudinal) coordinate.

phifloat [0, 2*pi]

The azimuthal (longitudinal) coordinate.

legacy: bool, optional

If true, uses DIPY’s legacy descoteaux07 implementation (where |m| is used for m < 0). Else, implements the basis as defined in Descoteaux et al. 2007 (without the absolute value).

Returns
real_shreal float

The real harmonic \(Y^m_n\) sampled at theta and phi.

temporal_basis

dipy.reconst.qtdmri.temporal_basis(o, ut, tau)

Temporal basis dependent on temporal scaling factor ut

visualise_gradient_table_G_Delta_rainbow

dipy.reconst.qtdmri.visualise_gradient_table_G_Delta_rainbow(gtab, big_delta_start=None, big_delta_end=None, G_start=None, G_end=None, bval_isolines=array([0, 250, 1000, 2500, 5000, 7500, 10000, 14000]), alpha_shading=0.6)

This function visualizes a q-tau acquisition scheme as a function of gradient strength and pulse separation (big_delta). It represents every measurements at its G and big_delta position regardless of b-vector, with a background of b-value isolines for reference. It assumes there is only one unique pulse length (small_delta) in the acquisition scheme.

Parameters
gtabGradientTable object

constructed gradient table with big_delta and small_delta given as inputs.

big_delta_startfloat,

optional minimum big_delta that is plotted in seconds

big_delta_endfloat,

optional maximum big_delta that is plotted in seconds

G_startfloat,

optional minimum gradient strength that is plotted in T/m

G_endfloat,

optional maximum gradient strength taht is plotted in T/m

bval_isolinesarray,

optional array of bvalue isolines that are plotted in the background

alpha_shadingfloat between [0-1]

optional shading of the bvalue colors in the background

warn

dipy.reconst.qtdmri.warn(/, message, category=None, stacklevel=1, source=None)

Issue a warning, or maybe ignore it or raise an exception.

QtiFit

class dipy.reconst.qti.QtiFit(params)

Bases: object

Methods

S0_hat()

Estimated signal without diffusion-weighting.

c_c()

Microscopic orientation coherence.

c_m()

Normalized macroscopic anisotropy.

c_md()

Normalized variance of mean diffusivities.

c_mu()

Normalized microscopic anisotropy.

d_sq()

Diffusion tensor's outer product with itself.

fa()

Fractional anisotropy.

k_bulk()

Bulk kurtosis.

k_mu()

Microscopic kurtosis.

k_shear()

Shear kurtosis.

md()

Mean diffusivity.

mean_d_sq()

Average of microscopic diffusion tensors' outer products with

mk()

Mean kurtosis.

predict(gtab)

Generate signals from this model fit and a given gradient table.

ufa()

Microscopic fractional anisotropy.

v_iso()

Total isotropic variance.

v_md()

Variance of microscopic mean diffusivities.

v_shear()

Shear variance.

__init__(params)

Fitted QTI model.

Parameters
paramsnumpy.ndarray

Array of shape (…, 28) containing the model parameters. Element 0 is the natural logarithm of the signal without diffusion-weighting, elements 1-6 are the diffusion tensor elements in Voigt notation, and elements 7-27 are the covariance tensor elements in Voigt notation.

S0_hat()

Estimated signal without diffusion-weighting.

Returns
S0numpy.ndarray
c_c()

Microscopic orientation coherence.

Returns
c_cnumpy.ndarray

rac{C_ ext{M}}{C_mu}

c_m()

Normalized macroscopic anisotropy.

Returns
c_mnumpy.ndarray

rac{3}{2} rac{langle mathbf{D} angle

otimes langle mathbf{D}

anglemathbb{E}_ ext{shear}}

{langle mathbf{D}

angle otimes langle mathbf{D} angle :

mathbb{E}_ ext{iso}}

c_md()

Normalized variance of mean diffusivities.

Returns
c_mdnumpy.ndarray
rac{mathbb{C}mathbb{E}_ ext{bulk}}

{langle mathbf{D} otimes mathbf{D}

angle :

mathbb{E}_ ext{bulk}}

c_mu()

Normalized microscopic anisotropy.

Returns
c_munumpy.ndarray

rac{3}{2} rac{langle mathbf{D} otimes mathbf{D}

anglemathbb{E}_ ext{shear}}{langle mathbf{D} otimes

mathbf{D}

angle : mathbb{E}_ ext{iso}}

d_sq()

Diffusion tensor’s outer product with itself.

Returns
d_sqnumpy.ndarray
fa()

Fractional anisotropy.

Returns
fanumpy.ndarray

Notes

Fractional anisotropy is calculated as

\[ext{FA} = \sqrt{C_ ext{M}}\]
k_bulk()

Bulk kurtosis.

Returns
k_bulknumpy.ndarray
rac{mathbb{C}mathbb{E}_ ext{bulk}}

{langle mathbf{D}

angle otimes langle mathbf{D} angle :

mathbb{E}_ ext{bulk}}

k_mu()

Microscopic kurtosis.

Returns
k_munumpy.ndarray

rac{6}{5} rac{langle mathbf{D} otimes mathbf{D}

angle : mathbb{E}_ ext{shear}}{langle mathbf{D} angle

otimes langle mathbf{D}

angle : mathbb{E}_ ext{bulk}}

k_shear()

Shear kurtosis.

Returns
k_shearnumpy.ndarray

rac{6}{5} rac{mathbb{C} :

mathbb{E}_ ext{shear}}{langle mathbf{D}

angle otimes

langle mathbf{D}

angle : mathbb{E}_ ext{bulk}}

md()

Mean diffusivity.

Returns
mdnumpy.ndarray

angle : mathbf{E}_ ext{iso}

mean_d_sq()
Average of microscopic diffusion tensors’ outer products with

themselves.

Returns
mean_d_sqnumpy.ndarray
angle = mathbb{C} +

langle mathbf{D}

angle otimes langle mathbf{D} angle

mk()

Mean kurtosis.

Returns
mknumpy.ndarray

Notes

Mean kurtosis is calculated as

\[ext{MK} = K_ ext{bulk} + K_ ext{shear}\]
predict(gtab)

Generate signals from this model fit and a given gradient table.

Parameters
gtabdipy.core.gradients.GradientTable

Gradient table with b-tensors.

Returns
Snumpy.ndarray

Signals.

ufa()

Microscopic fractional anisotropy.

Returns
ufanumpy.ndarray

Notes

Microscopic fractional anisotropy is calculated as

\[\mu ext{FA} = \sqrt{C_\mu}\]
v_iso()

Total isotropic variance.

Returns
v_isonumpy.ndarray

Notes

Total isotropic variance is calculated as

\[V_ ext{iso} = \mathbb{C} : \mathbb{E}_ ext{iso}\]
v_md()

Variance of microscopic mean diffusivities.

Returns
v_mdnumpy.ndarray

Notes

Variance of microscopic mean diffusivities is calculated as

\[V_ ext{MD} = \mathbb{C} : \mathbb{E}_ ext{bulk}\]
v_shear()

Shear variance.

Returns
v_shearnumpy.ndarray

Notes

Shear variance is calculated as

\[V_ ext{shear} = \mathbb{C} : \mathbb{E}_ ext{shear}\]

QtiModel

class dipy.reconst.qti.QtiModel(gtab, fit_method='WLS')

Bases: dipy.reconst.base.ReconstModel

Methods

fit(data[, mask])

Fit QTI to data.

predict(params)

Generate signals from this model class instance and given parameters.

__init__(gtab, fit_method='WLS')

Covariance tensor model of q-space trajectory imaging [1].

Parameters
gtabdipy.core.gradients.GradientTable

Gradient table with b-tensors.

fit_methodstr, optional
Must be one of the followng:
‘OLS’ for ordinary least squares

qti._ols_fit()

‘WLS’ for weighted least squares

qti._wls_fit()

References

1

Westin, Carl-Fredrik, et al. “Q-space trajectory imaging for multidimensional diffusion MRI of the human brain.” Neuroimage 135 (2016): 345-362. https://doi.org/10.1016/j.neuroimage.2016.02.039.

fit(data, mask=None)

Fit QTI to data.

Parameters
datanumpy.ndarray

Array of shape (…, number of acquisitions).

masknumpy.ndarray, optional

Array with the same shape as the data array of a single acquisition.

Returns
qtifitdipy.reconst.qti.QtiFit

The fitted model.

predict(params)

Generate signals from this model class instance and given parameters.

Parameters
paramsnumpy.ndarray

Array of shape (…, 28) containing the model parameters. Element 0 is the natural logarithm of the signal without diffusion-weighting, elements 1-6 are the diffusion tensor elements in Voigt notation, and elements 7-27 are the covariance tensor elements in Voigt notation.

Returns
Snumpy.ndarray

Signals.

ReconstModel

class dipy.reconst.qti.ReconstModel(gtab)

Bases: object

Abstract class for signal reconstruction models

Methods

fit

__init__(gtab)

Initialization of the abstract class for signal reconstruction models

Parameters
gtabGradientTable class instance
fit(data, mask=None, **kwargs)

auto_attr

dipy.reconst.qti.auto_attr(func)

Decorator to create OneTimeProperty attributes.

Parameters
funcmethod

The method that will be called the first time to compute a value. Afterwards, the method’s name will be a standard attribute holding the value of this computation.

Examples

>>> class MagicProp(object):
...     @auto_attr
...     def a(self):
...         return 99
...
>>> x = MagicProp()
>>> 'a' in x.__dict__
False
>>> x.a
99
>>> 'a' in x.__dict__
True

design_matrix

dipy.reconst.qti.design_matrix(btens)

Calculate the design matrix from the b-tensors.

Parameters
btensnumpy.ndarray

An array of b-tensors of shape (number of acquisitions, 3, 3).

Returns
Xnumpy.ndarray

Design matrix.

rac{1}{2}(mathbf{b}_1

otimesmathbf{b}_1)^T

dots & dots & dots 1 &

-mathbf{b}_n^T &

rac{1}{2}(mathbf{b}_notimesmathbf{b}_n)^T

end{pmatrix}

dtd_covariance

dipy.reconst.qti.dtd_covariance(DTD)

Calculate covariance of a diffusion tensor distribution (DTD).

Parameters
DTDnumpy.ndarray

Diffusion tensor distribution of shape (number of tensors, 3, 3) or (number of tensors, 6, 1).

Returns
Cnumpy.ndarray

Covariance tensor of shape (6, 6).

angle -

langle mathbf{D}

angle otimes langle mathbf{D} angle

from_21x1_to_6x6

dipy.reconst.qti.from_21x1_to_6x6(V)

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

Parameters
Vnumpy.ndarray

An array of size (…, 21, 1).

Returns
Tnumpy.ndarray

Converted matrices of size (…, 6, 6).

Notes

The conversion of a matrix into a vector is defined as

\[egin{matrix} \mathbf{V} = & ig[ T_{11} & T_{22} & T_{33} \ & \sqrt{2} T_{23} & \sqrt{2} T_{13} & \sqrt{2} T_{12} \ & \sqrt{2} T_{14} & \sqrt{2} T_{15} & \sqrt{2} T_{16} \ & \sqrt{2} T_{24} & \sqrt{2} T_{25} & \sqrt{2} T_{26} \ & \sqrt{2} T_{34} & \sqrt{2} T_{35} & \sqrt{2} T_{36} \ & T_{44} & T_{55} & T_{66} \ & \sqrt{2} T_{45} & \sqrt{2} T_{56} & \sqrt{2} T_{46} ig]^T \end{matrix}\]

from_3x3_to_6x1

dipy.reconst.qti.from_3x3_to_6x1(T)

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

Parameters
Tnumpy.ndarray

An array of size (…, 3, 3).

Returns
Vnumpy.ndarray

Converted vectors of size (…, 6, 1).

Notes

The conversion of a matrix into a vector is defined as

\[\mathbf{V} = egin{bmatrix} T_{11} & T_{22} & T_{33} & \sqrt{2} T_{23} & \sqrt{2} T_{13} & \sqrt{2} T_{12} \end{bmatrix}^T\]

from_6x1_to_3x3

dipy.reconst.qti.from_6x1_to_3x3(V)

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

Parameters
Vnumpy.ndarray

An array of size (…, 6, 1).

Returns
Tnumpy.ndarray

Converted matrices of size (…, 3, 3).

Notes

The conversion of a matrix into a vector is defined as

\[\mathbf{V} = egin{bmatrix} T_{11} & T_{22} & T_{33} & \sqrt{2} T_{23} & \sqrt{2} T_{13} & \sqrt{2} T_{12} \end{bmatrix}^T\]

from_6x6_to_21x1

dipy.reconst.qti.from_6x6_to_21x1(T)

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

Parameters
Tnumpy.ndarray

An array of size (…, 6, 6).

Returns
Vnumpy.ndarray

Converted vectors of size (…, 21, 1).

Notes

The conversion of a matrix into a vector is defined as

\[egin{matrix} \mathbf{V} = & ig[ T_{11} & T_{22} & T_{33} \ & \sqrt{2} T_{23} & \sqrt{2} T_{13} & \sqrt{2} T_{12} \ & \sqrt{2} T_{14} & \sqrt{2} T_{15} & \sqrt{2} T_{16} \ & \sqrt{2} T_{24} & \sqrt{2} T_{25} & \sqrt{2} T_{26} \ & \sqrt{2} T_{34} & \sqrt{2} T_{35} & \sqrt{2} T_{36} \ & T_{44} & T_{55} & T_{66} \ & \sqrt{2} T_{45} & \sqrt{2} T_{56} & \sqrt{2} T_{46} ig]^T \end{matrix}\]

ndindex

dipy.reconst.qti.ndindex(shape)

An N-dimensional iterator object to index arrays.

Given the shape of an array, an ndindex instance iterates over the N-dimensional index of the array. At each iteration a tuple of indices is returned; the last dimension is iterated over first.

Parameters
shapetuple of ints

The dimensions of the array.

Examples

>>> from dipy.core.ndindex import ndindex
>>> shape = (3, 2, 1)
>>> for index in ndindex(shape):
...     print(index)
(0, 0, 0)
(0, 1, 0)
(1, 0, 0)
(1, 1, 0)
(2, 0, 0)
(2, 1, 0)

qti_signal

dipy.reconst.qti.qti_signal(gtab, D, C, S0=1)

Generate signals using the covariance tensor signal representation.

Parameters
gtabdipy.core.gradients.GradientTable

Gradient table with b-tensors.

Dnumpy.ndarray

Diffusion tensors of shape (…, 3, 3), (…, 6, 1), or (…, 6).

Cnumpy.ndarray

Covariance tensors of shape (…, 6, 6), (…, 21, 1), or (…, 21).

S0numpy.ndarray, optional

Signal magnitudes without diffusion-weighting. Must be a single number or an array of same shape as D and C without the last two dimensions.

Returns
Snumpy.ndarray

Simulated signals.

angle

rac{1}{2}(mathbf{b} otimes mathbf{b}) : mathbb{C} ight)

warn

dipy.reconst.qti.warn(/, message, category=None, stacklevel=1, source=None)

Issue a warning, or maybe ignore it or raise an exception.

quick_squash

dipy.reconst.quick_squash.quick_squash()

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. obj_arr is an array of scalars of type T. Returns an array like obj_arr.astype(T)

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

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

  4. Items in obj_arr are not ndarrays or scalars. Returns obj_arr.

Parameters
obj_arrarray, dtype=object

The array to be converted.

maskarray, dtype=bool, optional

mask is nonzero where obj_arr has Nones.

fillnumber, optional

Nones are replaced by fill.

Returns
resultarray

Examples

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

reduce

dipy.reconst.quick_squash.reduce(function, sequence[, initial]) value

Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). If initial is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty.

adj_to_countarrs

dipy.reconst.recspeed.adj_to_countarrs()

Convert adjacency sequence to counts and flattened indices

We use this to provide expected input to argmax_from_countarrs

Parameters
adj_indicessequence

length V sequence of sequences, where sequence i contains the neighbors of a particular vertex.

Returns
counts(V,) array

Number of neighbors for each vertex

adj_inds(n,) array

flat array containing adj_indices unrolled as a vector

argmax_from_adj

dipy.reconst.recspeed.argmax_from_adj()

Indices of local maxima from vals given adjacent points

Parameters
vals(N,) array, dtype np.float64

values at all vertices referred to in either of vertex_inds or adj_inds

vertex_inds(V,) array

indices into vals giving vertices that may be local maxima.

adj_indssequence

For every vertex in vertex_inds, the indices (into vals) of the neighboring points

Returns
inds(M,) array

Indices into vals giving local maxima of vals, given topology from adj_inds, and restrictions from vertex_inds. Inds are returned sorted by value at that index - i.e. smallest value (at index) first.

argmax_from_countarrs

dipy.reconst.recspeed.argmax_from_countarrs()

Indices of local maxima from vals from count, array neighbors

Parameters
vals(N,) array, dtype float

values at all vertices referred to in either of vertex_inds or adj_inds

vertinds(V,) array, dtype uint32

indices into vals giving vertices that may be local maxima.

adj_counts(V,) array, dtype uint32

For every vertex i in vertex_inds, the number of neighbors for vertex i

adj_inds(P,) array, dtype uint32

Indices for neighbors for each point. P=sum(adj_counts)

Returns
inds(M,) array

Indices into vals giving local maxima of vals, given topology from adj_counts and adj_inds, and restrictions from vertex_inds. Inds are returned sorted by value at that index - i.e. smallest value (at index) first.

le_to_odf

dipy.reconst.recspeed.le_to_odf()

odf for interpolated Laplacian normalized signal

local_maxima

dipy.reconst.recspeed.local_maxima()

Local maxima of a function evaluated on a discrete set of points.

If a function is evaluated on some set of points where each pair of neighboring points is an edge in edges, find the local maxima.

Parameters
odfarray, 1d, dtype=double

The function evaluated on a set of discrete points.

edgesarray (N, 2)

The set of neighbor relations between the points. Every edge, ie edges[i, :], is a pair of neighboring points.

Returns
peak_valuesndarray

Value of odf at a maximum point. Peak values is sorted in descending order.

peak_indicesndarray

Indices of maximum points. Sorted in the same order as peak_values so odf[peak_indices[i]] == peak_values[i].

See also

dipy.core.sphere

Notes

A point is a local maximum if it is > at least one neighbor and >= all neighbors. If no points meet the above criteria, 1 maximum is returned such that odf[maximum] == max(odf).

proc_reco_args

dipy.reconst.recspeed.proc_reco_args()

remove_similar_vertices

dipy.reconst.recspeed.remove_similar_vertices(vertices, theta, return_mapping=False, return_index=False)

Remove vertices that are less than theta degrees from any other

Returns vertices that are at least theta degrees from any other vertex. Vertex v and -v are considered the same so if v and -v are both in vertices only one is kept. Also if v and w are both in vertices, w must be separated by theta degrees from both v and -v to be unique.

Parameters
vertices(N, 3) ndarray

N unit vectors.

thetafloat

The minimum separation between vertices in degrees.

return_mapping{False, True}, optional

If True, return mapping as well as vertices and maybe indices (see below).

return_indices{False, True}, optional

If True, return indices as well as vertices and maybe mapping (see below).

Returns
unique_vertices(M, 3) ndarray

Vertices sufficiently separated from one another.

mapping(N,) ndarray

For each element vertices[i] (\(i \in 0..N-1\)), the index \(j\) to a vertex in unique_vertices that is less than theta degrees from vertices[i]. Only returned if return_mapping is True.

indices(N,) ndarray

indices gives the reverse of mapping. For each element unique_vertices[j] (\(j \in 0..M-1\)), the index \(i\) to a vertex in vertices that is less than theta degrees from unique_vertices[j]. If there is more than one element of vertices that is less than theta degrees from unique_vertices[j], return the first (lowest index) matching value. Only return if return_indices is True.

search_descending

dipy.reconst.recspeed.search_descending(a, relative_threshold)

i in descending array a so a[i] < a[0] * relative_threshold

Call T = a[0] * relative_threshold. Return value i will be the smallest index in the descending array a such that a[i] < T. Equivalently, i will be the largest index such that all(a[:i] >= T). If all values in a are >= T, return the length of array a.

Parameters
andarray, ndim=1, c-contiguous

Array to be searched. We assume a is in descending order.

relative_thresholdfloat

Applied threshold will be T with T = a[0] * relative_threshold.

Returns
inp.intp

If T = a[0] * relative_threshold then i will be the largest index such that all(a[:i] >= T). If all values in a are >= T then i will be len(a).

Examples

>>> a = np.arange(10, 0, -1, dtype=float)
>>> a
array([ 10.,   9.,   8.,   7.,   6.,   5.,   4.,   3.,   2.,   1.])
>>> search_descending(a, 0.5)
6
>>> a < 10 * 0.5
array([False, False, False, False, False, False,  True,  True,  True,  True], dtype=bool)
>>> search_descending(a, 1)
1
>>> search_descending(a, 2)
0
>>> search_descending(a, 0)
10

sum_on_blocks_1d

dipy.reconst.recspeed.sum_on_blocks_1d()

Summations on blocks of 1d array

AxSymShResponse

class dipy.reconst.rumba.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.

Methods

basis(sphere)

A basis that maps the response coefficients onto a sphere.

on_sphere(sphere)

Evaluates the response function on sphere.

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

OdfFit

class dipy.reconst.rumba.OdfFit(model, data)

Bases: dipy.reconst.base.ReconstFit

Methods

odf(sphere)

To be implemented but specific odf models

__init__(model, data)
odf(sphere)

To be implemented but specific odf models

OdfModel

class dipy.reconst.rumba.OdfModel(gtab)

Bases: dipy.reconst.base.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.

Methods

fit(data)

To be implemented by specific odf models

__init__(gtab)

Initialization of the abstract class for signal reconstruction models

Parameters
gtabGradientTable class instance
fit(data)

To be implemented by specific odf models

RumbaFit

class dipy.reconst.rumba.RumbaFit(model, model_params)

Bases: dipy.reconst.odf.OdfFit

Methods

combined_odf_iso()

Constructs fODF combined with isotropic volume fraction at discrete vertices on model sphere.

f_csf()

Constructs CSF volume fraction for each voxel.

f_gm()

Constructs GM volume fraction for each voxel.

f_iso()

Constructs isotropic volume fraction for each voxel.

f_wm()

Constructs white matter volume fraction for each voxel.

odf([sphere])

Constructs fODF at discrete vertices on model sphere for each voxel.

predict([gtab, S0])

Compute signal prediction on model gradient table given given fODF and GM/CSF volume fractions for each voxel.

__init__(model, model_params)

Constructs fODF, GM/CSF volume fractions, and other dereived results.

fODF and GM/CSF fractions are normalized to collectively sum to 1 for each voxel.

Parameters
modelRumbaSDModel

RumbaSDModel-SD model.

model_paramsndarray ([x, y, z], M)

fODF and GM/CSF volume fractions for each voxel.

datandarray ([x, y, z], N)

Signal values for each voxel.

combined_odf_iso()

Constructs fODF combined with isotropic volume fraction at discrete vertices on model sphere.

Distributes isotropic compartments evenly along each fODF direction. Sums to 1.

Returns
combinedndarray ([x, y, z], M-2)

fODF combined with isotropic volume fraction.

f_csf()

Constructs CSF volume fraction for each voxel.

Returns
f_csfndarray ([x, y, z])

CSF volume fraction.

f_gm()

Constructs GM volume fraction for each voxel.

Returns
f_gmndarray ([x, y, z])

GM volume fraction.

f_iso()

Constructs isotropic volume fraction for each voxel.

Equivalent to sum of GM and CSF volume fractions.

Returns
f_isondarray ([x, y, z])

Isotropic volume fraction.

f_wm()

Constructs white matter volume fraction for each voxel.

Equivalent to sum of fODF.

Returns
f_wmndarray ([x, y, z])

White matter volume fraction.

odf(sphere=None)

Constructs fODF at discrete vertices on model sphere for each voxel.

Parameters
sphereSphere, optional

Sphere on which to construct fODF. If specified, must be the same sphere used by the RumbaSDModel model. Default: None.

Returns
odfndarray ([x, y, z], M-2)

fODF computed at each vertex on model sphere.

predict(gtab=None, S0=None)

Compute signal prediction on model gradient table given given fODF and GM/CSF volume fractions for each voxel.

Parameters
gtabGradientTable, optional

The gradients for which the signal will be predicted. Use the model’s gradient table if None. Default: None

S0ndarray ([x, y, z]) or float, optional

The non diffusion-weighted signal value for each voxel. If a float, the same value is used for each voxel. If None, 1 is used for each voxel. Default: None

Returns
pred_signdarray ([x, y, z], N)

The predicted signal.

RumbaSDModel

class dipy.reconst.rumba.RumbaSDModel(gtab, wm_response=array([0.0017, 0.0002, 0.0002]), gm_response=0.0008, csf_response=0.003, n_iter=600, recon_type='smf', n_coils=1, R=1, voxelwise=True, use_tv=False, sphere=None, verbose=False)

Bases: dipy.reconst.odf.OdfModel

Methods

fit(data)

To be implemented by specific odf models

__init__(gtab, wm_response=array([0.0017, 0.0002, 0.0002]), gm_response=0.0008, csf_response=0.003, n_iter=600, recon_type='smf', n_coils=1, R=1, voxelwise=True, use_tv=False, sphere=None, verbose=False)

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

Modification of the Richardson-Lucy algorithm accounting for Rician and Noncentral Chi noise distributions, which more accurately represent MRI noise. Computes a maximum likelihood estimation of the fiber orientation density function (fODF) at each voxel. Includes white matter compartments alongside optional GM and CSF compartments to account for partial volume effects. This fit can be performed voxelwise or globally. The global fit will proceed more quickly than the voxelwise fit provided that the computer has adequate RAM (>= 16 GB should be sufficient for most datasets).

Kernel for deconvolution constructed using a priori knowledge of white matter response function, as well as the mean diffusivity of GM and/or CSF. RUMBA-SD is robust against impulse response imprecision, and thus the default diffusivity values are often adequate [2].

Parameters
gtabGradientTable
wm_response1d ndarray or 2d ndarray or AxSymShResponse, optional

Tensor eigenvalues as a (3,) ndarray, multishell eigenvalues as a (len(unique_bvals_tolerance(gtab.bvals))-1, 3) ndarray in order of smallest to largest b-value, or an AxSymShResponse. Default: np.array([1.7e-3, 0.2e-3, 0.2e-3])

gm_responsefloat, optional

Mean diffusivity for GM compartment. If None, then grey matter volume fraction is not computed. Default: 0.8e-3

csf_responsefloat, optional

Mean diffusivity for CSF compartment. If None, then CSF volume fraction is not computed. Default: 3.0e-3

n_iterint, optional

Number of iterations for fODF estimation. Must be a positive int. Default: 600

recon_type{‘smf’, ‘sos’}, optional

MRI reconstruction method: spatial matched filter (SMF) or sum-of-squares (SoS). SMF reconstruction generates Rician noise while SoS reconstruction generates Noncentral Chi noise. Default: ‘smf’

n_coilsint, optional

Number of coils in MRI scanner – only relevant in SoS reconstruction. Must be a positive int. Default: 1

Rint, optional

Acceleration factor of the acquisition. For SIEMENS, R = iPAT factor. For GE, R = ASSET factor. For PHILIPS, R = SENSE factor. Typical values are 1 or 2. Must be a positive int. Default: 1

voxelwisebool, optional

If true, performs a voxelwise fit. If false, performs a global fit on the entire brain at once. The global fit requires a 4D brain volume in fit. Default: True

use_tvbool, optional

If true, applies total variation regularization. This only takes effect in a global fit (voxelwise is set to False). TV can only be applied to 4D brain volumes with no singleton dimensions. Default: False

sphereSphere, optional

Sphere on which to construct fODF. If None, uses repulsion724. Default: None

verbosebool, optional

If true, logs updates on estimated signal-to-noise ratio after each iteration. This only takes effect in a global fit (voxelwise is set to False). Default: False

References

1

Canales-Rodríguez, E. J., Daducci, A., Sotiropoulos, S. N., Caruyer, E., Aja-Fernández, S., Radua, J., Mendizabal, J. M. Y., Iturria-Medina, Y., Melie-García, L., Alemán-Gómez, Y., Thiran, J.-P., Sarró, S., Pomarol-Clotet, E., & Salvador, R. (2015). Spherical Deconvolution of Multichannel Diffusion MRI Data with Non-Gaussian Noise Models and Spatial Regularization. PLOS ONE, 10(10), e0138910. https://doi.org/10.1371/journal.pone.0138910

2

Dell’Acqua, F., Rizzo, G., Scifo, P., Clarke, R., Scotti, G., & Fazio, F. (2007). A Model-Based Deconvolution Approach to Solve Fiber Crossing in Diffusion-Weighted MR Imaging. IEEE Transactions on Bio-Medical Engineering, 54, 462–472. https://doi.org/10.1109/TBME.2006.888830

Sphere

class dipy.reconst.rumba.Sphere(x=None, y=None, z=None, theta=None, phi=None, xyz=None, faces=None, edges=None)

Bases: object

Points on the unit sphere.

The sphere can be constructed using one of three conventions:

Sphere(x, y, z)
Sphere(xyz=xyz)
Sphere(theta=theta, phi=phi)
Parameters
x, y, z1-D array_like

Vertices as x-y-z coordinates.

theta, phi1-D array_like

Vertices as spherical coordinates. Theta and phi are the inclination and azimuth angles respectively.

xyz(N, 3) ndarray

Vertices as x-y-z coordinates.

faces(N, 3) ndarray

Indices into vertices that form triangular faces. If unspecified, the faces are computed using a Delaunay triangulation.

edges(N, 2) ndarray

Edges between vertices. If unspecified, the edges are derived from the faces.

Attributes
x
y
z

Methods

find_closest(xyz)

Find the index of the vertex in the Sphere closest to the input vector

subdivide([n])

Subdivides each face of the sphere into four new faces.

edges

faces

vertices

__init__(x=None, y=None, z=None, theta=None, phi=None, xyz=None, faces=None, edges=None)
edges()
faces()
find_closest(xyz)

Find the index of the vertex in the Sphere closest to the input vector

Parameters
xyzarray-like, 3 elements

A unit vector

Returns
idxint

The index into the Sphere.vertices array that gives the closest vertex (in angle).

subdivide(n=1)

Subdivides each face of the sphere into four new faces.

New vertices are created at a, b, and c. Then each face [x, y, z] is divided into faces [x, a, c], [y, a, b], [z, b, c], and [a, b, c].

      y
      /\
     /  \
   a/____\b
   /\    /\
  /  \  /  \
 /____\/____\
x      c     z
Parameters
nint, optional

The number of subdivisions to preform.

Returns
new_sphereSphere

The subdivided sphere.

vertices()
property x
property y
property z

all_tensor_evecs

dipy.reconst.rumba.all_tensor_evecs(e0)

Given the principle tensor axis, return the array of all eigenvectors column-wise (or, the rotation matrix that orientates the tensor).

Parameters
e0(3,) ndarray

Principle tensor axis.

Returns
evecs(3,3) ndarray

Tensor eigenvectors, arranged column-wise.

auto_attr

dipy.reconst.rumba.auto_attr(func)

Decorator to create OneTimeProperty attributes.

Parameters
funcmethod

The method that will be called the first time to compute a value. Afterwards, the method’s name will be a standard attribute holding the value of this computation.

Examples

>>> class MagicProp(object):
...     @auto_attr
...     def a(self):
...         return 99
...
>>> x = MagicProp()
>>> 'a' in x.__dict__
False
>>> x.a
99
>>> 'a' in x.__dict__
True

bounding_box

dipy.reconst.rumba.bounding_box(vol)

Compute the bounding box of nonzero intensity voxels in the volume.

Parameters
volndarray

Volume to compute bounding box on.

Returns
npminslist

Array containg minimum index of each dimension

npmaxslist

Array containg maximum index of each dimension

crop

dipy.reconst.rumba.crop(vol, mins, maxs)

Crops the input volume.

Parameters
volndarray

Volume to crop.

minsarray

Array containg minimum index of each dimension.

maxsarray

Array containg maximum index of each dimension.

Returns
volndarray

The cropped volume.

generate_kernel

dipy.reconst.rumba.generate_kernel(gtab, sphere, wm_response, gm_response, csf_response)

Generate deconvolution kernel

Compute kernel mapping orientation densities of white matter fiber populations (along each vertex of the sphere) and isotropic volume fractions to a diffusion weighted signal.

Parameters
gtabGradientTable
sphereSphere

Sphere with which to sample discrete fiber orientations in order to construct kernel

wm_response1d ndarray or 2d ndarray or AxSymShResponse, optional

Tensor eigenvalues as a (3,) ndarray, multishell eigenvalues as a (len(unique_bvals_tolerance(gtab.bvals))-1, 3) ndarray in order of smallest to largest b-value, or an AxSymShResponse.

gm_responsefloat, optional

Mean diffusivity for GM compartment. If None, then grey matter compartment set to all zeros.

csf_responsefloat, optional

Mean diffusivity for CSF compartment. If None, then CSF compartment set to all zeros.

Returns
kernel2d ndarray (N, M)

Computed kernel; can be multiplied with a vector consisting of volume fractions for each of M-2 fiber populations as well as GM and CSF fractions to produce a diffusion weighted signal.

get_bval_indices

dipy.reconst.rumba.get_bval_indices(bvals, bval, tol=20)

Get indices where the b-value is bval

Parameters
bvals: ndarray

Array containing the b-values

bval: float or int

b-value to extract indices

tol: int

The tolerated gap between the b-values to extract and the actual b-values.

Returns
Array of indices where the b-value is bval

get_sphere

dipy.reconst.rumba.get_sphere(name='symmetric362')

provide triangulated spheres

Parameters
namestr

which sphere - one of: * ‘symmetric362’ * ‘symmetric642’ * ‘symmetric724’ * ‘repulsion724’ * ‘repulsion100’ * ‘repulsion200’

Returns
spherea dipy.core.sphere.Sphere class instance

Examples

>>> import numpy as np
>>> from dipy.data import get_sphere
>>> sphere = get_sphere('symmetric362')
>>> verts, faces = sphere.vertices, sphere.faces
>>> verts.shape == (362, 3)
True
>>> faces.shape == (720, 3)
True
>>> verts, faces = get_sphere('not a sphere name') 
Traceback (most recent call last):
    ...
DataError: No sphere called "not a sphere name"

gradient_table

dipy.reconst.rumba.gradient_table(bvals, bvecs=None, big_delta=None, small_delta=None, b0_threshold=50, atol=0.01, btens=None)

A general function for creating diffusion MR gradients.

It reads, loads and prepares scanner parameters like the b-values and b-vectors so that they can be useful during the reconstruction process.

Parameters
bvalscan be any of the four options
  1. an array of shape (N,) or (1, N) or (N, 1) with the b-values.

  2. a path for the file which contains an array like the above (1).

  3. an array of shape (N, 4) or (4, N). Then this parameter is considered to be a b-table which contains both bvals and bvecs. In this case the next parameter is skipped.

  4. a path for the file which contains an array like the one at (3).

bvecscan be any of two options
  1. an array of shape (N, 3) or (3, N) with the b-vectors.

  2. a path for the file which contains an array like the previous.

big_deltafloat

acquisition pulse separation time in seconds (default None)

small_deltafloat

acquisition pulse duration time in seconds (default None)

b0_thresholdfloat

All b-values with values less than or equal to bo_threshold are considered as b0s i.e. without diffusion weighting.

atolfloat

All b-vectors need to be unit vectors up to a tolerance.

btenscan be any of three options
  1. a string specifying the shape of the encoding tensor for all volumes in data. Options: ‘LTE’, ‘PTE’, ‘STE’, ‘CTE’ corresponding to linear, planar, spherical, and “cigar-shaped” tensor encoding. Tensors are rotated so that linear and cigar tensors are aligned with the corresponding gradient direction and the planar tensor’s normal is aligned with the corresponding gradient direction. Magnitude is scaled to match the b-value.

  2. an array of strings of shape (N,), (N, 1), or (1, N) specifying encoding tensor shape for each volume separately. N corresponds to the number volumes in data. Options for elements in array: ‘LTE’, ‘PTE’, ‘STE’, ‘CTE’ corresponding to linear, planar, spherical, and “cigar-shaped” tensor encoding. Tensors are rotated so that linear and cigar tensors are aligned with the corresponding gradient direction and the planar tensor’s normal is aligned with the corresponding gradient direction. Magnitude is scaled to match the b-value.

  3. an array of shape (N,3,3) specifying the b-tensor of each volume exactly. N corresponds to the number volumes in data. No rotation or scaling is performed.

Returns
gradientsGradientTable

A GradientTable with all the gradient information.

Notes

  1. Often b0s (b-values which correspond to images without diffusion weighting) have 0 values however in some cases the scanner cannot provide b0s of an exact 0 value and it gives a bit higher values e.g. 6 or 12. This is the purpose of the b0_threshold in the __init__.

  2. We assume that the minimum number of b-values is 7.

  3. B-vectors should be unit vectors.

Examples

>>> from dipy.core.gradients import gradient_table
>>> bvals = 1500 * np.ones(7)
>>> bvals[0] = 0
>>> sq2 = np.sqrt(2) / 2
>>> bvecs = np.array([[0, 0, 0],
...                   [1, 0, 0],
...                   [0, 1, 0],
...                   [0, 0, 1],
...                   [sq2, sq2, 0],
...                   [sq2, 0, sq2],
...                   [0, sq2, sq2]])
>>> gt = gradient_table(bvals, bvecs)
>>> gt.bvecs.shape == bvecs.shape
True
>>> gt = gradient_table(bvals, bvecs.T)
>>> gt.bvecs.shape == bvecs.T.shape
False

lazy_index

dipy.reconst.rumba.lazy_index(index)

Produces a lazy index

Returns a slice that can be used for indexing an array, if no slice can be made index is returned as is.

mbessel_ratio

dipy.reconst.rumba.mbessel_ratio(n, x)

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

Computes:

\(I_{n}(x) / I_{n-1}(x)\)

using Perron’s continued fraction equation where \(I_n\) is the modified Bessel function of first kind, order \(n\) [1].

Parameters
nint

Order of Bessel function in numerator (denominator is of order n-1). Must be a positive int.

xfloat or ndarray

Value or array of values with which to compute ratio.

Returns
yfloat or ndarray

Result of ratio computation.

References

1

W. Gautschi and J. Slavik, “On the computation of modified Bessel function ratios,” Math. Comp., vol. 32, no. 143, pp. 865–875, 1978, doi: 10.1090/S0025-5718-1978-0470267-9

normalize_data

dipy.reconst.rumba.normalize_data(data, where_b0, min_signal=1e-05, out=None)

Normalizes the data with respect to the mean b0

rumba_deconv

dipy.reconst.rumba.rumba_deconv(data, kernel, n_iter=600, recon_type='smf', n_coils=1)

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

Deconvolves the kernel from the diffusion-weighted signal by computing a maximum likelihood estimation of the fODF. Minimizes the negative log-likelihood of the data under Rician or Noncentral Chi noise distributions by adapting the iterative technique developed in Richardson-Lucy deconvolution.

Parameters
data1d ndarray (N,)

Signal values for a single voxel.

kernel2d ndarray (N, M)

Deconvolution kernel mapping volume fractions of the M compartments to N-length signal. Last two columns should be for GM and CSF.

n_iterint, optional

Number of iterations for fODF estimation. Must be a positive int. Default: 600

recon_type{‘smf’, ‘sos’}, optional

MRI reconstruction method: spatial matched filter (SMF) or sum-of-squares (SoS). SMF reconstruction generates Rician noise while SoS reconstruction generates Noncentral Chi noise. Default: ‘smf’

n_coilsint, optional

Number of coils in MRI scanner – only relevant in SoS reconstruction. Must be a positive int. Default: 1

Returns
fit_vec1d ndarray (M,)

Vector containing fODF and GM/CSF volume fractions. First M-2 components are fODF while last two are GM and CSF respectively.

Notes

The diffusion MRI signal measured at a given voxel is a sum of contributions from each intra-voxel compartment, including parallel white matter (WM) fiber populations in a given orientation as well as effects from GM and CSF. The equation governing these contributions is:

\(S_i = S_0\left(\sum_{j=1}^{M}f_j\exp(-b_i\textbf{v}_i^T\textbf{D}_j \textbf{v}_i) + f_{GM}\exp(-b_iD_{GM})+f_{CSF}\exp(-b_iD_{CSF})\right)\)

Where \(S_i\) is the resultant signal along the diffusion-sensitizing gradient unit vector \(\textbf{v_i}; i = 1, ..., N\) with a b-value of \(b_i\). \(f_j; j = 1, ..., M\) is the volume fraction of the \(j^{th}\) fiber population with an anisotropic diffusion tensor \(\textbf{D_j}\).

\(f_{GM}\) and \(f_{CSF}\) are the volume fractions and \(D_{GM}\) and \(D_{CSF}\) are the mean diffusivities of GM and CSF respectively.

This equation is linear in \(f_j, f_{GM}, f_{CSF}\) and can be simplified to a single matrix multiplication:

\(\textbf{S} = \textbf{Hf}\)

Where \(\textbf{S}\) is the signal vector at a certain voxel, \(\textbf{H}\) is the deconvolution kernel, and \(\textbf{f}\) is the vector of volume fractions for each compartment.

Modern MRI scanners produce noise following a Rician or Noncentral Chi distribution, depending on their signal reconstruction technique [2]. Using this linear model, it can be shown that the likelihood of a signal under a Noncentral Chi noise model is:

\(P(\textbf{S}|\textbf{H}, \textbf{f}, \sigma^2, n) = \prod_{i=1}^{N}\left( \frac{S_i}{\bar{S_i}}\right)^n\exp\left\{-\frac{1}{2\sigma^2}\left[ S_i^2 + \bar{S}_i^2\right]\right\}I_{n-1}\left(\frac{S_i\bar{S}_i} {\sigma^2}\right)u(S_i)\)

Where \(S_i\) and \(\bar{S}_i = \textbf{Hf}\) are the measured and expected signals respectively, and \(n\) is the number of coils in the scanner, and \(I_{n-1}\) is the modified Bessel function of first kind of order \(n-1\). This gives the likelihood under a Rician distribution when \(n\) is set to 1.

By taking the negative log of this with respect to \(\textbf{f}\) and setting the derivative to 0, the \(\textbf{f}\) maxmizing likelihood is found to be:

\(\textbf{f} = \textbf{f} \circ \frac{\textbf{H}^T\left[\textbf{S}\circ \frac{I_n(\textbf{S}\circ \textbf{Hf}/\sigma^2)} {I_{n-1}(\textbf{S} \circ\textbf{Hf}\sigma^2)} \right ]} {\textbf{H}^T\textbf{Hf}}\)

The solution can be found using an iterative scheme, just as in the Richardson-Lucy algorithm:

\(\textbf{f}^{k+1} = \textbf{f}^k \circ \frac{\textbf{H}^T\left[\textbf{S} \circ\frac{I_n(\textbf{S}\circ\textbf{Hf}^k/\sigma^2)} {I_{n-1}(\textbf{S} \circ\textbf{Hf}^k/\sigma^2)} \right ]} {\textbf{H}^T\textbf{Hf}^k}\)

In order to apply this, a reasonable estimate of \(\sigma^2\) is required. To find this, a separate iterative scheme is found using the derivative of the negative log with respect to \(\sigma^2\), and is run in parallel. This is shown here:

\(\alpha^{k+1} = \frac{1}{nN}\left\{ \frac{\textbf{S}^T\textbf{S} + \textbf{f}^T\textbf{H}^T\textbf{Hf}}{2} - \textbf{1}^T_N\left[(\textbf{S} \circ\textbf{Hf})\circ\frac{I_n(\textbf{S}\circ\textbf{Hf}/\alpha^k)} {I_{n-1}(\textbf{S}\circ\textbf{Hf}/\alpha^k)} \right ]\right \}\)

For more details, see [1].

References

1(1,2,3)

Canales-Rodríguez, E. J., Daducci, A., Sotiropoulos, S. N., Caruyer, E., Aja-Fernández, S., Radua, J., Mendizabal, J. M. Y., Iturria-Medina, Y., Melie-García, L., Alemán-Gómez, Y., Thiran, J.-P.,Sarró, S., Pomarol-Clotet, E., & Salvador, R. (2015). Spherical Deconvolution of Multichannel Diffusion MRI Data with Non-Gaussian Noise Models and Spatial Regularization. PLOS ONE, 10(10), e0138910. https://doi.org/10.1371/journal.pone.0138910

2

Constantinides, C. D., Atalar, E., & McVeigh, E. R. (1997). Signal-to-Noise Measurements in Magnitude Images from NMR Phased Arrays. Magnetic Resonance in Medicine : Official Journal of the Society of Magnetic Resonance in Medicine / Society of Magnetic Resonance in Medicine, 38(5), 852–857.

rumba_deconv_global

dipy.reconst.rumba.rumba_deconv_global(data, kernel, mask, n_iter=600, recon_type='smf', n_coils=1, R=1, use_tv=True, verbose=False)

Fit fODF for all voxels simultaneously using RUMBA-SD.

Deconvolves the kernel from the diffusion-weighted signal at each voxel by computing a maximum likelihood estimation of the fODF [1]. Global fitting also permits the use of total variation regularization (RUMBA-SD + TV). The spatial dependence introduced by TV promotes smoother solutions (i.e. prevents oscillations), while still allowing for sharp discontinuities [2]. This promotes smoothness and continuity along individual tracts while preventing smoothing of adjacent tracts.

Generally, global_fit will proceed more quickly than the voxelwise fit provided that the computer has adequate RAM (>= 16 GB should be more than sufficient).

Parameters
data4d ndarray (x, y, z, N)

Signal values for entire brain. None of the volume dimensions x, y, z can be 1 if TV regularization is required.

kernel2d ndarray (N, M)

Deconvolution kernel mapping volume fractions of the M compartments to N-length signal. Last two columns should be for GM and CSF.

mask3d ndarray(x, y, z)

Binary mask specifying voxels of interest with 1; fODF will only be fit at these voxels (0 elsewhere).

n_iterint, optional

Number of iterations for fODF estimation. Must be a positive int. Default: 600

recon_type{‘smf’, ‘sos’}, optional

MRI reconstruction method: spatial matched filter (SMF) or sum-of-squares (SoS). SMF reconstruction generates Rician noise while SoS reconstruction generates Noncentral Chi noise. Default: ‘smf’

n_coilsint, optional

Number of coils in MRI scanner – only relevant in SoS reconstruction. Must be a positive int. Default: 1

use_tvbool, optional

If true, applies total variation regularization. This requires a brain volume with no singleton dimensions. Default: True

verbosebool, optional

If true, logs updates on estimated signal-to-noise ratio after each iteration. Default: False

Returns
fit_array4d ndarray (x, y, z, M)

fODF and GM/CSF volume fractions computed for each voxel. First M-2 components are fODF, while last two are GM and CSf respectively.

Notes

TV modifies our cost function as follows:

\(J(\textbf{f}) = -\log{P(\textbf{S}|\textbf{H}, \textbf{f}, \sigma^2, n)})+ \alpha_{TV}TV(\textbf{f})\)

where the first term is the negative log likelihood described in the notes of rumba_deconv, and the second term is the TV energy, or the sum of gradient absolute values for the fODF across the entire brain. This results in a new multiplicative factor in the iterative scheme, now becoming:

\(\textbf{f}^{k+1} = \textbf{f}^k \circ \frac{\textbf{H}^T\left[\textbf{S} \circ\frac{I_n(\textbf{S}\circ\textbf{Hf}^k/\sigma^2)} {I_{n-1}(\textbf{S} \circ\textbf{Hf}^k/\sigma^2)} \right ]} {\textbf{H}^T\textbf{Hf}^k}\circ \textbf{R}^k\)

where \(\textbf{R}^k\) is computed voxelwise by:

\((\textbf{R}^k)_j = \frac{1}{1 - \alpha_{TV}div\left(\frac{\triangledown[ \textbf{f}^k_{3D}]_j}{\lvert\triangledown[\textbf{f}^k_{3D}]_j \rvert} \right)\biggr\rvert_{x, y, z}}\)

Here, \(\triangledown\) is the symbol for the 3D gradient at any voxel.

The regularization strength, \(\alpha_{TV}\) is updated after each iteration by the discrepancy principle – specifically, it is selected to match the estimated variance after each iteration [3].

References

1

Canales-Rodríguez, E. J., Daducci, A., Sotiropoulos, S. N., Caruyer, E., Aja-Fernández, S., Radua, J., Mendizabal, J. M. Y., Iturria-Medina, Y., Melie-García, L., Alemán-Gómez, Y., Thiran, J.-P., Sarró, S., Pomarol-Clotet, E., & Salvador, R. (2015). Spherical Deconvolution of Multichannel Diffusion MRI Data with Non-Gaussian Noise Models and Spatial Regularization. PLOS ONE, 10(10), e0138910. https://doi.org/10.1371/journal.pone.0138910

2

Rudin, L. I., Osher, S., & Fatemi, E. (1992). Nonlinear total variation based noise removal algorithms. Physica D: Nonlinear Phenomena, 60(1), 259–268. https://doi.org/10.1016/0167-2789(92)90242-F

3

Chambolle A. An algorithm for total variation minimization and applications. Journal of Mathematical Imaging and Vision. 2004; 20:89–97.

single_tensor

dipy.reconst.rumba.single_tensor(gtab, S0=1, evals=None, evecs=None, snr=None)

Simulate diffusion-weighted signals with a single tensor.

Parameters
gtabGradientTable

Table with information of b-values and gradient directions g. Note that if gtab has a btens attribute, simulations will be performed according to the given b-tensor B information.

S0double,

Strength of signal in the presence of no diffusion gradient (also called the b=0 value).

evals(3,) ndarray

Eigenvalues of the diffusion tensor. By default, values typical for prolate white matter are used.

evecs(3, 3) ndarray

Eigenvectors of the tensor. You can also think of this as a rotation matrix that transforms the direction of the tensor. The eigenvectors need to be column wise.

snrfloat

Signal to noise ratio, assuming Rician noise. None implies no noise.

Returns
S(N,) ndarray
Simulated signal:

S(b, g) = S_0 e^(-b g^T R D R.T g), if gtab.tens=None S(B) = S_0 e^(-B:D), if gtab.tens information is given

References

1

M. Descoteaux, “High Angular Resolution Diffusion MRI: from Local Estimation to Segmentation and Tractography”, PhD thesis, University of Nice-Sophia Antipolis, p. 42, 2008.

2

E. Stejskal and J. Tanner, “Spin diffusion measurements: spin echos in the presence of a time-dependent field gradient”, Journal of Chemical Physics, nr. 42, pp. 288–292, 1965.

unique_bvals_tolerance

dipy.reconst.rumba.unique_bvals_tolerance(bvals, tol=20)

Gives the unique b-values of the data, within a tolerance gap

The b-values must be regrouped in clusters easily separated by a distance greater than the tolerance gap. If all the b-values of a cluster fit within the tolerance gap, the highest b-value is kept.

Parameters
bvalsndarray

Array containing the b-values

tolint

The tolerated gap between the b-values to extract and the actual b-values.

Returns
ubvalsndarray

Array containing the unique b-values using the median value for each cluster

vec2vec_rotmat

dipy.reconst.rumba.vec2vec_rotmat(u, v)

rotation matrix from 2 unit vectors

u, v being unit 3d vectors return a 3x3 rotation matrix R than aligns u to v.

In general there are many rotations that will map u to v. If S is any rotation using v as an axis then R.S will also map u to v since (S.R)u = S(Ru) = Sv = v. The rotation R returned by vec2vec_rotmat leaves fixed the perpendicular to the plane spanned by u and v.

The transpose of R will align v to u.

Parameters
uarray, shape(3,)
varray, shape(3,)
Returns
Rarray, shape(3,3)

Examples

>>> import numpy as np
>>> from dipy.core.geometry import vec2vec_rotmat
>>> u=np.array([1,0,0])
>>> v=np.array([0,1,0])
>>> R=vec2vec_rotmat(u,v)
>>> np.dot(R,u)
array([ 0.,  1.,  0.])
>>> np.dot(R.T,v)
array([ 1.,  0.,  0.])

Cache

class dipy.reconst.sfm.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)

Methods

cache_clear()

Clear the cache.

cache_get(tag, key[, default])

Retrieve a value from the cache.

cache_set(tag, key, value)

Store a value in the cache.

__init__(*args, **kwargs)
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

ExponentialIsotropicFit

class dipy.reconst.sfm.ExponentialIsotropicFit(model, params)

Bases: dipy.reconst.sfm.IsotropicFit

A fit to the ExponentialIsotropicModel object, based on data.

Methods

predict([gtab])

Predict the isotropic signal, based on a gradient table.

__init__(model, params)

Initialize an IsotropicFit object.

Parameters
modelIsotropicModel class instance
paramsndarray

The mean isotropic model parameters (the mean diffusion-weighted signal in each voxel).

n_voxint

The number of voxels for which the fit was done.

predict(gtab=None)

Predict the isotropic signal, based on a gradient table. In this case, the prediction will be for an exponential decay with the mean diffusivity derived from the data that was fit.

Parameters
gtaba GradientTable class instance (optional)

Defaults to use the gtab from the IsotropicModel from which this fit was derived.

ExponentialIsotropicModel

class dipy.reconst.sfm.ExponentialIsotropicModel(gtab)

Bases: dipy.reconst.sfm.IsotropicModel

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

Methods

fit(data[, mask])

Parameters

__init__(gtab)

Initialize an IsotropicModel.

Parameters
gtaba GradientTable class instance
fit(data, mask=None, **kwargs)
Parameters
datandarray
maskarray, optional

A boolean array used to mark the coordinates in the data that should be analyzed. Has the shape data.shape[:-1]. Default: None, which implies that all points should be analyzed.

Returns
ExponentialIsotropicFit class instance.

IsotropicFit

class dipy.reconst.sfm.IsotropicFit(model, params)

Bases: dipy.reconst.base.ReconstFit

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

Methods

predict([gtab])

Predict the isotropic signal.

__init__(model, params)

Initialize an IsotropicFit object.

Parameters
modelIsotropicModel class instance
paramsndarray

The mean isotropic model parameters (the mean diffusion-weighted signal in each voxel).

n_voxint

The number of voxels for which the fit was done.

predict(gtab=None)

Predict the isotropic signal.

Based on a gradient table. In this case, the (naive!) prediction will be the mean of the diffusion-weighted signal in the voxels.

Parameters
gtaba GradientTable class instance (optional)

Defaults to use the gtab from the IsotropicModel from which this fit was derived.

IsotropicModel

class dipy.reconst.sfm.IsotropicModel(gtab)

Bases: dipy.reconst.base.ReconstModel

A base-class for the representation of isotropic signals.

The default behavior, suitable for single b-value data is to calculate the mean in each voxel as an estimate of the signal that does not depend on direction.

Methods

fit(data[, mask])

Fit an IsotropicModel.

__init__(gtab)

Initialize an IsotropicModel.

Parameters
gtaba GradientTable class instance
fit(data, mask=None, **kwargs)

Fit an IsotropicModel.

This boils down to finding the mean diffusion-weighted signal in each voxel

Parameters
datandarray
Returns
IsotropicFit class instance.

OrderedDict

class dipy.reconst.sfm.OrderedDict

Bases: dict

Dictionary that remembers insertion order

Methods

clear()

copy()

fromkeys(/, iterable[, value])

Create a new ordered dictionary with keys from iterable and values set to value.

get(key[, default])

Return the value for key if key is in the dictionary, else default.

items()

keys()

move_to_end(/, key[, last])

Move an existing element to the end (or beginning if last is false).

pop(k[,d])

value.

popitem(/[, last])

Remove and return a (key, value) pair from the dictionary.

setdefault(/, key[, default])

Insert key with a value of default if key is not in the dictionary.

update([E, ]**F)

If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

values()

__init__(*args, **kwargs)
clear() None.  Remove all items from od.
copy() a shallow copy of od
fromkeys(/, iterable, value=None)

Create a new ordered dictionary with keys from iterable and values set to value.

items() a set-like object providing a view on D's items
keys() a set-like object providing a view on D's keys
move_to_end(/, key, last=True)

Move an existing element to the end (or beginning if last is false).

Raise KeyError if the element does not exist.

pop(k[, d]) v, remove specified key and return the corresponding

value. If key is not found, d is returned if given, otherwise KeyError is raised.

popitem(/, last=True)

Remove and return a (key, value) pair from the dictionary.

Pairs are returned in LIFO order if last is true or FIFO order if false.

setdefault(/, key, default=None)

Insert key with a value of default if key is not in the dictionary.

Return the value for key if key is in the dictionary, else default.

update([E, ]**F) None.  Update D from dict/iterable E and F.

If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

values() an object providing a view on D's values

ReconstFit

class dipy.reconst.sfm.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)

ReconstModel

class dipy.reconst.sfm.ReconstModel(gtab)

Bases: object

Abstract class for signal reconstruction models

Methods

fit

__init__(gtab)

Initialization of the abstract class for signal reconstruction models

Parameters
gtabGradientTable class instance
fit(data, mask=None, **kwargs)

SparseFascicleFit

class dipy.reconst.sfm.SparseFascicleFit(model, beta, S0, iso)

Bases: dipy.reconst.base.ReconstFit

Methods

odf(sphere)

The orientation distribution function of the SFM

predict([gtab, response, S0])

Predict the signal based on the SFM parameters

__init__(model, beta, S0, iso)

Initalize a SparseFascicleFit class instance

Parameters
modela SparseFascicleModel object.
betandarray

The parameters of fit to data.

S0ndarray

The mean non-diffusion-weighted signal.

isoIsotropicFit class instance

A representation of the isotropic signal, together with parameters of the isotropic signal in each voxel, that is capable of deriving/predicting an isotropic signal, based on a gradient-table.

odf(sphere)

The orientation distribution function of the SFM

Parameters
sphereSphere

The points in which the ODF is evaluated

Returns
odfndarray of shape (x, y, z, sphere.vertices.shape[0])
predict(gtab=None, response=None, S0=None)

Predict the signal based on the SFM parameters

Parameters
gtabGradientTable, optional

The bvecs/bvals to predict the signal on. Default: the gtab from the model object.

responselist of 3 elements, optional

The eigenvalues of a tensor which will serve as a kernel function. Default: the response of the model object. Default to use model.response.

S0float or array, optional

The non-diffusion-weighted signal. Default: use the S0 of the data

Returns
pred_signdarray

The signal predicted in each voxel/direction

SparseFascicleModel

class dipy.reconst.sfm.SparseFascicleModel(gtab, sphere=None, response=[0.0015, 0.0005, 0.0005], solver='ElasticNet', l1_ratio=0.5, alpha=0.001, isotropic=None, seed=42)

Bases: dipy.reconst.base.ReconstModel, dipy.reconst.cache.Cache

Methods

cache_clear()

Clear the cache.

cache_get(tag, key[, default])

Retrieve a value from the cache.

cache_set(tag, key, value)

Store a value in the cache.

design_matrix()

The design matrix for a SFM.

fit(data[, mask, num_processes, ...])

Fit the SparseFascicleModel object to data.

__init__(gtab, sphere=None, response=[0.0015, 0.0005, 0.0005], solver='ElasticNet', l1_ratio=0.5, alpha=0.001, isotropic=None, seed=42)

Initialize a Sparse Fascicle Model

Parameters
gtabGradientTable class instance
sphereSphere class instance, optional

A sphere on which coefficients will be estimated. Default: symmetric sphere with 362 points (from dipy.data).

response(3,) array-like, optional

The eigenvalues of a canonical tensor to be used as the response function of single-fascicle signals. Default:[0.0015, 0.0005, 0.0005]

solverstring, or initialized linear model object.

This will determine the algorithm used to solve the set of linear equations underlying this model. If it is a string it needs to be one of the following: {‘ElasticNet’, ‘NNLS’}. Otherwise, it can be an object that inherits from dipy.optimize.SKLearnLinearSolver or an object with a similar interface from Scikit Learn: sklearn.linear_model.ElasticNet, sklearn.linear_model.Lasso or sklearn.linear_model.Ridge and other objects that inherit from sklearn.base.RegressorMixin. Default: ‘ElasticNet’.

l1_ratiofloat, optional

Sets the balance betwee L1 and L2 regularization in ElasticNet [Zou2005]. Default: 0.5

alphafloat, optional

Sets the balance between least-squares error and L1/L2 regularization in ElasticNet [Zou2005]. Default: 0.001

isotropicIsotropicModel class instance

This is a class that implements the function that calculates the value of the isotropic signal. This is a value of the signal that is independent of direction, and therefore removed from both sides of the SFM equation. The default is an instance of IsotropicModel, but other functions can be inherited from IsotropicModel to implement other fits to the aspects of the data that depend on b-value, but not on direction.

Notes

This is an implementation of the SFM, described in [Rokem2015].

Rokem2014

Ariel Rokem, Jason D. Yeatman, Franco Pestilli, Kendrick N. Kay, Aviv Mezer, Stefan van der Walt, Brian A. Wandell (2014). Evaluating the accuracy of diffusion MRI models in white matter. PLoS ONE 10(4): e0123272. doi:10.1371/journal.pone.0123272

Zou2005(1,2)

Zou H, Hastie T (2005). Regularization and variable selection via the elastic net. J R Stat Soc B:301-320

design_matrix()

The design matrix for a SFM.

Returns
ndarray

The design matrix, where each column is a rotated version of the response function.

fit(data, mask=None, num_processes=1, parallel_backend='multiprocessing')

Fit the SparseFascicleModel object to data.

Parameters
dataarray

The measured signal.

maskarray, optional

A boolean array used to mark the coordinates in the data that should be analyzed. Has the shape data.shape[:-1]. Default: None, which implies that all points should be analyzed.

num_processesint, optional

Split the fit calculation to a pool of children processes using joblib. This only applies to 4D data arrays. Default is 1, which does not require joblib and will run fit serially. If < 0 the maximal number of cores minus num_processes + 1 is used (enter -1 to use as many cores as possible). 0 raises an error.

parallel_backend: str, ParallelBackendBase instance or None

Specify the parallelization backend implementation. Supported backends are: - “loky” used by default, can induce some

communication and memory overhead when exchanging input and output data with the worker Python processes.

  • “multiprocessing” previous process-based backend based on multiprocessing.Pool. Less robust than loky.

  • “threading” is a very low-overhead backend but it suffers from the Python Global Interpreter Lock if the called function relies a lot on Python objects. “threading” is mostly useful when the execution bottleneck is a compiled extension that explicitly releases the GIL (for instance a Cython loop wrapped in a “with nogil” block or an expensive call to a library such as NumPy).

Default: ‘multiprocessing’.

Returns
SparseFascicleFit object

auto_attr

dipy.reconst.sfm.auto_attr(func)

Decorator to create OneTimeProperty attributes.

Parameters
funcmethod

The method that will be called the first time to compute a value. Afterwards, the method’s name will be a standard attribute holding the value of this computation.

Examples

>>> class MagicProp(object):
...     @auto_attr
...     def a(self):
...         return 99
...
>>> x = MagicProp()
>>> 'a' in x.__dict__
False
>>> x.a
99
>>> 'a' in x.__dict__
True

determine_num_processes

dipy.reconst.sfm.determine_num_processes(num_processes)

Determine the effective number of processes for parallelization.

  • For num_processes = None` return the maximum number of cores retrieved

by cpu_count().

  • For num_processes > 0, return this value.

  • For num_processes < 0, return the maximal number of cores minus

num_processes + 1. In particular num_processes = -1 will use as many cores as possible.

  • For num_processes = 0 a ValueError is raised.

Parameters
num_processesint or None

Desired number of processes to be used.

nanmean

dipy.reconst.sfm.nanmean(a, axis=None, dtype=None, out=None, keepdims=<no value>, *, where=<no value>)

Compute the arithmetic mean along the specified axis, ignoring NaNs.

Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. float64 intermediate and return values are used for integer inputs.

For all-NaN slices, NaN is returned and a RuntimeWarning is raised.

New in version 1.8.0.

Parameters
aarray_like

Array containing numbers whose mean is desired. If a is not an array, a conversion is attempted.

axis{int, tuple of int, None}, optional

Axis or axes along which the means are computed. The default is to compute the mean of the flattened array.

dtypedata-type, optional

Type to use in computing the mean. For integer inputs, the default is float64; for inexact inputs, it is the same as the input dtype.

outndarray, optional

Alternate output array in which to place the result. The default is None; if provided, it must have the same shape as the expected output, but the type will be cast if necessary. See ufuncs-output-type for more details.

keepdimsbool, optional

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original a.

If the value is anything but the default, then keepdims will be passed through to the mean or sum methods of sub-classes of ndarray. If the sub-classes methods does not implement keepdims any exceptions will be raised.

wherearray_like of bool, optional

Elements to include in the mean. See ~numpy.ufunc.reduce for details.

New in version 1.22.0.

Returns
mndarray, see dtype parameter above

If out=None, returns a new array containing the mean values, otherwise a reference to the output array is returned. Nan is returned for slices that contain only NaNs.

See also

average

Weighted average

mean

Arithmetic mean taken while not ignoring NaNs

var, nanvar

Notes

The arithmetic mean is the sum of the non-NaN elements along the axis divided by the number of non-NaN elements.

Note that for floating-point input, the mean is computed using the same precision the input has. Depending on the input data, this can cause the results to be inaccurate, especially for float32. Specifying a higher-precision accumulator using the dtype keyword can alleviate this issue.

Examples

>>> a = np.array([[1, np.nan], [3, 4]])
>>> np.nanmean(a)
2.6666666666666665
>>> np.nanmean(a, axis=0)
array([2.,  4.])
>>> np.nanmean(a, axis=1)
array([1.,  3.5]) # may vary

optional_package

dipy.reconst.sfm.optional_package(name, trip_msg=None)

Return package-like thing and module setup for package name

Parameters
namestr

package name

trip_msgNone or str

message to give when someone tries to use the return package, but we could not import it, and have returned a TripWire object instead. Default message if None.

Returns
pkg_likemodule or TripWire instance

If we can import the package, return it. Otherwise return an object raising an error when accessed

have_pkgbool

True if import for package was successful, false otherwise

module_setupfunction

callable usually set as setup_module in calling namespace, to allow skipping tests.

Examples

Typical use would be something like this at the top of a module using an optional package:

>>> from dipy.utils.optpkg import optional_package
>>> pkg, have_pkg, setup_module = optional_package('not_a_package')

Of course in this case the package doesn’t exist, and so, in the module:

>>> have_pkg
False

and

>>> pkg.some_function() 
Traceback (most recent call last):
    ...
TripWireError: We need package not_a_package for these functions, but
``import not_a_package`` raised an ImportError

If the module does exist - we get the module

>>> pkg, _, _ = optional_package('os')
>>> hasattr(pkg, 'path')
True

Or a submodule if that’s what we asked for

>>> subpkg, _, _ = optional_package('os.path')
>>> hasattr(subpkg, 'dirname')
True

sfm_design_matrix

dipy.reconst.sfm.sfm_design_matrix(gtab, sphere, response, mode='signal')

Construct the SFM design matrix

Parameters
gtabGradientTable or Sphere

Sets the rows of the matrix, if the mode is ‘signal’, this should be a GradientTable. If mode is ‘odf’ this should be a Sphere.

sphereSphere

Sets the columns of the matrix

responselist of 3 elements

The eigenvalues of a tensor which will serve as a kernel function.

modestr {‘signal’ | ‘odf’}, optional

Choose the (default) ‘signal’ for a design matrix containing predicted signal in the measurements defined by the gradient table for putative fascicles oriented along the vertices of the sphere. Otherwise, choose ‘odf’ for an odf convolution matrix, with values of the odf calculated from a tensor with the provided response eigenvalues, evaluated at the b-vectors in the gradient table, for the tensors with prinicipal diffusion directions along the vertices of the sphere.

Returns
matndarray

A design matrix that can be used for one of the following operations: when the ‘signal’ mode is used, each column contains the putative signal in each of the bvectors of the gtab if a fascicle is oriented in the direction encoded by the sphere vertex corresponding to this column. This is used for deconvolution with a measured DWI signal. If the ‘odf’ mode is chosen, each column instead contains the values of the tensor ODF for a tensor with a principal diffusion direction corresponding to this vertex. This is used to generate odfs from the fits of the SFM for the purpose of tracking.

Notes

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.

Behrens2007

Behrens TEJ, Berg HJ, Jbabdi S, Rushworth MFS, Woolrich MW (2007): Probabilistic diffusion tractography with multiple fibre orientations: What can we gain? Neuroimage 34:144-55.

Examples

>>> import dipy.data as dpd
>>> data, gtab = dpd.dsi_voxels()
>>> sphere = dpd.get_sphere()
>>> from dipy.reconst.sfm import sfm_design_matrix

A canonical tensor approximating corpus-callosum voxels [Rokem2014]:

>>> tensor_matrix = sfm_design_matrix(gtab, sphere,
...                                   [0.0015, 0.0005, 0.0005])

A ‘stick’ function ([Behrens2007]):

>>> stick_matrix = sfm_design_matrix(gtab, sphere, [0.001, 0, 0])

Cache

class dipy.reconst.shm.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)

Methods

cache_clear()

Clear the cache.

cache_get(tag, key[, default])

Retrieve a value from the cache.

cache_set(tag, key, value)

Store a value in the cache.

__init__(*args, **kwargs)
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

CsaOdfModel

class dipy.reconst.shm.CsaOdfModel(gtab, sh_order, smooth=0.006, min_signal=1e-05, assume_normed=False)

Bases: dipy.reconst.shm.QballBaseModel

Implementation of Constant Solid Angle reconstruction method.

References

1

Aganj, I., et al. 2009. ODF Reconstruction in Q-Ball Imaging With Solid Angle Consideration.

Methods

cache_clear()

Clear the cache.

cache_get(tag, key[, default])

Retrieve a value from the cache.

cache_set(tag, key, value)

Store a value in the cache.

fit(data[, mask])

Fits the model to diffusion data and returns the model fit

sampling_matrix(sphere)

The matrix needed to sample ODFs from coefficients of the model.

__init__(gtab, sh_order, smooth=0.006, min_signal=1e-05, assume_normed=False)

Creates a model that can be used to fit or sample diffusion data

Parameters
gtabGradientTable

Diffusion gradients used to acquire data

sh_ordereven int >= 0

the spherical harmonic order of the model

smoothfloat between 0 and 1, optional

The regularization parameter of the model

min_signalfloat, > 0, optional

During fitting, all signal values less than min_signal are clipped to min_signal. This is done primarily to avoid values less than or equal to zero when taking logs.

assume_normedbool, optional

If True, clipping and normalization of the data with respect to the mean B0 signal are skipped during mode fitting. This is an advanced feature and should be used with care.

See also

normalize_data
max = 0.999
min = 0.001

OdfFit

class dipy.reconst.shm.OdfFit(model, data)

Bases: dipy.reconst.base.ReconstFit

Methods

odf(sphere)

To be implemented but specific odf models

__init__(model, data)
odf(sphere)

To be implemented but specific odf models

OdfModel

class dipy.reconst.shm.OdfModel(gtab)

Bases: dipy.reconst.base.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.

Methods

fit(data)

To be implemented by specific odf models

__init__(gtab)

Initialization of the abstract class for signal reconstruction models

Parameters
gtabGradientTable class instance
fit(data)

To be implemented by specific odf models

OpdtModel

class dipy.reconst.shm.OpdtModel(gtab, sh_order, smooth=0.006, min_signal=1e-05, assume_normed=False)

Bases: dipy.reconst.shm.QballBaseModel

Implementation of Orientation Probability Density Transform reconstruction method.

References

1

Tristan-Vega, A., et al. 2010. A new methodology for estimation of fiber populations in white matter of the brain with Funk-Radon transform.

2

Tristan-Vega, A., et al. 2009. Estimation of fiber orientation probability density functions in high angular resolution diffusion imaging.

Methods

cache_clear()

Clear the cache.

cache_get(tag, key[, default])

Retrieve a value from the cache.

cache_set(tag, key, value)

Store a value in the cache.

fit(data[, mask])

Fits the model to diffusion data and returns the model fit

sampling_matrix(sphere)

The matrix needed to sample ODFs from coefficients of the model.

__init__(gtab, sh_order, smooth=0.006, min_signal=1e-05, assume_normed=False)

Creates a model that can be used to fit or sample diffusion data

Parameters
gtabGradientTable

Diffusion gradients used to acquire data

sh_ordereven int >= 0

the spherical harmonic order of the model

smoothfloat between 0 and 1, optional

The regularization parameter of the model

min_signalfloat, > 0, optional

During fitting, all signal values less than min_signal are clipped to min_signal. This is done primarily to avoid values less than or equal to zero when taking logs.

assume_normedbool, optional

If True, clipping and normalization of the data with respect to the mean B0 signal are skipped during mode fitting. This is an advanced feature and should be used with care.

See also

normalize_data

QballBaseModel

class dipy.reconst.shm.QballBaseModel(gtab, sh_order, smooth=0.006, min_signal=1e-05, assume_normed=False)

Bases: dipy.reconst.shm.SphHarmModel

To be subclassed by Qball type models.

Methods

cache_clear()

Clear the cache.

cache_get(tag, key[, default])

Retrieve a value from the cache.

cache_set(tag, key, value)

Store a value in the cache.

fit(data[, mask])

Fits the model to diffusion data and returns the model fit

sampling_matrix(sphere)

The matrix needed to sample ODFs from coefficients of the model.

__init__(gtab, sh_order, smooth=0.006, min_signal=1e-05, assume_normed=False)

Creates a model that can be used to fit or sample diffusion data

Parameters
gtabGradientTable

Diffusion gradients used to acquire data

sh_ordereven int >= 0

the spherical harmonic order of the model

smoothfloat between 0 and 1, optional

The regularization parameter of the model

min_signalfloat, > 0, optional

During fitting, all signal values less than min_signal are clipped to min_signal. This is done primarily to avoid values less than or equal to zero when taking logs.

assume_normedbool, optional

If True, clipping and normalization of the data with respect to the mean B0 signal are skipped during mode fitting. This is an advanced feature and should be used with care.

See also

normalize_data
fit(data, mask=None)

Fits the model to diffusion data and returns the model fit

QballModel

class dipy.reconst.shm.QballModel(gtab, sh_order, smooth=0.006, min_signal=1e-05, assume_normed=False)

Bases: dipy.reconst.shm.QballBaseModel

Implementation of regularized Qball reconstruction method.

References

1

Descoteaux, M., et al. 2007. Regularized, fast, and robust analytical Q-ball imaging.

Methods

cache_clear()

Clear the cache.

cache_get(tag, key[, default])

Retrieve a value from the cache.

cache_set(tag, key, value)

Store a value in the cache.

fit(data[, mask])

Fits the model to diffusion data and returns the model fit

sampling_matrix(sphere)

The matrix needed to sample ODFs from coefficients of the model.

__init__(gtab, sh_order, smooth=0.006, min_signal=1e-05, assume_normed=False)

Creates a model that can be used to fit or sample diffusion data

Parameters
gtabGradientTable

Diffusion gradients used to acquire data

sh_ordereven int >= 0

the spherical harmonic order of the model

smoothfloat between 0 and 1, optional

The regularization parameter of the model

min_signalfloat, > 0, optional

During fitting, all signal values less than min_signal are clipped to min_signal. This is done primarily to avoid values less than or equal to zero when taking logs.

assume_normedbool, optional

If True, clipping and normalization of the data with respect to the mean B0 signal are skipped during mode fitting. This is an advanced feature and should be used with care.

See also

normalize_data

ResidualBootstrapWrapper

class dipy.reconst.shm.ResidualBootstrapWrapper(signal_object, B, where_dwi, min_signal=1e-05)

Bases: object

Returns a residual bootstrap sample of the signal_object when indexed

Wraps a signal_object, this signal object can be an interpolator. When indexed, the the wrapper indexes the signal_object to get the signal. There wrapper than samples the residual boostrap distribution of signal and returns that sample.

__init__(signal_object, B, where_dwi, min_signal=1e-05)

Builds a ResidualBootstrapWapper

Given some linear model described by B, the design matrix, and a signal_object, returns an object which can sample the residual bootstrap distribution of the signal. We assume that the signals are normalized so we clip the bootsrap samples to be between min_signal and 1.

Parameters
signal_objectsome object that can be indexed

This object should return diffusion weighted signals when indexed.

Bndarray, ndim=2

The design matrix of the spherical harmonics model used to fit the data. This is the model that will be used to compute the residuals and sample the residual bootstrap distribution

where_dwi

indexing object to find diffusion weighted signals from signal

min_signalfloat

The lowest allowable signal.

SphHarmFit

class dipy.reconst.shm.SphHarmFit(model, shm_coef, mask)

Bases: dipy.reconst.odf.OdfFit

Diffusion data fit to a spherical harmonic model

Attributes
shape
shm_coeff

The spherical harmonic coefficients of the odf

Methods

odf(sphere)

Samples the odf function on the points of a sphere

predict([gtab, S0])

Predict the diffusion signal from the model coefficients.

gfa

__init__(model, shm_coef, mask)
gfa()
odf(sphere)

Samples the odf function on the points of a sphere

Parameters
sphereSphere

The points on which to sample the odf.

Returns
valuesndarray

The value of the odf on each point of sphere.

predict(gtab=None, S0=1.0)

Predict the diffusion signal from the model coefficients.

Parameters
gtaba GradientTable class instance

The directions and bvalues on which prediction is desired

S0float array

The mean non-diffusion-weighted signal in each voxel.

property shape
property shm_coeff

The spherical harmonic coefficients of the odf

Make this a property for now, if there is a usecase for modifying the coefficients we can add a setter or expose the coefficients more directly

SphHarmModel

class dipy.reconst.shm.SphHarmModel(gtab)

Bases: dipy.reconst.odf.OdfModel, dipy.reconst.cache.Cache

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

Methods

cache_clear()

Clear the cache.

cache_get(tag, key[, default])

Retrieve a value from the cache.

cache_set(tag, key, value)

Store a value in the cache.

fit(data)

To be implemented by specific odf models

sampling_matrix(sphere)

The matrix needed to sample ODFs from coefficients of the model.

__init__(gtab)

Initialization of the abstract class for signal reconstruction models

Parameters
gtabGradientTable class instance
sampling_matrix(sphere)

The matrix needed to sample ODFs from coefficients of the model.

Parameters
sphereSphere

Points used to sample ODF.

Returns
sampling_matrixarray

The size of the matrix will be (N, M) where N is the number of vertices on sphere and M is the number of coefficients needed by the model.

anisotropic_power

dipy.reconst.shm.anisotropic_power(sh_coeffs, norm_factor=1e-05, power=2, non_negative=True)

Calculate anisotropic power map with a given SH coefficient matrix.

Parameters
sh_coeffsndarray

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.

powerint, 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_apndarray

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

auto_attr

dipy.reconst.shm.auto_attr(func)

Decorator to create OneTimeProperty attributes.

Parameters
funcmethod

The method that will be called the first time to compute a value. Afterwards, the method’s name will be a standard attribute holding the value of this computation.

Examples

>>> class MagicProp(object):
...     @auto_attr
...     def a(self):
...         return 99
...
>>> x = MagicProp()
>>> 'a' in x.__dict__
False
>>> x.a
99
>>> 'a' in x.__dict__
True

bootstrap_data_array

dipy.reconst.shm.bootstrap_data_array(data, H, R, permute=None)

Applies the Residual Bootstraps to the data given H and R

data must be normalized, ie 0 < data <= 1

This function, and the bootstrap_data_voxel function, calculate residual-bootsrap samples given a Hat matrix and a Residual matrix. These samples can be used for non-parametric statistics or for bootstrap probabilistic tractography:

References

1

J. I. Berman, et al., “Probabilistic streamline q-ball tractography using the residual bootstrap” 2008.

2

HA Haroon, et al., “Using the model-based residual bootstrap to quantify uncertainty in fiber orientations from Q-ball analysis” 2009.

3

B. Jeurissen, et al., “Probabilistic Fiber Tracking Using the Residual Bootstrap with Constrained Spherical Deconvolution” 2011.

bootstrap_data_voxel

dipy.reconst.shm.bootstrap_data_voxel(data, H, R, permute=None)

Like bootstrap_data_array but faster when for a single voxel

data must be 1d and normalized

calculate_max_order

dipy.reconst.shm.calculate_max_order(n_coeffs, full_basis=False)

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

Parameters
n_coeffsint

The number of SH coefficients

full_basis: bool, optional

True if the used SH basis contains even and odd order SH functions. False if the SH basis consists only of even order SH functions.

Returns
Lint

The maximal SH order, given the number of coefficients

Notes

The calculation in this function for the symmetric SH basis proceeds according to the following logic: .. math:

n = \frac{1}{2} (L+1) (L+2)
\rarrow 2n = L^2 + 3L + 2
\rarrow L^2 + 3L + 2 - 2n = 0
\rarrow L^2 + 3L + 2(1-n) = 0
\rarrow L_{1,2} = \frac{-3 \pm \sqrt{9 - 8 (1-n)}}{2}
\rarrow L{1,2} = \frac{-3 \pm \sqrt{1 + 8n}}{2}

Finally, the positive value is chosen between the two options.

For a full SH basis, the calculation consists in solving the equation \(n = (L + 1)^2\) for \(L\), which gives \(L = sqrt(n) - 1\).

cart2sphere

dipy.reconst.shm.cart2sphere(x, y, z)

Return angles for Cartesian 3D coordinates x, y, and z

See doc for sphere2cart for angle conventions and derivation of the formulae.

\(0\le\theta\mathrm{(theta)}\le\pi\) and \(-\pi\le\phi\mathrm{(phi)}\le\pi\)

Parameters
xarray_like

x coordinate in Cartesian space

yarray_like

y coordinate in Cartesian space

zarray_like

z coordinate

Returns
rarray

radius

thetaarray

inclination (polar) angle

phiarray

azimuth angle

convert_sh_from_legacy

dipy.reconst.shm.convert_sh_from_legacy(sh_coeffs, sh_basis, full_basis=False)

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

Parameters
sh_coeffs: ndarray

A ndarray where the last dimension is the SH coefficients estimates for that voxel.

sh_basis: {‘descoteaux07’, ‘tournier07’}

tournier07 for the Tournier 2007 [R8020d68d5dcd-2]_[R8020d68d5dcd-3]_ basis, descoteaux07 for the Descoteaux 2007 [1] basis.

full_basis: bool, optional

True if the input SH basis includes both even and odd order SH functions, else False.

Returns
out_sh_coeffs: ndarray

The array of coefficients expressed in the new SH basis.

References

1(1,2,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.

2

Tournier J.D., Calamante F. and Connelly A. Robust determination of the fibre orientation distribution in diffusion MRI: Non-negativity constrained super-resolved spherical deconvolution. NeuroImage. 2007;35(4):1459-1472.

3

Tournier J-D, Smith R, Raffelt D, Tabbara R, Dhollander T, Pietsch M, et al. MRtrix3: A fast, flexible and open software framework for medical image processing and visualisation. NeuroImage. 2019 Nov 15;202:116-137.

convert_sh_to_full_basis

dipy.reconst.shm.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

Parameters
sh_coeffs: ndarray

A ndarray where the last dimension is the SH coefficients estimates for that voxel.

Returns
full_sh_coeffs: ndarray

A ndarray where the last dimension is the SH coefficients estimates for that voxel in a full SH basis.

convert_sh_to_legacy

dipy.reconst.shm.convert_sh_to_legacy(sh_coeffs, sh_basis, full_basis=False)

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

Parameters
sh_coeffs: ndarray

A ndarray where the last dimension is the SH coefficients estimates for that voxel.

sh_basis: {‘descoteaux07’, ‘tournier07’}

tournier07 for the Tournier 2007 [R2032a14b59d6-2]_[R2032a14b59d6-3]_ basis, descoteaux07 for the Descoteaux 2007 [1] basis.

full_basis: bool, optional

True if the input SH basis includes both even and odd order SH functions.

Returns
out_sh_coeffs: ndarray

The array of coefficients expressed in the legacy SH basis.

References

1(1,2,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.

2

Tournier J.D., Calamante F. and Connelly A. Robust determination of the fibre orientation distribution in diffusion MRI: Non-negativity constrained super-resolved spherical deconvolution. NeuroImage. 2007;35(4):1459-1472.

3

Tournier J-D, Smith R, Raffelt D, Tabbara R, Dhollander T, Pietsch M, et al. MRtrix3: A fast, flexible and open software framework for medical image processing and visualisation. NeuroImage. 2019 Nov 15;202:116-137.

deprecate_with_version

dipy.reconst.shm.deprecate_with_version(message, since='', until='', version_comparator=<function cmp_pkg_version>, warn_class=<class 'DeprecationWarning'>, error_class=<class 'dipy.utils.deprecator.ExpiredDeprecationError'>)

Return decorator function function for deprecation warning / error.

The decorated function / method will:

  • Raise the given warning_class warning when the function / method gets called, up to (and including) version until (if specified);

  • Raise the given error_class error when the function / method gets called, when the package version is greater than version until (if specified).

Parameters
messagestr

Message explaining deprecation, giving possible alternatives.

sincestr, optional

Released version at which object was first deprecated.

untilstr, optional

Last released version at which this function will still raise a deprecation warning. Versions higher than this will raise an error.

version_comparatorcallable

Callable accepting string as argument, and return 1 if string represents a higher version than encoded in the version_comparator, 0 if the version is equal, and -1 if the version is lower. For example, the version_comparator may compare the input version string to the current package version string.

warn_classclass, optional

Class of warning to generate for deprecation.

error_classclass, optional

Class of error to generate when version_comparator returns 1 for a given argument of until.

Returns
deprecatorfunc

Function returning a decorator.

forward_sdeconv_mat

dipy.reconst.shm.forward_sdeconv_mat(r_rh, n)

Build forward spherical deconvolution matrix

Parameters
r_rhndarray

Rotational harmonics coefficients for the single fiber response function. Each element rh[i] is associated with spherical harmonics of degree 2*i.

nndarray

The order of spherical harmonic function associated with each row of the deconvolution matrix. Only even orders are allowed

Returns
Rndarray (N, N)

Deconvolution matrix with shape (N, N)

gen_dirac

dipy.reconst.shm.gen_dirac(m, n, theta, phi, legacy=True)

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

The spherical harmonics (SH) representation of this Dirac is returned as coefficients to spherical harmonic functions produced from descoteaux07 basis.

Parameters
mndarray (N,)

The degree of the spherical harmonic function associated with each coefficient.

nndarray (N,)

The order of the spherical harmonic function associated with each coefficient.

thetafloat [0, pi]

The polar (colatitudinal) coordinate.

phifloat [0, 2*pi]

The azimuthal (longitudinal) coordinate.

Returns
diracndarray

SH coefficients representing the Dirac function. The shape of this is (m + 2) * (m + 1) / 2.

See also

shm.real_sh_descoteaux_from_index, shm.real_sh_descoteaux

hat

dipy.reconst.shm.hat(B)

Returns the hat matrix for the design matrix B

lazy_index

dipy.reconst.shm.lazy_index(index)

Produces a lazy index

Returns a slice that can be used for indexing an array, if no slice can be made index is returned as is.

lcr_matrix

dipy.reconst.shm.lcr_matrix(H)

Returns a matrix for computing leveraged, centered residuals from data

if r = (d-Hd), the leveraged centered residuals are lcr = (r/l)-mean(r/l) ruturns the matrix R, such lcr = Rd

normalize_data

dipy.reconst.shm.normalize_data(data, where_b0, min_signal=1e-05, out=None)

Normalizes the data with respect to the mean b0

order_from_ncoef

dipy.reconst.shm.order_from_ncoef(ncoef, full_basis=False)

Given a number n of coefficients, calculate back the sh_order

Parameters
ncoef: int

number of coefficients

full_basis: bool, optional

True when coefficients are for a full SH basis.

Returns
sh_order: int

maximum order of SH basis

randint

dipy.reconst.shm.randint(low, high=None, size=None, dtype=int)

Return random integers from low (inclusive) to high (exclusive).

Return random integers from the “discrete uniform” distribution of the specified dtype in the “half-open” interval [low, high). If high is None (the default), then results are from [0, low).

Note

New code should use the integers method of a default_rng() instance instead; please see the random-quick-start.

Parameters
lowint or array-like of ints

Lowest (signed) integers to be drawn from the distribution (unless high=None, in which case this parameter is one above the highest such integer).

highint or array-like of ints, optional

If provided, one above the largest (signed) integer to be drawn from the distribution (see above for behavior if high=None). If array-like, must contain integer values

sizeint or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. Default is None, in which case a single value is returned.

dtypedtype, optional

Desired dtype of the result. Byteorder must be native. The default value is int.

New in version 1.11.0.

Returns
outint or ndarray of ints

size-shaped array of random integers from the appropriate distribution, or a single such random int if size not provided.

See also

random_integers

similar to randint, only for the closed interval [low, high], and 1 is the lowest value if high is omitted.

Generator.integers

which should be used for new code.

Examples

>>> np.random.randint(2, size=10)
array([1, 0, 0, 0, 1, 1, 0, 0, 1, 0]) # random
>>> np.random.randint(1, size=10)
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

Generate a 2 x 4 array of ints between 0 and 4, inclusive:

>>> np.random.randint(5, size=(2, 4))
array([[4, 0, 2, 1], # random
       [3, 2, 2, 0]])

Generate a 1 x 3 array with 3 different upper bounds

>>> np.random.randint(1, [3, 5, 10])
array([2, 2, 9]) # random

Generate a 1 by 3 array with 3 different lower bounds

>>> np.random.randint([1, 5, 7], 10)
array([9, 8, 7]) # random

Generate a 2 by 4 array using broadcasting with dtype of uint8

>>> np.random.randint([1, 3, 5, 7], [[10], [20]], dtype=np.uint8)
array([[ 8,  6,  9,  7], # random
       [ 1, 16,  9, 12]], dtype=uint8)

real_sh_descoteaux

dipy.reconst.shm.real_sh_descoteaux(sh_order, theta, phi, full_basis=False, legacy=True)

Compute real spherical harmonics as in Descoteaux et al. 2007 [R191e35d27b5b-1], where the real harmonic \(Y^m_n\) is defined to be:

Imag(\(Y^m_n\)) * sqrt(2) if m > 0 \(Y^0_n\) if m = 0 Real(\(Y^m_n\)) * sqrt(2) if m < 0

This may take scalar or array arguments. The inputs will be broadcasted against each other.

Parameters
sh_orderint

The maximum degree or the spherical harmonic basis.

thetafloat [0, pi]

The polar (colatitudinal) coordinate.

phifloat [0, 2*pi]

The azimuthal (longitudinal) coordinate.

full_basis: bool, optional

If true, returns a basis including odd order SH functions as well as even order SH functions. Otherwise returns only even order SH functions.

legacy: bool, optional

If true, uses DIPY’s legacy descoteaux07 implementation (where |m| for m < 0). Else, implements the basis as defined in Descoteaux et al. 2007.

Returns
real_shreal float

The real harmonic \(Y^m_n\) sampled at theta and phi.

marray

The degree of the harmonics.

narray

The order of the harmonics.

real_sh_descoteaux_from_index

dipy.reconst.shm.real_sh_descoteaux_from_index(m, n, theta, phi, legacy=True)

Compute real spherical harmonics as in Descoteaux et al. 2007 [R700bd48b1688-1], where the real harmonic \(Y^m_n\) is defined to be:

Imag(\(Y^m_n\)) * sqrt(2) if m > 0 \(Y^0_n\) if m = 0 Real(\(Y^m_n\)) * sqrt(2) if m < 0

This may take scalar or array arguments. The inputs will be broadcasted against each other.

Parameters
mint |m| <= n

The degree of the harmonic.

nint >= 0

The order of the harmonic.

thetafloat [0, pi]

The polar (colatitudinal) coordinate.

phifloat [0, 2*pi]

The azimuthal (longitudinal) coordinate.

legacy: bool, optional

If true, uses DIPY’s legacy descoteaux07 implementation (where |m| is used for m < 0). Else, implements the basis as defined in Descoteaux et al. 2007 (without the absolute value).

Returns
real_shreal float

The real harmonic \(Y^m_n\) sampled at theta and phi.

real_sh_tournier

dipy.reconst.shm.real_sh_tournier(sh_order, theta, phi, full_basis=False, legacy=True)

Compute real spherical harmonics as initially defined in Tournier 2007 [1] then updated in MRtrix3 [2], where the real harmonic \(Y^m_n\) is defined to be:

Real(\(Y^m_n\)) * sqrt(2) if m > 0 \(Y^0_n\) if m = 0 Imag(\(Y^|m|_n\)) * sqrt(2) if m < 0

This may take scalar or array arguments. The inputs will be broadcasted against each other.

Parameters
sh_orderint

The maximum degree or the spherical harmonic basis.

thetafloat [0, pi]

The polar (colatitudinal) coordinate.

phifloat [0, 2*pi]

The azimuthal (longitudinal) coordinate.

full_basis: bool, optional

If true, returns a basis including odd order SH functions as well as even order SH functions. Else returns only even order SH functions.

legacy: bool, optional

If true, uses MRtrix 0.2 SH basis definition, where the sqrt(2) factor is omitted. Else, uses MRtrix 3 definition presented above.

Returns
real_shreal float

The real harmonic \(Y^m_n\) sampled at theta and phi.

marray

The degree of the harmonics.

narray

The order of the harmonics.

References

1(1,2)

Tournier J.D., Calamante F. and Connelly A. Robust determination of the fibre orientation distribution in diffusion MRI: Non-negativity constrained super-resolved spherical deconvolution. NeuroImage. 2007;35(4):1459-1472.

2(1,2)

Tournier J-D, Smith R, Raffelt D, Tabbara R, Dhollander T, Pietsch M, et al. MRtrix3: A fast, flexible and open software framework for medical image processing and visualisation. NeuroImage. 2019 Nov 15;202:116-137.

real_sh_tournier_from_index

dipy.reconst.shm.real_sh_tournier_from_index(m, n, theta, phi, legacy=True)

Compute real spherical harmonics as initially defined in Tournier 2007 [1] then updated in MRtrix3 [2], where the real harmonic \(Y^m_n\) is defined to be:

Real(\(Y^m_n\)) * sqrt(2) if m > 0 \(Y^0_n\) if m = 0 Imag(\(Y^|m|_n\)) * sqrt(2) if m < 0

This may take scalar or array arguments. The inputs will be broadcasted against each other.

Parameters
mint |m| <= n

The degree of the harmonic.

nint >= 0

The order of the harmonic.

thetafloat [0, pi]

The polar (colatitudinal) coordinate.

phifloat [0, 2*pi]

The azimuthal (longitudinal) coordinate.

legacy: bool, optional

If true, uses MRtrix 0.2 SH basis definition, where the sqrt(2) factor is omitted. Else, uses the MRtrix 3 definition presented above.

Returns
real_shreal float

The real harmonics \(Y^m_n\) sampled at theta and phi.

References

1(1,2)

Tournier J.D., Calamante F. and Connelly A. Robust determination of the fibre orientation distribution in diffusion MRI: Non-negativity constrained super-resolved spherical deconvolution. NeuroImage. 2007;35(4):1459-1472.

2(1,2)

Tournier J-D, Smith R, Raffelt D, Tabbara R, Dhollander T, Pietsch M, et al. MRtrix3: A fast, flexible and open software framework for medical image processing and visualisation. NeuroImage. 2019 Nov 15;202:116-137.

real_sph_harm

dipy.reconst.shm.real_sph_harm(m, n, theta, phi)

Compute real spherical harmonics.

dipy.reconst.shm.real_sph_harm is deprecated, Please use dipy.reconst.shm.real_sh_descoteaux_from_index instead

  • deprecated from version: 1.3

  • Will raise <class ‘dipy.utils.deprecator.ExpiredDeprecationError’> as of version: 2.0

Where the real harmonic \(Y^m_n\) is defined to be:

Imag(\(Y^m_n\)) * sqrt(2) if m > 0 \(Y^0_n\) if m = 0 Real(\(Y^|m|_n\)) * sqrt(2) if m < 0

This may take scalar or array arguments. The inputs will be broadcasted against each other.

Parameters
mint |m| <= n

The degree of the harmonic.

nint >= 0

The order of the harmonic.

thetafloat [0, pi]

The polar (colatitudinal) coordinate.

phifloat [0, 2*pi]

The azimuthal (longitudinal) coordinate.

Returns
y_mnreal float

The real harmonic \(Y^m_n\) sampled at theta and phi.

See also

scipy.special.sph_harm

real_sym_sh_basis

dipy.reconst.shm.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. The basis functions are defined here the same way as in Descoteaux et al. 2007 [1] where the real harmonic \(Y^m_n\) is defined to be:

Imag(\(Y^m_n\)) * sqrt(2) if m > 0 \(Y^0_n\) if m = 0 Real(\(Y^|m|_n\)) * sqrt(2) if m < 0

This may take scalar or array arguments. The inputs will be broadcasted against each other.

Parameters
sh_orderint

even int > 0, max spherical harmonic order

thetafloat [0, 2*pi]

The azimuthal (longitudinal) coordinate.

phifloat [0, pi]

The polar (colatitudinal) coordinate.

Returns
y_mnreal float

The real harmonic \(Y^m_n\) sampled at theta and phi

marray

The degree of the harmonics.

narray

The order of the harmonics.

References

1

Descoteaux, M., Angelino, E., Fitzgibbons, S. and Deriche, R. Regularized, Fast, and Robust Analytical Q-ball Imaging. Magn. Reson. Med. 2007;58:497-510.

real_sym_sh_mrtrix

dipy.reconst.shm.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(:math:`Y^m_n`)       if m > 0
:math:`Y^0_n`             if m = 0
Imag(:math:`Y^|m|_n`)     if m < 0

This may take scalar or array arguments. The inputs will be broadcasted against each other.

Parameters
sh_orderint

The maximum order or the spherical harmonic basis.

thetafloat [0, pi]

The polar (colatitudinal) coordinate.

phifloat [0, 2*pi]

The azimuthal (longitudinal) coordinate.

Returns
y_mnreal float

The real harmonic \(Y^m_n\) sampled at theta and phi as implemented in mrtrix. Warning: the basis is Tournier et al. 2007 [2]; 2004 [1] is slightly different.

marray

The degree of the harmonics.

narray

The order of the harmonics.

References

1

Tournier J.D., Calamante F., Gadian D.G. and Connelly A. Direct estimation of the fibre orientation density function from diffusion-weighted MRI data using spherical deconvolution. NeuroImage. 2004;23:1176-1185.

2(1,2)

Tournier J.D., Calamante F. and Connelly A. Robust determination of the fibre orientation distribution in diffusion MRI: Non-negativity constrained super-resolved spherical deconvolution. NeuroImage. 2007;35(4):1459-1472.

sf_to_sh

dipy.reconst.shm.sf_to_sh(sf, sphere, sh_order=4, basis_type=None, full_basis=False, legacy=True, smooth=0.0)

Spherical function to spherical harmonics (SH).

Parameters
sfndarray

Values of a function on the given sphere.

sphereSphere

The points on which the sf is defined.

sh_orderint, optional

Maximum SH order in the SH fit. For sh_order, there will be (sh_order + 1) * (sh_order + 2) / 2 SH coefficients for a symmetric basis and (sh_order + 1) * (sh_order + 1) coefficients for a full SH basis.

basis_type{None, ‘tournier07’, ‘descoteaux07’}, optional

None for the default DIPY basis, tournier07 for the Tournier 2007 [R52104e733a02-2]_[R52104e733a02-3]_ basis, descoteaux07 for the Descoteaux 2007 [1] basis, (None defaults to descoteaux07).

full_basis: bool, optional

True for using a SH basis containing even and odd order SH functions. False for using a SH basis consisting only of even order SH functions.

legacy: bool, optional

True to use a legacy basis definition for backward compatibility with previous tournier07 and descoteaux07 implementations.

smoothfloat, optional

Lambda-regularization in the SH fit.

Returns
shndarray

SH coefficients representing the input function.

References

1

Descoteaux, M., Angelino, E., Fitzgibbons, S. and Deriche, R. Regularized, Fast, and Robust Analytical Q-ball Imaging. Magn. Reson. Med. 2007;58:497-510.

2

Tournier J.D., Calamante F. and Connelly A. Robust determination of the fibre orientation distribution in diffusion MRI: Non-negativity constrained super-resolved spherical deconvolution. NeuroImage. 2007;35(4):1459-1472.

3

Tournier J-D, Smith R, Raffelt D, Tabbara R, Dhollander T, Pietsch M, et al. MRtrix3: A fast, flexible and open software framework for medical image processing and visualisation. NeuroImage. 2019 Nov 15;202:116-137.

sh_to_rh

dipy.reconst.shm.sh_to_rh(r_sh, m, n)

Spherical harmonics (SH) to rotational harmonics (RH)

Calculate the rotational harmonic decomposition up to harmonic order n, degree m for an axially and antipodally symmetric function. Note that all m != 0 coefficients will be ignored as axial symmetry is assumed. Hence, there will be (sh_order/2 + 1) non-zero coefficients.

Parameters
r_shndarray (N,)

ndarray of SH coefficients for the single fiber response function. These coefficients must correspond to the real spherical harmonic functions produced by shm.real_sh_descoteaux_from_index.

mndarray (N,)

The degree of the spherical harmonic function associated with each coefficient.

nndarray (N,)

The order of the spherical harmonic function associated with each coefficient.

Returns
r_rhndarray ((sh_order + 1)*(sh_order + 2)/2,)

Rotational harmonics coefficients representing the input r_sh

See also

shm.real_sh_descoteaux_from_index, shm.real_sh_descoteaux

References

1

Tournier, J.D., et al. NeuroImage 2007. Robust determination of the fibre orientation distribution in diffusion MRI: Non-negativity constrained super-resolved spherical deconvolution

sh_to_sf

dipy.reconst.shm.sh_to_sf(sh, sphere, sh_order=4, basis_type=None, full_basis=False, legacy=True)

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

Parameters
shndarray

SH coefficients representing a spherical function.

sphereSphere

The points on which to sample the spherical function.

sh_orderint, optional

Maximum SH order in the SH fit. For sh_order, there will be (sh_order + 1) * (sh_order + 2) / 2 SH coefficients for a symmetric basis and (sh_order + 1) * (sh_order + 1) coefficients for a full SH basis.

basis_type{None, ‘tournier07’, ‘descoteaux07’}, optional

None for the default DIPY basis, tournier07 for the Tournier 2007 [Rc2e19fb985c5-2]_[Rc2e19fb985c5-3]_ basis, descoteaux07 for the Descoteaux 2007 [1] basis, (None defaults to descoteaux07).

full_basis: bool, optional

True to use a SH basis containing even and odd order SH functions. Else, use a SH basis consisting only of even order SH functions.

legacy: bool, optional

True to use a legacy basis definition for backward compatibility with previous tournier07 and descoteaux07 implementations.

Returns
sfndarray

Spherical function values on the sphere.

References

1

Descoteaux, M., Angelino, E., Fitzgibbons, S. and Deriche, R. Regularized, Fast, and Robust Analytical Q-ball Imaging. Magn. Reson. Med. 2007;58:497-510.

2

Tournier J.D., Calamante F. and Connelly A. Robust determination of the fibre orientation distribution in diffusion MRI: Non-negativity constrained super-resolved spherical deconvolution. NeuroImage. 2007;35(4):1459-1472.

3

Tournier J-D, Smith R, Raffelt D, Tabbara R, Dhollander T, Pietsch M, et al. MRtrix3: A fast, flexible and open software framework for medical image processing and visualisation. NeuroImage. 2019 Nov 15;202:116-137.

sh_to_sf_matrix

dipy.reconst.shm.sh_to_sf_matrix(sphere, sh_order=4, basis_type=None, full_basis=False, legacy=True, return_inv=True, smooth=0)

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

Parameters
sphereSphere

The points on which to sample the spherical function.

sh_orderint, optional

Maximum SH order in the SH fit. For sh_order, there will be (sh_order + 1) * (sh_order + 2) / 2 SH coefficients for a symmetric basis and (sh_order + 1) * (sh_order + 1) coefficients for a full SH basis.

basis_type{None, ‘tournier07’, ‘descoteaux07’}, optional

None for the default DIPY basis, tournier07 for the Tournier 2007 [R8e8198e28e5b-2]_[R8e8198e28e5b-3]_ basis, descoteaux07 for the Descoteaux 2007 [1] basis, (None defaults to descoteaux07).

full_basis: bool, optional

If True, uses a SH basis containing even and odd order SH functions. Else, uses a SH basis consisting only of even order SH functions.

legacy: bool, optional

True to use a legacy basis definition for backward compatibility with previous tournier07 and descoteaux07 implementations.

return_invbool, optional

If True then the inverse of the matrix is also returned.

smoothfloat, optional

Lambda-regularization in the SH fit.

Returns
Bndarray

Matrix that transforms spherical harmonics to spherical function sf = np.dot(sh, B).

invBndarray

Inverse of B.

References

1

Descoteaux, M., Angelino, E., Fitzgibbons, S. and Deriche, R. Regularized, Fast, and Robust Analytical Q-ball Imaging. Magn. Reson. Med. 2007;58:497-510.

2

Tournier J.D., Calamante F. and Connelly A. Robust determination of the fibre orientation distribution in diffusion MRI: Non-negativity constrained super-resolved spherical deconvolution. NeuroImage. 2007;35(4):1459-1472.

3

Tournier J-D, Smith R, Raffelt D, Tabbara R, Dhollander T, Pietsch M, et al. MRtrix3: A fast, flexible and open software framework for medical image processing and visualisation. NeuroImage. 2019 Nov 15;202:116-137.

smooth_pinv

dipy.reconst.shm.smooth_pinv(B, L)

Regularized pseudo-inverse

Computes a regularized least square inverse of B

Parameters
Barray_like (n, m)

Matrix to be inverted

Larray_like (n,)
Returns
invndarray (m, n)

regularized least square inverse of B

Notes

In the literature this inverse is often written \((B^{T}B+L^{2})^{-1}B^{T}\). However here this inverse is implemented using the pseudo-inverse because it is more numerically stable than the direct implementation of the matrix product.

sph_harm_ind_list

dipy.reconst.shm.sph_harm_ind_list(sh_order, full_basis=False)

Returns the degree (m) and order (n) of all the symmetric spherical harmonics of degree less then or equal to sh_order. The results, m_list and n_list are kx1 arrays, where k depends on sh_order. They can be passed to real_sh_descoteaux_from_index() and :func:real_sh_tournier_from_index.

Parameters
sh_orderint

even int > 0, max order to return

full_basis: bool, optional

True for SH basis with even and odd order terms

Returns
m_listarray

degrees of even spherical harmonics

n_listarray

orders of even spherical harmonics

See also

shm.real_sh_descoteaux_from_index, shm.real_sh_tournier_from_index

spherical_harmonics

dipy.reconst.shm.spherical_harmonics(m, n, theta, phi, use_scipy=True)

Compute spherical harmonics.

This may take scalar or array arguments. The inputs will be broadcasted against each other.

Parameters
mint |m| <= n

The degree of the harmonic.

nint >= 0

The order of the harmonic.

thetafloat [0, 2*pi]

The azimuthal (longitudinal) coordinate.

phifloat [0, pi]

The polar (colatitudinal) coordinate.

use_scipybool, optional

If True, use scipy implementation.

Returns
y_mncomplex float

The harmonic \(Y^m_n\) sampled at theta and phi.

Notes

This is a faster implementation of scipy.special.sph_harm for scipy version < 0.15.0. For scipy 0.15 and onwards, we use the scipy implementation of the function.

The usual definitions for theta` and `phi used in DIPY are interchanged in the method definition to agree with the definitions in scipy.special.sph_harm, where theta represents the azimuthal coordinate and phi represents the polar coordinate.

Although scipy uses a naming convention where m is the order and n is the degree of the SH, the opposite of DIPY’s, their definition for both parameters is the same as ours, with n >= 0 and |m| <= n.

warn

dipy.reconst.shm.warn(/, message, category=None, stacklevel=1, source=None)

Issue a warning, or maybe ignore it or raise an exception.

Cache

class dipy.reconst.shore.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)

Methods

cache_clear()

Clear the cache.

cache_get(tag, key[, default])

Retrieve a value from the cache.

cache_set(tag, key, value)

Store a value in the cache.

__init__(*args, **kwargs)
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

ShoreFit

class dipy.reconst.shore.ShoreFit(model, shore_coef)

Bases: object

Attributes
shore_coeff

The SHORE coefficients

Methods

fitted_signal()

The fitted signal.

msd()

Calculates the analytical mean squared displacement (MSD) [1]

odf(sphere)

Calculates the ODF for a given discrete sphere.

odf_sh()

Calculates the real analytical ODF in terms of Spherical Harmonics.

pdf(r_points)

Diffusion propagator on a given set of real points.

pdf_grid(gridsize, radius_max)

Applies the analytical FFT on \(S\) to generate the diffusion propagator.

rtop_pdf()

Calculates the analytical return to origin probability (RTOP) from the pdf [1].

rtop_signal()

Calculates the analytical return to origin probability (RTOP) from the signal [1].

__init__(model, shore_coef)

Calculates diffusion properties for a single voxel

Parameters
modelobject,

AnalyticalModel

shore_coef1d ndarray,

shore coefficients

fitted_signal()

The fitted signal.

msd()

Calculates the analytical mean squared displacement (MSD) [1]

..math::
nowrap
begin{equation}

MSD:{DSI}=int_{-infty}^{infty}int_{-infty}^{infty} int_{-infty}^{infty} P(hat{mathbf{r}}) cdot hat{mathbf{r}}^{2} dr_x dr_y dr_z

end{equation}

where \(\hat{\mathbf{r}}\) is a point in the 3D propagator space (see Wu et al. [1]).

References

1(1,2,3)

Wu Y. et al., “Hybrid diffusion imaging”, NeuroImage, vol 36,

  1. 617-629, 2007.

odf(sphere)

Calculates the ODF for a given discrete sphere.

odf_sh()

Calculates the real analytical ODF in terms of Spherical Harmonics.

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

pdf_grid(gridsize, radius_max)

Applies the analytical FFT on \(S\) to generate the diffusion propagator. This is calculated on a discrete 3D grid in order to obtain an EAP similar to that which is obtained with DSI.

Parameters
gridsizeunsigned int

dimension of the propagator grid

radius_maxfloat

maximal radius in which to compute the propagator

Returns
eapndarray

the ensemble average propagator in the 3D grid

rtop_pdf()

Calculates the analytical return to origin probability (RTOP) from the pdf [1].

References

1(1,2)

Ozarslan E. et al., “Mean apparent propagator (MAP) MRI: A novel

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

rtop_signal()

Calculates the analytical return to origin probability (RTOP) from the signal [1].

References

1(1,2)

Ozarslan E. et al., “Mean apparent propagator (MAP) MRI: A novel

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

property shore_coeff

The SHORE coefficients

ShoreModel

class dipy.reconst.shore.ShoreModel(gtab, radial_order=6, zeta=700, lambdaN=1e-08, lambdaL=1e-08, tau=0.025330295910584444, constrain_e0=False, positive_constraint=False, pos_grid=11, pos_radius=0.02, cvxpy_solver=None)

Bases: dipy.reconst.cache.Cache

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

The main idea is to model the diffusion signal as a linear combination of continuous functions \(\phi_i\),

..math::
nowrap
begin{equation}

S(mathbf{q})= sum_{i=0}^I c_{i} phi_{i}(mathbf{q}).

end{equation}

where \(\mathbf{q}\) is the wave vector which corresponds to different gradient directions. Numerous continuous functions \(\phi_i\) can be used to model \(S\). Some are presented in [2,3,4]_.

From the \(c_i\) coefficients, there exist analytical formulae to estimate the ODF, the return to the origin probability (RTOP), the mean square displacement (MSD), amongst others [5].

Notes

The implementation of SHORE depends on CVXPY (http://www.cvxpy.org/).

References

1(1,2)

Ozarslan E. et al., “Simple harmonic oscillator based reconstruction and estimation for one-dimensional q-space magnetic resonance 1D-SHORE)”, Proc Intl Soc Mag Reson Med, vol. 16, p. 35., 2008.

2

Merlet S. et al., “Continuous diffusion signal, EAP and ODF estimation via Compressive Sensing in diffusion MRI”, Medical Image Analysis, 2013.

3

Rathi Y. et al., “Sparse multi-shell diffusion imaging”, MICCAI, 2011.

4

Cheng J. et al., “Theoretical Analysis and eapactical Insights on EAP Estimation via a Unified HARDI Framework”, MICCAI workshop on Computational Diffusion MRI, 2011.

5

Ozarslan E. et al., “Mean apparent propagator (MAP) MRI: A novel diffusion imaging method for mapping tissue microstructure”, NeuroImage, 2013.

Methods

cache_clear()

Clear the cache.

cache_get(tag, key[, default])

Retrieve a value from the cache.

cache_set(tag, key, value)

Store a value in the cache.

fit(data[, mask])

Fit method for every voxel in data

__init__(gtab, radial_order=6, zeta=700, lambdaN=1e-08, lambdaL=1e-08, tau=0.025330295910584444, constrain_e0=False, positive_constraint=False, pos_grid=11, pos_radius=0.02, cvxpy_solver=None)

Analytical and continuous modeling of the diffusion signal with respect to the SHORE basis [1,2]_. This implementation is a modification of SHORE presented in [1]. The modification was made to obtain the same ordering of the basis presented in [2,3]_.

The main idea is to model the diffusion signal as a linear combination of continuous functions \(\phi_i\),

..math::
nowrap
begin{equation}

S(mathbf{q})= sum_{i=0}^I c_{i} phi_{i}(mathbf{q}).

end{equation}

where \(\mathbf{q}\) is the wave vector which corresponds to different gradient directions.

From the \(c_i\) coefficients, there exists an analytical formula to estimate the ODF.

Parameters
gtabGradientTable,

gradient directions and bvalues container class

radial_orderunsigned int,

an even integer that represent the order of the basis

zetaunsigned int,

scale factor

lambdaNfloat,

radial regularisation constant

lambdaLfloat,

angular regularisation constant

taufloat,

diffusion time. By default the value that makes q equal to the square root of the b-value.

constrain_e0bool,

Constrain the optimization such that E(0) = 1.

positive_constraintbool,

Constrain the propagator to be positive.

pos_gridint,

Grid that define the points of the EAP in which we want to enforce positivity.

pos_radiusfloat,

Radius of the grid of the EAP in which enforce positivity in millimeters. By default 20e-03 mm.

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

1

Merlet S. et al., “Continuous diffusion signal, EAP and

ODF estimation via Compressive Sensing in diffusion MRI”, Medical Image Analysis, 2013.

2

Cheng J. et al., “Theoretical Analysis and Practical Insights

on EAP Estimation via a Unified HARDI Framework”, MICCAI workshop on Computational Diffusion MRI, 2011.

3

Ozarslan E. et al., “Mean apparent propagator (MAP) MRI: A novel diffusion imaging method for mapping tissue microstructure”, NeuroImage, 2013.

Examples

In this example, where the data, gradient table and sphere tessellation used for reconstruction are provided, we model the diffusion signal with respect to the SHORE basis and compute the real and analytical ODF.

>>> import warnings
>>> from dipy.data import get_isbi2013_2shell_gtab, default_sphere
>>> from dipy.sims.voxel import sticks_and_ball
>>> from dipy.reconst.shm import descoteaux07_legacy_msg
>>> from dipy.reconst.shore import ShoreModel
>>> gtab = get_isbi2013_2shell_gtab()
>>> data, golden_directions = sticks_and_ball(
...    gtab, d=0.0015, S0=1., angles=[(0, 0), (90, 0)],
...    fractions=[50, 50], snr=None)
...
>>> radial_order = 4
>>> zeta = 700
>>> asm = ShoreModel(gtab, radial_order=radial_order, zeta=zeta,
...                  lambdaN=1e-8, lambdaL=1e-8)
>>> with warnings.catch_warnings():
...     warnings.filterwarnings(
...         "ignore", message=descoteaux07_legacy_msg,
...         category=PendingDeprecationWarning)
...     asmfit = asm.fit(data)
...     odf = asmfit.odf(default_sphere)
fit(data, mask=None)

Fit method for every voxel in data

Version

class dipy.reconst.shore.Version(version: str)

Bases: packaging.version._BaseVersion

Attributes
base_version
dev
epoch
is_devrelease
is_postrelease
is_prerelease
local
major
micro
minor
post
pre
public
release
__init__(version: str) None
property base_version: str
property dev: Optional[int]
property epoch: int
property is_devrelease: bool
property is_postrelease: bool
property is_prerelease: bool
property local: Optional[str]
property major: int
property micro: int
property minor: int
property post: Optional[int]
property pre: Optional[Tuple[str, int]]
property public: str
property release: Tuple[int, ...]

cart2sphere

dipy.reconst.shore.cart2sphere(x, y, z)

Return angles for Cartesian 3D coordinates x, y, and z

See doc for sphere2cart for angle conventions and derivation of the formulae.

\(0\le\theta\mathrm{(theta)}\le\pi\) and \(-\pi\le\phi\mathrm{(phi)}\le\pi\)

Parameters
xarray_like

x coordinate in Cartesian space

yarray_like

y coordinate in Cartesian space

zarray_like

z coordinate

Returns
rarray

radius

thetaarray

inclination (polar) angle

phiarray

azimuth angle

create_rspace

dipy.reconst.shore.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
vecsarray, shape (N,3)

positions of the pdf points in a 3D matrix

tabarray, shape (N,3)

real space points in which calculates the pdf

factorial

dipy.reconst.shore.factorial(x, /)

Find x!.

Raise a ValueError if x is negative or non-integral.

genlaguerre

dipy.reconst.shore.genlaguerre(n, alpha, monic=False)

Generalized (associated) Laguerre polynomial.

Defined to be the solution of

\[x\frac{d^2}{dx^2}L_n^{(\alpha)} + (\alpha + 1 - x)\frac{d}{dx}L_n^{(\alpha)} + nL_n^{(\alpha)} = 0,\]

where \(\alpha > -1\); \(L_n^{(\alpha)}\) is a polynomial of degree \(n\).

Parameters
nint

Degree of the polynomial.

alphafloat

Parameter, must be greater than -1.

monicbool, optional

If True, scale the leading coefficient to be 1. Default is False.

Returns
Lorthopoly1d

Generalized Laguerre polynomial.

See also

laguerre

Laguerre polynomial.

Notes

For fixed \(\alpha\), the polynomials \(L_n^{(\alpha)}\) are orthogonal over \([0, \infty)\) with weight function \(e^{-x}x^\alpha\).

The Laguerre polynomials are the special case where \(\alpha = 0\).

l_shore

dipy.reconst.shore.l_shore(radial_order)

Returns the angular regularisation matrix for SHORE basis

multi_voxel_fit

dipy.reconst.shore.multi_voxel_fit(single_voxel_fit)

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

n_shore

dipy.reconst.shore.n_shore(radial_order)

Returns the angular regularisation matrix for SHORE basis

optional_package

dipy.reconst.shore.optional_package(name, trip_msg=None)

Return package-like thing and module setup for package name

Parameters
namestr

package name

trip_msgNone or str

message to give when someone tries to use the return package, but we could not import it, and have returned a TripWire object instead. Default message if None.

Returns
pkg_likemodule or TripWire instance

If we can import the package, return it. Otherwise return an object raising an error when accessed

have_pkgbool

True if import for package was successful, false otherwise

module_setupfunction

callable usually set as setup_module in calling namespace, to allow skipping tests.

Examples

Typical use would be something like this at the top of a module using an optional package:

>>> from dipy.utils.optpkg import optional_package
>>> pkg, have_pkg, setup_module = optional_package('not_a_package')

Of course in this case the package doesn’t exist, and so, in the module:

>>> have_pkg
False

and

>>> pkg.some_function() 
Traceback (most recent call last):
    ...
TripWireError: We need package not_a_package for these functions, but
``import not_a_package`` raised an ImportError

If the module does exist - we get the module

>>> pkg, _, _ = optional_package('os')
>>> hasattr(pkg, 'path')
True

Or a submodule if that’s what we asked for

>>> subpkg, _, _ = optional_package('os.path')
>>> hasattr(subpkg, 'dirname')
True

real_sh_descoteaux_from_index

dipy.reconst.shore.real_sh_descoteaux_from_index(m, n, theta, phi, legacy=True)

Compute real spherical harmonics as in Descoteaux et al. 2007 [Rf0cd5775fa0d-1], where the real harmonic \(Y^m_n\) is defined to be:

Imag(\(Y^m_n\)) * sqrt(2) if m > 0 \(Y^0_n\) if m = 0 Real(\(Y^m_n\)) * sqrt(2) if m < 0

This may take scalar or array arguments. The inputs will be broadcasted against each other.

Parameters
mint |m| <= n

The degree of the harmonic.

nint >= 0

The order of the harmonic.

thetafloat [0, pi]

The polar (colatitudinal) coordinate.

phifloat [0, 2*pi]

The azimuthal (longitudinal) coordinate.

legacy: bool, optional

If true, uses DIPY’s legacy descoteaux07 implementation (where |m| is used for m < 0). Else, implements the basis as defined in Descoteaux et al. 2007 (without the absolute value).

Returns
real_shreal float

The real harmonic \(Y^m_n\) sampled at theta and phi.

shore_indices

dipy.reconst.shore.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}(q\textbf{u})=\sum_{l=0, even}^{N_{max}}
                                \sum_{n=l}^{(N_{max}+l)/2}
                                \sum_{m=-l}^l c_{nlm}
                                \phi_{nlm}(q\textbf{u})
    \end{equation}

where \(\phi_{nlm}\) is ..math:

:nowrap:
    \begin{equation}
        \phi_{nlm}^{SHORE}(q\textbf{u})=\Biggl[\dfrac{2(n-l)!}
            {\zeta^{3/2} \Gamma(n+3/2)} \Biggr]^{1/2}
            \Biggl(\dfrac{q^2}{\zeta}\Biggr)^{l/2}
            exp\Biggl(\dfrac{-q^2}{2\zeta}\Biggr)
            L^{l+1/2}_{n-l} \Biggl(\dfrac{q^2}{\zeta}\Biggr)
            Y_l^m(\textbf{u}).
    \end{equation}
Parameters
radial_orderunsigned int

an even integer that represent the maximal order of the basis

indexunsigned int

index of the coefficients, start from 0

Returns
nunsigned int

the index n of the modified shore basis

lunsigned int

the index l of the modified shore basis

munsigned int

the index m of the modified shore basis

shore_matrix

dipy.reconst.shore.shore_matrix(radial_order, zeta, gtab, tau=0.025330295910584444)

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}(q\textbf{u})=\Biggl[\dfrac{2(n-l)!}
            {\zeta^{3/2} \Gamma(n+3/2)} \Biggr]^{1/2}
            \Biggl(\dfrac{q^2}{\zeta}\Biggr)^{l/2}
            exp\Biggl(\dfrac{-q^2}{2\zeta}\Biggr)
            L^{l+1/2}_{n-l} \Biggl(\dfrac{q^2}{\zeta}\Biggr)
            Y_l^m(\textbf{u}).
    \end{equation}
Parameters
radial_orderunsigned int,

an even integer that represent the order of the basis

zetaunsigned int,

scale factor

gtabGradientTable,

gradient directions and bvalues container class

taufloat,

diffusion time. By default the value that makes q=sqrt(b).

References

1(1,2)

Merlet S. et al., “Continuous diffusion signal, EAP and

ODF estimation via Compressive Sensing in diffusion MRI”, Medical Image Analysis, 2013.

shore_matrix_odf

dipy.reconst.shore.shore_matrix_odf(radial_order, zeta, sphere_vertices)

Compute the SHORE ODF matrix [1]

Parameters
radial_orderunsigned int,

an even integer that represent the order of the basis

zetaunsigned int,

scale factor

sphere_verticesarray, shape (N,3)

vertices of the odf sphere

References

1(1,2)

Merlet S. et al., “Continuous diffusion signal, EAP and

ODF estimation via Compressive Sensing in diffusion MRI”, Medical Image Analysis, 2013.

shore_matrix_pdf

dipy.reconst.shore.shore_matrix_pdf(radial_order, zeta, rtab)

Compute the SHORE propagator matrix [1]

Parameters
radial_orderunsigned int,

an even integer that represent the order of the basis

zetaunsigned int,

scale factor

rtabarray, shape (N,3)

real space points in which calculates the pdf

References

1(1,2)

Merlet S. et al., “Continuous diffusion signal, EAP and

ODF estimation via Compressive Sensing in diffusion MRI”, Medical Image Analysis, 2013.

shore_order

dipy.reconst.shore.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.

Parameters
nunsigned int

the index n of the modified shore basis

lunsigned int

the index l of the modified shore basis

munsigned int

the index m of the modified shore basis

Returns
radial_orderunsigned int

an even integer that represent the maximal order of the basis

indexunsigned int

index of the coefficient correspondig to (n,l,m), start from 0

warn

dipy.reconst.shore.warn(/, message, category=None, stacklevel=1, source=None)

Issue a warning, or maybe ignore it or raise an exception.

dki_design_matrix

dipy.reconst.utils.dki_design_matrix(gtab)

Construct B design matrix for DKI.

Parameters
gtabGradientTable

Measurement directions.

Returns
Barray (N, 22)

Design matrix or B matrix for the DKI model B[j, :] = (Bxx, Bxy, Bzz, Bxz, Byz, Bzz,

Bxxxx, Byyyy, Bzzzz, Bxxxy, Bxxxz, Bxyyy, Byyyz, Bxzzz, Byzzz, Bxxyy, Bxxzz, Byyzz, Bxxyz, Bxyyz, Bxyzz, BlogS0)

vec_val_vect

dipy.reconst.vec_val_sum.vec_val_vect()

Vectorize vecs.diag(vals).`vecs`.T for last 2 dimensions of vecs

Parameters
vecsshape (…, M, N) array

containing tensor in last two dimensions; M, N usually equal to (3, 3)

valsshape (…, N) array

diagonal values carried in last dimension, ... shape above must match that for vecs

Returns
resshape (…, M, M) array

For all the dimensions ellided by ..., loops to get (M, N) vec matrix, and (N,) vals vector, and calculates vec.dot(np.diag(val).dot(vec.T).

Raises
ValueErrornon-matching ... dimensions of vecs, vals
ValueErrornon-matching N dimensions of vecs, vals

Examples

Make a 3D array where the first dimension is only 1

>>> vecs = np.arange(9).reshape((1, 3, 3))
>>> vals = np.arange(3).reshape((1, 3))
>>> vec_val_vect(vecs, vals)
array([[[   9.,   24.,   39.],
        [  24.,   66.,  108.],
        [  39.,  108.,  177.]]])

That’s the same as the 2D case (apart from the float casting):

>>> vecs = np.arange(9).reshape((3, 3))
>>> vals = np.arange(3)
>>> np.dot(vecs, np.dot(np.diag(vals), vecs.T))
array([[  9,  24,  39],
       [ 24,  66, 108],
       [ 39, 108, 177]])