reconst
reconst.base
reconst.benchmarks
reconst.benchmarks.bench_bounding_box
reconst.benchmarks.bench_csd
reconst.benchmarks.bench_peaks
reconst.benchmarks.bench_squash
reconst.benchmarks.bench_vec_val_sum
reconst.cache
reconst.cross_validation
reconst.csdeconv
reconst.dki
reconst.dki_micro
reconst.dsi
reconst.dti
reconst.forecast
reconst.fwdti
reconst.gqi
reconst.interpolate
reconst.ivim
reconst.mapmri
reconst.multi_voxel
reconst.odf
reconst.peaks
reconst.qtdmri
reconst.sfm
reconst.shm
reconst.shore
reconst.utils
ReconstFit
ReconstModel
ConstrainedSphericalDeconvModel
GradientTable
Cache
range
AxSymShResponse
ConstrainedSDTModel
ConstrainedSphericalDeconvModel
SphHarmFit
SphHarmModel
TensorModel
range
DiffusionKurtosisFit
DiffusionKurtosisModel
ReconstModel
TensorFit
range
DiffusionKurtosisFit
DiffusionKurtosisModel
KurtosisMicrostructuralFit
KurtosisMicrostructureModel
Cache
DiffusionSpectrumDeconvFit
DiffusionSpectrumDeconvModel
DiffusionSpectrumFit
DiffusionSpectrumModel
OdfFit
OdfModel
ReconstModel
TensorFit
TensorModel
range
Cache
ForecastFit
ForecastModel
OdfFit
OdfModel
FreeWaterTensorFit
FreeWaterTensorModel
ReconstModel
TensorFit
Cache
GeneralizedQSamplingFit
GeneralizedQSamplingModel
OdfFit
OdfModel
Interpolator
NearestNeighborInterpolator
OutsideImage
TriLinearInterpolator
IvimFit
IvimModelLM
IvimModelVP
LooseVersion
ReconstModel
Cache
MapmriFit
MapmriModel
Optimizer
ReconstFit
ReconstModel
CallableArray
MultiVoxelFit
ReconstFit
OdfFit
OdfModel
ReconstFit
ReconstModel
InTemporaryDirectory
PeaksAndMetrics
PeaksAndMetricsDirectionGetter
Sphere
repeat
xrange
Cache
QtdmriFit
QtdmriModel
Cache
ExponentialIsotropicFit
ExponentialIsotropicModel
IsotropicFit
IsotropicModel
ReconstFit
ReconstModel
SparseFascicleFit
SparseFascicleModel
Cache
CsaOdfModel
LooseVersion
OdfFit
OdfModel
OpdtModel
QballBaseModel
QballModel
ResidualBootstrapWrapper
SphHarmFit
SphHarmModel
Cache
ShoreFit
ShoreModel
reconst
bench |
Run benchmarks for module using nose. |
test |
Run tests for module using nose. |
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 |
reconst.benchmarks.bench_bounding_box
bench_bounding_box () |
|
bounding_box (vol) |
Compute the bounding box of nonzero intensity voxels in the volume. |
measure (code_str[, times, label]) |
Return elapsed time for executing code in the namespace of the caller. |
reconst.benchmarks.bench_csd
ConstrainedSphericalDeconvModel (gtab, response) |
Methods |
GradientTable (gradients[, big_delta, …]) |
Diffusion gradient information |
bench_csdeconv ([center, width]) |
|
num_grad (gtab) |
|
read_stanford_labels () |
Read stanford hardi data and label map |
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 () |
|
get_sphere ([name]) |
provide triangulated spheres |
local_maxima |
Local maxima of a function evaluated on a discrete set of points. |
measure (code_str[, times, label]) |
Return elapsed time for executing code in the namespace of the caller. |
unique_edges (faces[, return_mapping]) |
Extract all unique edges from given triangular faces. |
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 |
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. |
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. |
randn (d0, d1, …, dn) |
Return a sample (or samples) from the “standard normal” distribution. |
vec_val_vect |
Vectorize vecs.diag(vals).`vecs`.T for last 2 dimensions of vecs |
with_einsum (f) |
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. |
reconst.cross_validation
Cross-validation analysis of diffusion models
range (stop) |
range(start, stop[, step]) -> range object |
coeff_of_determination (data, model[, axis]) |
Calculate the coefficient of determination for a model prediction, relative |
kfold_xval (model, data, folds, *model_args, …) |
Perform k-fold cross-validation to generate out-of-sample predictions for each measurement. |
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 |
range (stop) |
range(start, stop[, step]) -> range object |
auto_response (gtab, data[, roi_center, …]) |
Automatic estimation of response function using FA. |
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] |
estimate_response (gtab, evals, S0) |
Estimate single fiber response function |
fa_inferior (FA, fa_thr) |
Check that the FA is lower than the FA threshold |
fa_superior (FA, fa_thr) |
Check that the FA is greater than the FA threshold |
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]) |
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. |
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_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 |
recursive_response (gtab, data[, mask, …]) |
Recursive calibration of response function using peak threshold |
response_from_mask (gtab, data, mask) |
Estimate the response function from a given mask. |
sh_to_rh (r_sh, m, n) |
Spherical harmonics (SH) to rotational harmonics (RH) |
single_tensor (gtab[, S0, evals, evecs, snr]) |
Simulated Q-space signal with a single tensor. |
sph_harm_ind_list (sh_order) |
Returns the degree (n) and order (m) 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 |
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]) |
|
||
range (stop) |
range(start, stop[, step]) -> range object | ||
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. | ||
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) |
Constructs 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_sphere ([name]) |
provide triangulated spheres | ||
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 [1]. | ||
ndindex (shape) |
An N-dimensional iterator object to index arrays. | ||
ols_fit_dki (design_matrix, data) |
Computes ordinary least squares (OLS) fit to calculate the diffusion tensor and kurtosis tensor using a linear regression diffusion kurtosis model [1]. | ||
radial_kurtosis (dki_params[, min_kurtosis, …]) |
Radial Kurtosis (RK) of a diffusion kurtosis tensor [1]. | ||
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 weighted linear least squares (WLS) fit to calculate the diffusion tensor and kurtosis tensor using a weighted linear regression diffusion kurtosis model [1]. |
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 |
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. |
reconst.dti
Classes and functions for fitting tensors
ReconstModel (gtab) |
Abstract class for signal reconstruction models | ||
TensorFit (model, model_params[, model_S0]) |
|
||
TensorModel (gtab[, fit_method, return_S0_hat]) |
Diffusion Tensor | ||
range (stop) |
range(start, stop[, step]) -> range object | ||
apparent_diffusion_coef (q_form, sphere) |
Calculate the apparent diffusion coefficient (ADC) in each direction of a | ||
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. | ||
eigh (a[, UPLO]) |
Iterate over np.linalg.eigh if it doesn’t support vectorized operation | ||
fractional_anisotropy (evals[, axis]) |
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 [Rd0568a744381-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 tensor params using non-linear least-squares. | ||
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 [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 [Chang2005] 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]. |
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) |
|
||
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 | ||
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 | ||
get_sphere ([name]) |
provide triangulated spheres | ||
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_sph_harm (m, n, theta, phi) |
Compute real spherical harmonics. | ||
rho_matrix (sh_order, vecs) |
Compute the SH matrix \(\rho\) | ||
warn |
Issue a warning, or maybe ignore it or raise an exception. |
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]) |
|
||
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) |
Perfoms 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. |
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 |
gfa (samples) |
The general fractional anisotropy of a function evaluated on the unit sphere |
local_maxima |
Local maxima of a function evaluated on a discrete set of points. |
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 |
remove_similar_vertices |
Remove vertices that are less than theta degrees from any other |
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 |
reconst.interpolate
Interpolators wrap arrays to allow the array to be indexed in continuous coordinates
This module uses the trackvis coordinate system, for more information about this coordinate system please see dipy.tracking.utils The following modules also use this coordinate system: dipy.tracking.utils dipy.tracking.integration dipy.reconst.interpolate
Interpolator (data, voxel_size) |
Class to be subclassed by different interpolator types |
NearestNeighborInterpolator (data, voxel_size) |
Interpolates data using nearest neighbor interpolation |
OutsideImage |
|
TriLinearInterpolator (data, voxel_size) |
Interpolates data using trilinear interpolation |
array (object[, dtype, copy, order, subok, ndmin]) |
Create an array. |
trilinear_interp |
Interpolates vector from 4D data at 3D point given by index |
reconst.ivim
Classes and functions for fitting ivim model
IvimFit (model, model_params) |
|
||
IvimModelLM (gtab[, split_b_D, split_b_S0, …]) |
Ivim model | ||
IvimModelVP (gtab[, maxiter, xtol]) |
Methods |
||
LooseVersion ([vstring]) |
Version numbering for anarchists and software realists. | ||
ReconstModel (gtab) |
Abstract class for signal reconstruction models | ||
IvimModel (gtab[, fit_method]) |
Selector function to switch between the 2-stage Levenberg-Marquardt based NLLS fitting method (also containing the linear fit): LM and the Variable Projections based fitting method: VarPro. | ||
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 Levenberg-Marquardt based NLLS fitting method (also containing the linear fit): LM 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 |
reconst.mapmri
Cache |
Cache values based on a key object (such as a sphere or gradient table). | ||
MapmriFit (model, mapmri_coef, mu, R, lopt[, …]) |
|
||
MapmriModel (gtab[, radial_order, …]) |
Mean Apparent Propagator MRI (MAPMRI) [1] of the diffusion signal. | ||
Optimizer (fun, x0[, args, method, jac, …]) |
|
||
ReconstFit (model, data) |
Abstract class which holds the fit result of ReconstModel | ||
ReconstModel (gtab) |
Abstract class for signal reconstruction models | ||
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) |
Generates 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, …) |
Puts 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 |
factorial(x) -> Integral | ||
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_sph_harm (m, n, theta, phi) |
Compute real spherical harmonics. | ||
sfactorial (n[, exact]) |
The factorial of a number or array of numbers. | ||
sph_harm_ind_list (sh_order) |
Returns the degree (n) and order (m) of all the symmetric spherical harmonics of degree less then or equal to sh_order. | ||
warn |
Issue a warning, or maybe ignore it or raise an exception. |
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 |
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. |
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 |
reconst.peaks
InTemporaryDirectory ([suffix, prefix, dir]) |
Create, return, and change directory to a temporary directory | ||
PeaksAndMetrics |
|
||
PeaksAndMetricsDirectionGetter |
Deterministic Direction Getter based on peak directions. | ||
Sphere ([x, y, z, theta, phi, xyz, faces, edges]) |
Points on the unit sphere. | ||
repeat (object [,times]) |
for the specified number of times. | ||
xrange |
alias of builtins.range |
||
Pool |
Returns a process pool object | ||
cpu_count |
Returns the number of CPUs in the system | ||
gfa (samples) |
The general fractional anisotropy of a function evaluated on the unit sphere | ||
local_maxima |
Local maxima of a function evaluated on a discrete set of points. | ||
ndindex (shape) |
An N-dimensional iterator object to index arrays. | ||
peak_directions (odf, sphere[, …]) |
Get the directions of odf peaks. | ||
peak_directions_nl (sphere_eval[, …]) |
Non Linear Direction Finder. | ||
peaks_from_model (model, data, sphere, …[, …]) |
Fit the model to data and computes peaks and metrics | ||
remove_similar_vertices |
Remove vertices that are less than theta degrees from any other | ||
reshape_peaks_for_visualization (peaks) |
Reshape peaks for visualization. | ||
search_descending |
i in descending array a so a[i] < a[0] * relative_threshold | ||
sh_to_sf_matrix (sphere, sh_order[, …]) |
Matrix that transforms Spherical harmonics (SH) to spherical function (SF). | ||
warn |
Issue a warning, or maybe ignore it or raise an exception. |
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\). |
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[, dtype]) |
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_sph_harm (m, n, theta, phi) |
Compute real spherical harmonics. |
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 |
Issue a warning, or maybe ignore it or raise an exception. |
reconst.sfm
The Sparse Fascicle Model.
This is an implementation of the sparse fascicle model described in [R204bb22f26e5-Rokem2015]. The multi b-value version of this model is described in [R204bb22f26e5-Rokem2014].
[R204bb22f26e5-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 |
[R204bb22f26e5-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. |
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. |
nanmean (a[, axis, dtype, out, keepdims]) |
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 |
reconst.shm
Tools for using spherical harmonic models to fit diffusion data
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. |
LooseVersion ([vstring]) |
Version numbering for anarchists and software realists. |
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, …]) |
Calculates 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) |
Calculate the maximal harmonic order, given that you know the |
cart2sphere (x, y, z) |
Return angles for Cartesian 3D coordinates x, y, and z |
concatenate ((a1, a2, …)[, axis, out]) |
Join a sequence of arrays along an existing axis. |
diag (v[, k]) |
Extract a diagonal or construct a diagonal array. |
diff (a[, n, axis]) |
Calculate the n-th discrete difference along the given axis. |
dot (a, b[, out]) |
Dot product of two arrays. |
empty (shape[, dtype, order]) |
Return a new array of given shape and type, without initializing entries. |
eye (N[, M, k, dtype, order]) |
Return a 2-D array with ones on the diagonal and zeros elsewhere. |
forward_sdeconv_mat (r_rh, n) |
Build forward spherical deconvolution matrix |
gen_dirac (m, n, theta, phi) |
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 |
lpn (n, z) |
Legendre function of the first kind. |
normalize_data (data, where_b0[, min_signal, out]) |
Normalizes the data with respect to the mean b0 |
order_from_ncoef (ncoef) |
Given a number n of coefficients, calculate back the sh_order |
pinv (a[, rcond]) |
Compute the (Moore-Penrose) pseudo-inverse of a matrix. |
randint (low[, high, size, dtype]) |
Return random integers from low (inclusive) to high (exclusive). |
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) |
Compute real spherical harmonics as in Tournier 2007 [2], where the real harmonic \(Y^m_n\) is defined to be. |
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) |
Returns the degree (n) and order (m) of all the symmetric spherical harmonics of degree less then or equal to sh_order. |
spherical_harmonics (m, n, theta, phi) |
Compute spherical harmonics |
svd (a[, full_matrices, compute_uv]) |
Singular Value Decomposition. |
unique (ar[, return_index, return_inverse, …]) |
Find the unique elements of an array. |
reconst.shore
Cache |
Cache values based on a key object (such as a sphere or gradient table). | ||
ShoreFit (model, shore_coef) |
|
||
ShoreModel (gtab[, radial_order, zeta, …]) |
Simple Harmonic Oscillator based Reconstruction and Estimation (SHORE) [1] of the diffusion signal. | ||
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_sph_harm (m, n, theta, phi) |
Compute real spherical harmonics. | ||
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 |
Issue a warning, or maybe ignore it or raise an exception. |
reconst.utils
dki_design_matrix (gtab) |
Constructs B design matrix for DKI |
dipy.reconst.
bench
(label='fast', verbose=1, extra_argv=None)Run benchmarks for module using nose.
Parameters: |
|
---|---|
Returns: |
|
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
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: |
|
---|---|
Returns: |
|
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
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.
ReconstModel
dipy.reconst.base.
ReconstModel
(gtab)Bases: object
Abstract class for signal reconstruction models
Methods
fit |
dipy.reconst.benchmarks.bench_bounding_box.
bounding_box
(vol)Compute the bounding box of nonzero intensity voxels in the volume.
Parameters: |
|
---|---|
Returns: |
|
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: |
|
---|---|
Returns: |
|
Examples
>>> 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
dipy.reconst.benchmarks.bench_csd.
ConstrainedSphericalDeconvModel
(gtab, response, reg_sphere=None, sh_order=8, lambda_=1, 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 |
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)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: |
|
---|
References
[1] | (1, 2, 3, 4, 5, 6) 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] | (1, 2) Descoteaux, M., et al. IEEE TMI 2009. Deterministic and Probabilistic Tractography Based on Complex Fibre Orientation Distributions |
[3] | (1, 2) C^ot’e, 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 |
predict
(sh_coeff, gtab=None, S0=1.0)Compute a signal prediction given spherical harmonic coefficients for the provided GradientTable class instance.
Parameters: |
|
---|---|
Returns: |
|
GradientTable
dipy.reconst.benchmarks.bench_csd.
GradientTable
(gradients, big_delta=None, small_delta=None, b0_threshold=50)Bases: object
Diffusion gradient information
Parameters: |
|
---|
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: |
|
---|
Methods
b0s_mask | |
bvals | |
bvecs | |
gradient_strength | |
qvals | |
tau |
dipy.reconst.benchmarks.bench_peaks.
get_sphere
(name='symmetric362')provide triangulated spheres
Parameters: |
|
---|---|
Returns: |
|
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"
dipy.reconst.benchmarks.bench_peaks.
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: |
|
---|---|
Returns: |
|
See also
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: |
|
---|---|
Returns: |
|
Examples
>>> 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
dipy.reconst.benchmarks.bench_peaks.
unique_edges
(faces, return_mapping=False)Extract all unique edges from given triangular faces.
Parameters: |
|
---|---|
Returns: |
|
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: |
|
---|---|
Returns: |
|
Examples
>>> 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
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: |
|
---|
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)
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:
Parameters: |
|
---|---|
Returns: |
|
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')
dipy.reconst.benchmarks.bench_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:
S
. Returns an array with shape obj_arr.shape + S
Parameters: |
|
---|---|
Returns: |
|
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')
dipy.reconst.benchmarks.bench_squash.
reduce
(function, sequence[, initial]) → valueApply 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.
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: |
|
---|---|
Returns: |
|
Examples
>>> 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
dipy.reconst.benchmarks.bench_vec_val_sum.
randn
(d0, d1, ..., dn)Return a sample (or samples) from the “standard normal” distribution.
If positive, int_like or int-convertible arguments are provided,
randn generates an array of shape (d0, d1, ..., dn)
, filled
with random floats sampled from a univariate “normal” (Gaussian)
distribution of mean 0 and variance 1 (if any of the \(d_i\) are
floats, they are first converted to integers by truncation). A single
float randomly sampled from the distribution is returned if no
argument is provided.
This is a convenience function. If you want an interface that takes a tuple as the first argument, use numpy.random.standard_normal instead.
Parameters: |
|
---|---|
Returns: |
|
See also
standard_normal
Notes
For random samples from \(N(\mu, \sigma^2)\), use:
sigma * np.random.randn(...) + mu
Examples
>>> np.random.randn()
2.1923875335537315 #random
Two-by-four array of samples from N(3, 6.25):
>>> 2.5 * np.random.randn(2, 4) + 3
array([[-4.49401501, 4.00950034, -1.81814867, 7.29718677], #random
[ 0.39924804, 4.68456316, 4.99394529, 4.84057254]]) #random
dipy.reconst.benchmarks.bench_vec_val_sum.
vec_val_vect
()Vectorize vecs.diag(vals).`vecs`.T for last 2 dimensions of vecs
Parameters: |
|
---|---|
Returns: |
|
Raises: |
|
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
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. |
cache_get
(tag, key, default=None)Retrieve a value from the cache.
Parameters: |
|
---|---|
Returns: |
|
cache_set
(tag, key, value)Store a value in the cache.
Parameters: |
|
---|
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
dipy.reconst.cache.
auto_attr
(func)Decorator to create OneTimeProperty attributes.
Parameters: |
|
---|
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
range
dipy.reconst.cross_validation.
range
(stop) → range objectBases: object
range(start, stop[, step]) -> range object
Return an object that produces a sequence of integers from start (inclusive) to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, …, j-1. start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3. These are exactly the valid indices for a list of 4 elements. When step is given, it specifies the increment (or decrement).
Attributes: |
|
---|
Methods
count (value) |
|
index (value, [start, [stop]]) |
Raise ValueError if the value is not present. |
dipy.reconst.cross_validation.
coeff_of_determination
(data, model, axis=-1)Calculate the coefficient of determination for a model prediction, relative to data.
Parameters: |
|
---|---|
Returns: |
|
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).
dipy.reconst.cross_validation.
kfold_xval
(model, data, folds, *model_args, **model_kwargs)Perform k-fold cross-validation to generate out-of-sample predictions for each measurement.
Parameters: |
|
---|
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
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).
Methods
basis (sphere) |
A basis that maps the response coefficients onto a sphere. |
on_sphere (sphere) |
Evaluates the response function on sphere. |
ConstrainedSDTModel
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: |
|
---|
References
[1] | (1, 2, 3) Descoteaux, M., et al. IEEE TMI 2009. Deterministic and Probabilistic Tractography Based on Complex Fibre Orientation Distributions. |
ConstrainedSphericalDeconvModel
dipy.reconst.csdeconv.
ConstrainedSphericalDeconvModel
(gtab, response, reg_sphere=None, sh_order=8, lambda_=1, 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 |
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)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: |
|
---|
References
[1] | (1, 2, 3, 4, 5, 6) 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] | (1, 2) Descoteaux, M., et al. IEEE TMI 2009. Deterministic and Probabilistic Tractography Based on Complex Fibre Orientation Distributions |
[3] | (1, 2) C^ot’e, 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 |
predict
(sh_coeff, gtab=None, S0=1.0)Compute a signal prediction given spherical harmonic coefficients for the provided GradientTable class instance.
Parameters: |
|
---|---|
Returns: |
|
SphHarmFit
dipy.reconst.csdeconv.
SphHarmFit
(model, shm_coef, mask)Bases: dipy.reconst.odf.OdfFit
Diffusion data fit to a spherical harmonic model
Attributes: |
|
---|
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 |
odf
(sphere)Samples the odf function on the points of a sphere
Parameters: |
|
---|---|
Returns: |
|
SphHarmModel
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: |
|
---|
sampling_matrix
(sphere)The matrix needed to sample ODFs from coefficients of the model.
Parameters: |
|
---|---|
Returns: |
|
TensorModel
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: |
|
---|
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.
Example : In iter_fit_tensor()
we have a default step value of
1e4
References
[1] | (1, 2) 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] | (1, 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] | (1, 2) 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: |
|
---|
predict
(dti_params, S0=1.0)Predict a signal for this TensorModel class instance given parameters.
Parameters: |
|
---|
range
dipy.reconst.csdeconv.
range
(stop) → range objectBases: object
range(start, stop[, step]) -> range object
Return an object that produces a sequence of integers from start (inclusive) to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, …, j-1. start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3. These are exactly the valid indices for a list of 4 elements. When step is given, it specifies the increment (or decrement).
Attributes: |
|
---|
Methods
count (value) |
|
index (value, [start, [stop]]) |
Raise ValueError if the value is not present. |
dipy.reconst.csdeconv.
auto_response
(gtab, data, roi_center=None, roi_radius=10, fa_thr=0.7, fa_callable=<function fa_superior>, return_number_of_voxels=False)Automatic estimation of response function using FA.
Parameters: |
|
---|---|
Returns: |
|
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. For example we can use an ROI (20x20x20) at the center of the volume and store the signal values for the voxels with FA values higher than 0.7. Of course, if we haven’t precalculated FA we need to fit a Tensor model to the datasets. Which is what we do in this 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. If requested, the number of voxels used for estimating the response function is also returned, which can be used to judge the fidelity of the response function. As a rule of thumb, at least 300 voxels should be used to estimate a good response function (see [1]).
References
[1] | (1, 2) Tournier, J.D., et al. NeuroImage 2004. Direct estimation of the |
fiber orientation density function from diffusion-weighted MRI data using spherical deconvolution
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: |
|
---|---|
Returns: |
|
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: |
|
---|---|
Returns: |
|
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, 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. |
dipy.reconst.csdeconv.
forward_sdeconv_mat
(r_rh, n)Build forward spherical deconvolution matrix
Parameters: |
|
---|---|
Returns: |
|
dipy.reconst.csdeconv.
forward_sdt_deconv_mat
(ratio, n, r2_term=False)Build forward sharpening deconvolution transform (SDT) matrix
Parameters: |
|
---|---|
Returns: |
|
dipy.reconst.csdeconv.
fractional_anisotropy
(evals, axis=-1)Fractional anisotropy (FA) of a diffusion tensor.
Parameters: |
|
---|---|
Returns: |
|
Notes
FA is calculated using the following equation:
dipy.reconst.csdeconv.
get_sphere
(name='symmetric362')provide triangulated spheres
Parameters: |
|
---|---|
Returns: |
|
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"
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 |
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: |
|
---|
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)
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: |
|
---|---|
Returns: |
|
References
[1] | (1, 2, 3, 4) Tuch, D. MRM 2004. Q-Ball Imaging. |
[2] | (1, 2, 3, 4) Descoteaux, M., et al. IEEE TMI 2009. Deterministic and Probabilistic Tractography Based on Complex Fibre Orientation Distributions |
[3] | (1, 2) Descoteaux, M, PhD thesis, INRIA Sophia-Antipolis, 2008. |
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: |
|
---|---|
Returns: |
|
References
[1] | (1, 2) Tuch, D. MRM 2004. Q-Ball Imaging. |
[2] | (1, 2, 3, 4) Descoteaux, M., et al. IEEE TMI 2009. Deterministic and Probabilistic Tractography Based on Complex Fibre Orientation Distributions |
[3] | (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. |
[4] | (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. |
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, nbr_processes=None)Fit the model to data and computes peaks and metrics
Parameters: |
|
---|---|
Returns: |
|
References
[1] | (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. |
[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. |
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: |
|
---|---|
Returns: |
|
Other Parameters: | |
|
See also
dblquad
tplquad
nquad
fixed_quad
quadrature
odeint
ode
simps
romb
scipy.special
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:
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[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)
.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. 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:
M_c
is infodict['momcom']
then the moments have been
computed for intervals of length |b-a| * 2**(-l)
,
l=0,1,...,M_c
.|b-a|* 2**(-l)
.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’:
K_f
).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
.M_f
containing the error estimate
corresponding to the interval in the same position in
infodict['rslist']
.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)
dipy.reconst.csdeconv.
real_sph_harm
(m, n, theta, phi)Compute real spherical harmonics.
Where the real harmonic \(Y^m_n\) is defined to be:
Imag(\(Y^m_n\)) * sqrt(2) if m > 0 \(Y^0_n\) if m = 0 Real(\(Y^|m|_n\)) * sqrt(2) if m < 0
This may take scalar or array arguments. The inputs will be broadcasted against each other.
Parameters: |
|
---|---|
Returns: |
|
See also
scipy.special.sph_harm
dipy.reconst.csdeconv.
real_sym_sh_basis
(sh_order, theta, phi)Samples a real symmetric spherical harmonic basis at point on the sphere
Samples the basis functions up to order sh_order at points on the sphere given by theta and phi. The basis functions are defined here the same way as in Descoteaux et al. 2007 [1] where the real harmonic \(Y^m_n\) is defined to be:
Imag(\(Y^m_n\)) * sqrt(2) if m > 0 \(Y^0_n\) if m = 0 Real(\(Y^|m|_n\)) * sqrt(2) if m < 0
This may take scalar or array arguments. The inputs will be broadcasted against each other.
Parameters: |
|
---|---|
Returns: |
|
References
[1] | (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. |
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=True, nbr_processes=None, sphere=<dipy.core.sphere.HemiSphere object>)Recursive calibration of response function using peak threshold
Parameters: |
|
---|---|
Returns: |
|
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. |
dipy.reconst.csdeconv.
response_from_mask
(gtab, data, mask)Estimate the response function from a given mask.
Parameters: |
|
---|---|
Returns: |
|
Notes
See csdeconv.auto_response() or csdeconv.recursive_response() if you don’t have a computed mask for the response function estimation.
References
[1] | (1, 2) Tournier, J.D., et al. NeuroImage 2004. Direct estimation of the |
fiber orientation density function from diffusion-weighted MRI data using spherical deconvolution
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 m, degree n 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: |
|
---|---|
Returns: |
|
See also
shm.real_sph_harm
, shm.real_sym_sh_basis
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 |
dipy.reconst.csdeconv.
single_tensor
(gtab, S0=1, evals=None, evecs=None, snr=None)Simulated Q-space signal with a single tensor.
Parameters: |
|
---|---|
Returns: |
|
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. |
dipy.reconst.csdeconv.
sph_harm_ind_list
(sh_order)Returns the degree (n) and order (m) 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_sph_harm()
.
Parameters: |
|
---|---|
Returns: |
|
See also
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: |
|
---|---|
Returns: |
|
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
dipy.reconst.dki.
DiffusionKurtosisFit
(model, model_params)Bases: dipy.reconst.dti.TensorFit
Class for fitting the Diffusion Kurtosis Model
Attributes: |
|
---|
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]) |
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 () |
|
||
md () |
Mean diffusivity (MD) calculated from cached eigenvalues. | ||
mk ([min_kurtosis, max_kurtosis]) |
Computes mean Kurtosis (MK) from the kurtosis tensor. | ||
mode () |
Tensor mode calculated from cached eigenvalues. | ||
odf (sphere) |
The diffusion orientation distribution function (dODF). | ||
planarity () |
|
||
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]) |
Radial Kurtosis (RK) of a diffusion kurtosis tensor [1]. | ||
sphericity () |
|
||
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: |
|
---|
ak
(min_kurtosis=-0.42857142857142855, max_kurtosis=10)Axial Kurtosis (AK) of a diffusion kurtosis tensor [1].
Parameters: |
|
---|---|
Returns: |
|
References
[1] | (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 |
[2] | (1, 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 |
akc
(sphere)Calculates the apparent kurtosis coefficient (AKC) in each direction on the sphere for each voxel in the data
Parameters: |
|
---|---|
Returns: |
|
Notes
For each sphere direction with coordinates \((n_{1}, n_{2}, n_{3})\), the calculation of AKC is done using formula:
where \(W_{ijkl}\) are the elements of the kurtosis tensor, MD the mean diffusivity and ADC the apparent diffusion coefficent computed as:
where \(D_{ij}\) are the elements of the diffusion tensor.
kmax
(sphere='repulsion100', gtol=1e-05, mask=None)Computes the maximum value of a single voxel kurtosis tensor
Parameters: |
|
---|---|
Returns: |
|
mk
(min_kurtosis=-0.42857142857142855, max_kurtosis=10)Computes mean Kurtosis (MK) from the kurtosis tensor.
Parameters: |
|
---|---|
Returns: |
|
Notes
The MK analytical solution is calculated using the following equation [1]:
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
and
where \(R_f\) and \(R_d\) are the Carlson’s elliptic integrals.
References
[1] | (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 |
[2] | (1, 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: |
|
---|
Notes
The predicted signal is given by:
\(\mathbf{D(n)}\) and \(\mathbf{K(n)}\) can be computed from the DT and KT using the following equations:
and
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)Radial Kurtosis (RK) of a diffusion kurtosis tensor [1].
Parameters: |
|
---|---|
Returns: |
|
Notes
RK is calculated with the following equation:
where:
and
References
[1] | (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 |
[2] | (1, 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 |
DiffusionKurtosisModel
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: |
|
---|
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: |
|
---|
predict
(dki_params, S0=1.0)Predict a signal for this DKI model class instance given parameters.
Parameters: |
|
---|
ReconstModel
dipy.reconst.dki.
ReconstModel
(gtab)Bases: object
Abstract class for signal reconstruction models
Methods
fit |
TensorFit
dipy.reconst.dki.
TensorFit
(model, model_params, model_S0=None)Bases: object
Attributes: |
|
---|
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 () |
|
||
md () |
Mean diffusivity (MD) calculated from cached eigenvalues. | ||
mode () |
Tensor mode calculated from cached eigenvalues. | ||
odf (sphere) |
The diffusion orientation distribution function (dODF). | ||
planarity () |
|
||
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 () |
|
||
trace () |
Trace of the tensor calculated from cached eigenvalues. |
lower_triangular |
ad
()Axial diffusivity (AD) calculated from cached eigenvalues.
Returns: |
|
---|
Notes
RD is calculated with the following equation:
adc
(sphere)Calculate the apparent diffusion coefficient (ADC) in each direction on the sphere for each voxel in the data
Parameters: |
|
---|---|
Returns: |
|
ec{b} Q ec{b}^T
Where Q is the quadratic form of the tensor.
linearity
()Returns: |
|
---|
Notes
Linearity is calculated with the following equation:
References
md
()Mean diffusivity (MD) calculated from cached eigenvalues.
Returns: |
|
---|
Notes
MD is calculated with the following equation:
odf
(sphere)The diffusion orientation distribution function (dODF). This is an estimate of the diffusion distance in each direction
Parameters: |
|
---|---|
Returns: |
|
Notes
This is based on equation 3 in [Aganj2010]. To re-derive it from scratch, follow steps in [Descoteaux2008], Section 7.9 Equation 7.24 but with an \(r^2\) term in the integral.
References
[Aganj2010] | (1, 2) 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 |
[Descoteaux2008] | (1, 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: |
|
---|
Notes
Sphericity is calculated with the following equation:
References
predict
(gtab, S0=None, step=None)Given a model fit, predict the signal on the vertices of a sphere
Parameters: |
|
---|
Notes
The predicted signal is given by:
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
rd
()Radial diffusivity (RD) calculated from cached eigenvalues.
Returns: |
|
---|
Notes
RD is calculated with the following equation:
sphericity
()Returns: |
|
---|
Notes
Sphericity is calculated with the following equation:
References
range
dipy.reconst.dki.
range
(stop) → range objectBases: object
range(start, stop[, step]) -> range object
Return an object that produces a sequence of integers from start (inclusive) to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, …, j-1. start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3. These are exactly the valid indices for a list of 4 elements. When step is given, it specifies the increment (or decrement).
Attributes: |
|
---|
Methods
count (value) |
|
index (value, [start, [stop]]) |
Raise ValueError if the value is not present. |
dipy.reconst.dki.
Wcons
(k_elements)Construct the full 4D kurtosis tensors from its 15 independent elements
Parameters: |
|
---|---|
Returns: |
|
dipy.reconst.dki.
Wrotate
(kt, Basis)Rotate a kurtosis tensor from the standard Cartesian coordinate system to another coordinate system basis
Parameters: |
|
---|---|
Returns: |
|
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
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: |
|
---|---|
Returns: |
|
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
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: |
|
---|---|
Returns: |
|
Notes
For each sphere direction with coordinates \((n_{1}, n_{2}, n_{3})\), the calculation of AKC is done using formula [1]:
where \(W_{ijkl}\) are the elements of the kurtosis tensor, MD the mean diffusivity and ADC the apparent diffusion coefficent computed as:
where \(D_{ij}\) are the elements of the diffusion tensor.
References
[1] | (1, 2, 3, 4) 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] | (1, 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 |
dipy.reconst.dki.
axial_kurtosis
(dki_params, min_kurtosis=-0.42857142857142855, max_kurtosis=10)Computes axial Kurtosis (AK) from the kurtosis tensor.
Parameters: |
|
---|---|
Returns: |
|
References
[1] | (1, 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 |
dipy.reconst.dki.
carlson_rd
(x, y, z, errtol=0.0001)Computes the Carlson’s incomplete elliptic integral of the second kind defined as:
Parameters: |
|
---|---|
Returns: |
|
dipy.reconst.dki.
carlson_rf
(x, y, z, errtol=0.0003)Computes the Carlson’s incomplete elliptic integral of the first kind defined as:
Parameters: |
|
---|---|
Returns: |
|
References
[1] | Carlson, B.C., 1994. Numerical computation of real or complex elliptic integrals. arXiv:math/9409227 [math.CA] |
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: |
|
---|---|
Returns: |
|
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: |
|
---|---|
Returns: |
|
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: |
|
---|---|
Returns: |
|
dipy.reconst.dki.
design_matrix
(gtab)Constructs B design matrix for DKI
Returns: |
|
---|
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: |
|
---|---|
Returns: |
|
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 |
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: |
|
---|---|
Returns: |
|
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 |
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: |
|
---|---|
Returns: |
|
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] | (1, 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 |
dipy.reconst.dki.
dki_prediction
(dki_params, gtab, S0=1.0)Predict a signal given diffusion kurtosis imaging parameters.
Parameters: |
|
---|---|
Returns: |
|
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: |
|
---|---|
Returns: |
|
dipy.reconst.dki.
get_sphere
(name='symmetric362')provide triangulated spheres
Parameters: |
|
---|---|
Returns: |
|
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"
dipy.reconst.dki.
kurtosis_maximum
(dki_params, sphere='repulsion100', gtol=0.01, mask=None)Computes kurtosis maximum value
Parameters: |
|
---|---|
Returns: |
|
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: |
|
---|---|
Returns: |
|
See also
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: |
|
---|---|
Returns: |
|
dipy.reconst.dki.
mean_diffusivity
(evals, axis=-1)Mean Diffusivity (MD) of a diffusion tensor.
Parameters: |
|
---|---|
Returns: |
|
Notes
MD is calculated with the following equation:
dipy.reconst.dki.
mean_kurtosis
(dki_params, min_kurtosis=-0.42857142857142855, max_kurtosis=3)Computes mean Kurtosis (MK) from the kurtosis tensor [1].
Parameters: |
|
---|---|
Returns: |
|
Notes
The MK analytical solution is calculated using the following equation [1]:
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
where \(R_f\) and \(R_d\) are the Carlson’s elliptic integrals.
References
[1] | (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 |
[2] | (1, 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 |
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: |
|
---|
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)
dipy.reconst.dki.
ols_fit_dki
(design_matrix, data)Computes ordinary least squares (OLS) fit to calculate the diffusion tensor and kurtosis tensor using a linear regression diffusion kurtosis model [1].
Parameters: |
|
---|---|
Returns: |
|
See also
dipy.reconst.dki.
radial_kurtosis
(dki_params, min_kurtosis=-0.42857142857142855, max_kurtosis=10)Radial Kurtosis (RK) of a diffusion kurtosis tensor [1].
Parameters: |
|
---|---|
Returns: |
|
Notes
RK is calculated with the following equation [1]:
where:
and
References
[1] | (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 |
[2] | (1, 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 |
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: |
|
---|---|
Returns: |
|
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.
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: |
|
---|---|
Returns: |
|
dipy.reconst.dki.
vec_val_vect
()Vectorize vecs.diag(vals).`vecs`.T for last 2 dimensions of vecs
Parameters: |
|
---|---|
Returns: |
|
Raises: |
|
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]])
dipy.reconst.dki.
wls_fit_dki
(design_matrix, data)Computes weighted linear least squares (WLS) fit to calculate the diffusion tensor and kurtosis tensor using a weighted linear regression diffusion kurtosis model [1].
Parameters: |
|
---|---|
Returns: |
|
DiffusionKurtosisFit
dipy.reconst.dki_micro.
DiffusionKurtosisFit
(model, model_params)Bases: dipy.reconst.dti.TensorFit
Class for fitting the Diffusion Kurtosis Model
Attributes: |
|
---|
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]) |
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 () |
|
||
md () |
Mean diffusivity (MD) calculated from cached eigenvalues. | ||
mk ([min_kurtosis, max_kurtosis]) |
Computes mean Kurtosis (MK) from the kurtosis tensor. | ||
mode () |
Tensor mode calculated from cached eigenvalues. | ||
odf (sphere) |
The diffusion orientation distribution function (dODF). | ||
planarity () |
|
||
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]) |
Radial Kurtosis (RK) of a diffusion kurtosis tensor [1]. | ||
sphericity () |
|
||
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: |
|
---|
ak
(min_kurtosis=-0.42857142857142855, max_kurtosis=10)Axial Kurtosis (AK) of a diffusion kurtosis tensor [1].
Parameters: |
|
---|---|
Returns: |
|
References
[1] | (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 |
[2] | (1, 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 |
akc
(sphere)Calculates the apparent kurtosis coefficient (AKC) in each direction on the sphere for each voxel in the data
Parameters: |
|
---|---|
Returns: |
|
Notes
For each sphere direction with coordinates \((n_{1}, n_{2}, n_{3})\), the calculation of AKC is done using formula:
where \(W_{ijkl}\) are the elements of the kurtosis tensor, MD the mean diffusivity and ADC the apparent diffusion coefficent computed as:
where \(D_{ij}\) are the elements of the diffusion tensor.
kmax
(sphere='repulsion100', gtol=1e-05, mask=None)Computes the maximum value of a single voxel kurtosis tensor
Parameters: |
|
---|---|
Returns: |
|
mk
(min_kurtosis=-0.42857142857142855, max_kurtosis=10)Computes mean Kurtosis (MK) from the kurtosis tensor.
Parameters: |
|
---|---|
Returns: |
|
Notes
The MK analytical solution is calculated using the following equation [1]:
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
and
where \(R_f\) and \(R_d\) are the Carlson’s elliptic integrals.
References
[1] | (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 |
[2] | (1, 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: |
|
---|
Notes
The predicted signal is given by:
\(\mathbf{D(n)}\) and \(\mathbf{K(n)}\) can be computed from the DT and KT using the following equations:
and
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)Radial Kurtosis (RK) of a diffusion kurtosis tensor [1].
Parameters: |
|
---|---|
Returns: |
|
Notes
RK is calculated with the following equation:
where:
and
References
[1] | (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 |
[2] | (1, 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 |
DiffusionKurtosisModel
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: |
|
---|
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: |
|
---|
predict
(dki_params, S0=1.0)Predict a signal for this DKI model class instance given parameters.
Parameters: |
|
---|
KurtosisMicrostructuralFit
dipy.reconst.dki_micro.
KurtosisMicrostructuralFit
(model, model_params)Bases: dipy.reconst.dki.DiffusionKurtosisFit
Class for fitting the Diffusion Kurtosis Microstructural Model
Attributes: |
|
---|
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]) |
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 () |
|
||
md () |
Mean diffusivity (MD) calculated from cached eigenvalues. | ||
mk ([min_kurtosis, max_kurtosis]) |
Computes mean Kurtosis (MK) from the kurtosis tensor. | ||
mode () |
Tensor mode calculated from cached eigenvalues. | ||
odf (sphere) |
The diffusion orientation distribution function (dODF). | ||
planarity () |
|
||
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]) |
Radial Kurtosis (RK) of a diffusion kurtosis tensor [Rc4101656d30e-1]. | ||
sphericity () |
|
||
trace () |
Trace of the tensor calculated from cached eigenvalues. |
lower_triangular |
__init__
(model, model_params)Initialize a KurtosisMicrostructural Fit class instance.
Parameters: |
|
---|
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 |
awf
Returns the volume fraction of the restricted diffusion compartment also known as axonal water fraction.
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 |
axonal_diffusivity
Returns the axonal diffusivity defined as the restricted diffusion tensor trace [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 |
hindered_ad
Returns the axial diffusivity of the hindered compartment.
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 |
hindered_evals
Returns the eigenvalues of the hindered diffusion compartment.
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 |
hindered_rd
Returns the radial diffusivity of the hindered compartment.
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
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).
restricted_evals
Returns the eigenvalues of the restricted diffusion compartment.
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 |
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].
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
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: |
|
---|
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 |
fit
(data, mask=None, sphere='repulsion100', gtol=0.01, awf_only=False)Fit method of the Diffusion Kurtosis Microstructural Model
Parameters: |
|
---|
predict
(params, S0=1.0)Predict a signal for the DKI microstructural model class instance given parameters.
Parameters: |
|
---|
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 |
dipy.reconst.dki_micro.
axial_diffusivity
(evals, axis=-1)Axial Diffusivity (AD) of a diffusion tensor. Also called parallel diffusivity.
Parameters: |
|
---|---|
Returns: |
|
Notes
AD is calculated with the following equation:
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: |
|
---|---|
Returns: |
|
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 |
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: |
|
---|---|
Returns: |
|
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: |
|
---|---|
Returns: |
|
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 |
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: |
|
---|---|
Returns: |
|
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 |
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: |
|
---|---|
Returns: |
|
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] | (1, 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 |
dipy.reconst.dki_micro.
dkimicro_prediction
(params, gtab, S0=1)Signal prediction given the DKI microstructure model parameters.
Parameters: |
|
---|---|
Returns: |
|
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.
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: |
|
---|---|
Returns: |
|
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: |
|
---|---|
Returns: |
|
dipy.reconst.dki_micro.
get_sphere
(name='symmetric362')provide triangulated spheres
Parameters: |
|
---|---|
Returns: |
|
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"
dipy.reconst.dki_micro.
kurtosis_maximum
(dki_params, sphere='repulsion100', gtol=0.01, mask=None)Computes kurtosis maximum value
Parameters: |
|
---|---|
Returns: |
|
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: |
|
---|---|
Returns: |
|
dipy.reconst.dki_micro.
mean_diffusivity
(evals, axis=-1)Mean Diffusivity (MD) of a diffusion tensor.
Parameters: |
|
---|---|
Returns: |
|
Notes
MD is calculated with the following equation:
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: |
|
---|
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)
dipy.reconst.dki_micro.
radial_diffusivity
(evals, axis=-1)Radial Diffusivity (RD) of a diffusion tensor. Also called perpendicular diffusivity.
Parameters: |
|
---|---|
Returns: |
|
Notes
RD is calculated with the following equation:
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: |
|
---|---|
Returns: |
|
dipy.reconst.dki_micro.
tortuosity
(hindered_ad, hindered_rd)Computes the tortuosity of the hindered diffusion compartment given its axial and radial diffusivities
Parameters: |
|
---|
dipy.reconst.dki_micro.
trace
(evals, axis=-1)Trace of a diffusion tensor.
Parameters: |
|
---|---|
Returns: |
|
Notes
Trace is calculated with the following equation:
dipy.reconst.dki_micro.
vec_val_vect
()Vectorize vecs.diag(vals).`vecs`.T for last 2 dimensions of vecs
Parameters: |
|
---|---|
Returns: |
|
Raises: |
|
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
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. |
cache_get
(tag, key, default=None)Retrieve a value from the cache.
Parameters: |
|
---|---|
Returns: |
|
cache_set
(tag, key, value)Store a value in the cache.
Parameters: |
|
---|
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
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 |
DiffusionSpectrumDeconvModel
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.
nowrap: |
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: |
|
---|
References
[1] | (1, 2) 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.
DiffusionSpectrumFit
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: |
|
---|
msd_discrete
(normalized=True)Calculates the mean squared displacement on the discrete propagator
nowrap: |
end{equation} |
---|
where \(\hat{\mathbf{r}}\) is a point in the 3D Propagator space (see Wu et al. [1]).
Parameters: |
|
---|---|
Returns: |
|
References
[1] | (1, 2) Wu Y. et al., “Hybrid diffusion imaging”, NeuroImage, vol 36, |
odf
(sphere)Calculates the real discrete odf for a given discrete sphere
nowrap: |
end{equation} |
---|
where \(\hat{\mathbf{u}}\) is the unit vector which corresponds to a sphere point.
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: |
|
---|---|
Returns: |
|
References
[1] | (1, 2) Descoteaux M. et al., “Multiple q-shell diffusion propagator |
imaging”, Medical Image Analysis, vol 15, No. 4, p. 603-621, 2011.
[2] | (1, 2) Tuch D.S., “Diffusion MRI of Complex Tissue Structure”, PhD Thesis, 2002. |
[3] | (1, 2) 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
DiffusionSpectrumModel
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})\)
nowrap: |
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: |
|
---|
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.
References
[1] | (1, 2) 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] | (1, 2) 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, get_sphere
>>> data, gtab = dsi_voxels()
>>> sphere = get_sphere('symmetric724')
>>> from dipy.reconst.dsi import DiffusionSpectrumModel
>>> ds = DiffusionSpectrumModel(gtab)
>>> dsfit = ds.fit(data)
>>> from dipy.reconst.odf import gfa
>>> np.round(gfa(dsfit.odf(sphere))[0, 0, 0], 2)
0.11
OdfFit
dipy.reconst.dsi.
OdfFit
(model, data)Bases: dipy.reconst.base.ReconstFit
Methods
odf (sphere) |
To be implemented but specific odf models |
OdfModel
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 |
dipy.reconst.dsi.
LR_deconv
(prop, psf, numit=5, acc_factor=1)Perform Lucy-Richardson deconvolution algorithm on a 3D array.
Parameters: |
|
---|
References
[1] | (1, 2) Biggs David S.C. et al., “Acceleration of Iterative Image Restoration Algorithms”, Applied Optics, vol. 36, No. 8, p. 1766-1775, 1997. |
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: |
|
---|---|
Returns: |
|
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
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: |
|
---|---|
Returns: |
|
See also
ifftshift
Examples
>>> freqs = np.fft.fftfreq(10, 0.1)
>>> freqs
array([ 0., 1., 2., 3., 4., -5., -4., -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.]])
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: |
|
---|---|
Returns: |
|
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.
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: |
|
---|---|
Returns: |
|
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: |
|
---|---|
Returns: |
|
See also
fftshift
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.]])
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: |
|
---|---|
Returns: |
|
See also
spline_filter
, geometric_transform
, scipy.interpolate
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)
dipy.reconst.dsi.
pdf_odf
(Pr, rradius, interp_coords)Calculates the real ODF from the diffusion propagator(PDF) Pr
Parameters: |
|
---|
ReconstModel
dipy.reconst.dti.
ReconstModel
(gtab)Bases: object
Abstract class for signal reconstruction models
Methods
fit |
TensorFit
dipy.reconst.dti.
TensorFit
(model, model_params, model_S0=None)Bases: object
Attributes: |
|
---|
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 () |
|
||
md () |
Mean diffusivity (MD) calculated from cached eigenvalues. | ||
mode () |
Tensor mode calculated from cached eigenvalues. | ||
odf (sphere) |
The diffusion orientation distribution function (dODF). | ||
planarity () |
|
||
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 () |
|
||
trace () |
Trace of the tensor calculated from cached eigenvalues. |
lower_triangular |
ad
()Axial diffusivity (AD) calculated from cached eigenvalues.
Returns: |
|
---|
Notes
RD is calculated with the following equation:
adc
(sphere)Calculate the apparent diffusion coefficient (ADC) in each direction on the sphere for each voxel in the data
Parameters: |
|
---|---|
Returns: |
|
ec{b} Q ec{b}^T
Where Q is the quadratic form of the tensor.
linearity
()Returns: |
|
---|
Notes
Linearity is calculated with the following equation:
References
md
()Mean diffusivity (MD) calculated from cached eigenvalues.
Returns: |
|
---|
Notes
MD is calculated with the following equation:
odf
(sphere)The diffusion orientation distribution function (dODF). This is an estimate of the diffusion distance in each direction
Parameters: |
|
---|---|
Returns: |
|
Notes
This is based on equation 3 in [Aganj2010]. To re-derive it from scratch, follow steps in [Descoteaux2008], Section 7.9 Equation 7.24 but with an \(r^2\) term in the integral.
References
[Aganj2010] | (1, 2) 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 |
[Descoteaux2008] | (1, 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: |
|
---|
Notes
Sphericity is calculated with the following equation:
References
predict
(gtab, S0=None, step=None)Given a model fit, predict the signal on the vertices of a sphere
Parameters: |
|
---|
Notes
The predicted signal is given by:
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
rd
()Radial diffusivity (RD) calculated from cached eigenvalues.
Returns: |
|
---|
Notes
RD is calculated with the following equation:
sphericity
()Returns: |
|
---|
Notes
Sphericity is calculated with the following equation:
References
TensorModel
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: |
|
---|
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.
Example : In iter_fit_tensor()
we have a default step value of
1e4
References
[1] | (1, 2) 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] | (1, 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] | (1, 2) 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: |
|
---|
predict
(dti_params, S0=1.0)Predict a signal for this TensorModel class instance given parameters.
Parameters: |
|
---|
range
dipy.reconst.dti.
range
(stop) → range objectBases: object
range(start, stop[, step]) -> range object
Return an object that produces a sequence of integers from start (inclusive) to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, …, j-1. start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3. These are exactly the valid indices for a list of 4 elements. When step is given, it specifies the increment (or decrement).
Attributes: |
|
---|
Methods
count (value) |
|
index (value, [start, [stop]]) |
Raise ValueError if the value is not present. |
dipy.reconst.dti.
apparent_diffusion_coef
(q_form, sphere)Calculate the apparent diffusion coefficient (ADC) in each direction of a sphere.
Parameters: |
|
---|
ec{b} Q ec{b}^T
Where Q is the quadratic form of the tensor.
dipy.reconst.dti.
auto_attr
(func)Decorator to create OneTimeProperty attributes.
Parameters: |
|
---|
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
dipy.reconst.dti.
axial_diffusivity
(evals, axis=-1)Axial Diffusivity (AD) of a diffusion tensor. Also called parallel diffusivity.
Parameters: |
|
---|---|
Returns: |
|
Notes
AD is calculated with the following equation:
dipy.reconst.dti.
color_fa
(fa, evecs)Color fractional anisotropy of diffusion tensor
Parameters: |
|
---|---|
Returns: |
|
ec{e})) imes fa
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: |
|
---|---|
Returns: |
|
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: |
|
---|---|
Returns: |
|
dipy.reconst.dti.
determinant
(q_form)The determinant of a tensor, given in quadratic form
Parameters: |
|
---|---|
Returns: |
|
dipy.reconst.dti.
deviatoric
(q_form)Calculate the deviatoric (anisotropic) part of the tensor [1].
Parameters: |
|
---|---|
Returns: |
|
Notes
The deviatoric part of the tensor is defined as (equations 3-5 in [1]):
Where \(A\) is the tensor quadratic form and \(\bar{A}\) is the anisotropic part of the tensor.
References
[1] | (1, 2, 3, 4) 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. |
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: |
|
---|---|
Returns: |
|
dipy.reconst.dti.
eigh
(a, UPLO='L')Iterate over np.linalg.eigh if it doesn’t support vectorized operation
Parameters: |
|
---|---|
Returns: |
|
Raises: |
|
See also
np.linalg.eigh
dipy.reconst.dti.
fractional_anisotropy
(evals, axis=-1)Fractional anisotropy (FA) of a diffusion tensor.
Parameters: |
|
---|---|
Returns: |
|
Notes
FA is calculated using the following equation:
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: |
|
---|---|
Returns: |
|
dipy.reconst.dti.
geodesic_anisotropy
(evals, axis=-1)Geodesic anisotropy (GA) of a diffusion tensor.
Parameters: |
|
---|---|
Returns: |
|
Notes
GA is calculated using the following equation given in [1]:
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, 5) 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, 3) 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, 3) A. D. Lee, etal, P. M. Thompson. “Comparison of fractional and geodesic anisotropy in diffusion tensor images of 90 monozygotic and dizygotic twins”. 5th IEEE International Symposium on Biomedical Imaging (ISBI), pp. 943-946, May 2008. |
[4] | V. Arsigny, P. Fillard, X. Pennec, N. Ayache. “Log-Euclidean metrics for fast and simple calculus on diffusion tensors.” Magnetic Resonance in Medecine, vol 56, pp. 411-421, 2006. |
dipy.reconst.dti.
get_sphere
(name='symmetric362')provide triangulated spheres
Parameters: |
|
---|---|
Returns: |
|
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"
dipy.reconst.dti.
gradient_table
(bvals, bvecs=None, big_delta=None, small_delta=None, 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: |
|
---|---|
Returns: |
|
Notes
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
dipy.reconst.dti.
isotropic
(q_form)Calculate the isotropic part of the tensor [Rd0568a744381-1].
Parameters: |
|
---|---|
Returns: |
|
rac{1}{2} tr(A) I
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: |
|
---|
dipy.reconst.dti.
linearity
(evals, axis=-1)The linearity of the tensor [1]
Parameters: |
|
---|---|
Returns: |
|
Notes
Linearity is calculated with the following equation:
References
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: |
|
---|---|
Returns: |
|
dipy.reconst.dti.
mean_diffusivity
(evals, axis=-1)Mean Diffusivity (MD) of a diffusion tensor.
Parameters: |
|
---|---|
Returns: |
|
Notes
MD is calculated with the following equation:
dipy.reconst.dti.
mode
(q_form)Mode (MO) of a diffusion tensor [1].
Parameters: |
|
---|---|
Returns: |
|
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]):
Where \(\widetilde{A}\) is the deviatoric part of the tensor quadratic form.
References
[1] | (1, 2, 3, 4) 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. |
dipy.reconst.dti.
nlls_fit_tensor
(design_matrix, data, weighting=None, sigma=None, jac=True, return_S0_hat=False)Fit the tensor params using non-linear least-squares.
Parameters: |
|
---|---|
Returns: |
|
dipy.reconst.dti.
norm
(q_form)Calculate the Frobenius norm of a tensor quadratic form
Parameters: |
|
---|---|
Returns: |
|
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} |
---|
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 [1].
Parameters: |
|
---|---|
Returns: |
|
See also
WLS_fit_tensor
, decompose_tensor
, design_matrix
Notes
References
[1] | (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28) Chung, SW., Lu, Y., Henry, R.G., 2006. Comparison of bootstrap approaches for estimation of uncertainties of DTI parameters. NeuroImage 33, 531-541. |
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: |
|
---|---|
Returns: |
|
Raises: |
|
See also
np.linalg.pinv
dipy.reconst.dti.
planarity
(evals, axis=-1)The planarity of the tensor [1]
Parameters: |
|
---|---|
Returns: |
|
Notes
Planarity is calculated with the following equation:
References
dipy.reconst.dti.
radial_diffusivity
(evals, axis=-1)Radial Diffusivity (RD) of a diffusion tensor. Also called perpendicular diffusivity.
Parameters: |
|
---|---|
Returns: |
|
Notes
RD is calculated with the following equation:
dipy.reconst.dti.
restore_fit_tensor
(design_matrix, data, sigma=None, jac=True, return_S0_hat=False)Use the RESTORE algorithm [Chang2005] to calculate a robust tensor fit
Parameters: |
|
---|---|
Returns: |
|
References
Chang, L-C, Jones, DK and Pierpaoli, C (2005). RESTORE: robust estimation of tensors by outlier rejection. MRM, 53: 1088-95.
dipy.reconst.dti.
sphericity
(evals, axis=-1)The sphericity of the tensor [1]
Parameters: |
|
---|---|
Returns: |
|
Notes
Sphericity is calculated with the following equation:
References
dipy.reconst.dti.
tensor_prediction
(dti_params, gtab, S0)Predict a signal given tensor parameters.
Parameters: |
|
---|
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.
dipy.reconst.dti.
trace
(evals, axis=-1)Trace of a diffusion tensor.
Parameters: |
|
---|---|
Returns: |
|
Notes
Trace is calculated with the following equation:
dipy.reconst.dti.
vec_val_vect
()Vectorize vecs.diag(vals).`vecs`.T for last 2 dimensions of vecs
Parameters: |
|
---|---|
Returns: |
|
Raises: |
|
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]])
dipy.reconst.dti.
vector_norm
(vec, axis=-1, keepdims=False)Return vector Euclidean (L2) norm
See unit vector and Euclidean norm
Parameters: |
|
---|---|
Returns: |
|
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.])
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: |
|
---|---|
Returns: |
|
See also
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:
- calculate OLS estimates of the data
- apply the OLS estimates as weights to the WLS fit of the data
This ensured heteroscedasticity could be properly modeled for various types of bootstrap resampling (namely residual bootstrap).
References
[1] | (1, 2, 3) Chung, SW., Lu, Y., Henry, R.G., 2006. Comparison of bootstrap approaches for estimation of uncertainties of DTI parameters. NeuroImage 33, 531-541. |
Cache
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. |
cache_get
(tag, key, default=None)Retrieve a value from the cache.
Parameters: |
|
---|---|
Returns: |
|
cache_set
(tag, key, value)Store a value in the cache.
Parameters: |
|
---|
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
dipy.reconst.forecast.
ForecastFit
(model, data, sh_coef, d_par, d_perp)Bases: dipy.reconst.odf.OdfFit
Attributes: |
---|
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: |
|
---|
odf
(sphere, clip_negative=True)Calculates the fODF for a given discrete sphere.
Parameters: |
|
---|
ForecastModel
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 Tecnique (SMT) [2,3]_.
With FORECAST it is possible to calculate crossing invariant parallel diffusivity, perpendicular diffusivity, mean diffusivity, and fractional anisotropy [2]
References
[1] | Anderson A. W., “Measurement of Fiber Orientation Distributions Using High Angular Resolution Diffusion Imaging”, Magnetic Resonance in Medicine, 2005. |
[2] | (1, 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. |
The implementation of FORECAST may require CVXPY (http://www.cvxpy.org/).
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})\)
nowrap: |
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: |
|
---|
References
[1] | (1, 2) 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.
>>> from dipy.data import get_sphere, get_3shell_gtab
>>> gtab = get_3shell_gtab()
>>> from dipy.sims.voxel import MultiTensor
>>> mevals = np.array(([0.0017, 0.0003, 0.0003],
... [0.0017, 0.0003, 0.0003]))
>>> angl = [(0, 0), (60, 0)]
>>> data, sticks = MultiTensor(gtab,
... mevals,
... S0=100.0,
... angles=angl,
... fractions=[50, 50],
... snr=None)
>>> from dipy.reconst.forecast import ForecastModel
>>> fm = ForecastModel(gtab, sh_order=6)
>>> f_fit = fm.fit(data)
>>> d_par = f_fit.dpar
>>> d_perp = f_fit.dperp
>>> sphere = get_sphere('symmetric724')
>>> fodf = f_fit.odf(sphere)
OdfFit
dipy.reconst.forecast.
OdfFit
(model, data)Bases: dipy.reconst.base.ReconstFit
Methods
odf (sphere) |
To be implemented but specific odf models |
OdfModel
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 |
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: |
|
---|---|
Returns: |
|
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: |
|
---|---|
Returns: |
|
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, 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. |
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: |
|
---|---|
Returns: |
|
dipy.reconst.forecast.
get_sphere
(name='symmetric362')provide triangulated spheres
Parameters: |
|
---|---|
Returns: |
|
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"
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: |
|
---|---|
Returns: |
|
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 1D array, regardless of the shape of x0, or whether x0 is a scalar.
dipy.reconst.forecast.
optional_package
(name, trip_msg=None)Return package-like thing and module setup for package name
Parameters: |
|
---|---|
Returns: |
|
dipy.reconst.forecast.
real_sph_harm
(m, n, theta, phi)Compute real spherical harmonics.
Where the real harmonic \(Y^m_n\) is defined to be:
Imag(\(Y^m_n\)) * sqrt(2) if m > 0 \(Y^0_n\) if m = 0 Real(\(Y^|m|_n\)) * sqrt(2) if m < 0
This may take scalar or array arguments. The inputs will be broadcasted against each other.
Parameters: |
|
---|---|
Returns: |
|
See also
scipy.special.sph_harm
FreeWaterTensorFit
dipy.reconst.fwdti.
FreeWaterTensorFit
(model, model_params)Bases: dipy.reconst.dti.TensorFit
Class for fitting the Free Water Tensor Model
Attributes: |
|
---|
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 () |
|
||
md () |
Mean diffusivity (MD) calculated from cached eigenvalues. | ||
mode () |
Tensor mode calculated from cached eigenvalues. | ||
odf (sphere) |
The diffusion orientation distribution function (dODF). | ||
planarity () |
|
||
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 () |
|
||
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: |
|
---|
predict
(gtab, S0=1)Given a free water tensor model fit, predict the signal on the vertices of a gradient table
Parameters: |
|
---|---|
Returns: |
|
FreeWaterTensorModel
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: |
|
---|
References
[1] | (1, 2, 3, 4) Hoy, A.R., Koay, C.G., Kecskemeti, S.R., Alexander, A.L., 2014. Optimization of a free water elimination two-compartmental model for diffusion tensor imaging. NeuroImage 103, 323-333. doi: 10.1016/j.neuroimage.2014.09.053 |
predict
(fwdti_params, S0=1)Predict a signal for this TensorModel class instance given parameters.
Parameters: |
|
---|---|
Returns: |
|
ReconstModel
dipy.reconst.fwdti.
ReconstModel
(gtab)Bases: object
Abstract class for signal reconstruction models
Methods
fit |
TensorFit
dipy.reconst.fwdti.
TensorFit
(model, model_params, model_S0=None)Bases: object
Attributes: |
|
---|
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 () |
|
||
md () |
Mean diffusivity (MD) calculated from cached eigenvalues. | ||
mode () |
Tensor mode calculated from cached eigenvalues. | ||
odf (sphere) |
The diffusion orientation distribution function (dODF). | ||
planarity () |
|
||
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 () |
|
||
trace () |
Trace of the tensor calculated from cached eigenvalues. |
lower_triangular |
ad
()Axial diffusivity (AD) calculated from cached eigenvalues.
Returns: |
|
---|
Notes
RD is calculated with the following equation:
adc
(sphere)Calculate the apparent diffusion coefficient (ADC) in each direction on the sphere for each voxel in the data
Parameters: |
|
---|---|
Returns: |
|
ec{b} Q ec{b}^T
Where Q is the quadratic form of the tensor.
linearity
()Returns: |
|
---|
Notes
Linearity is calculated with the following equation:
References
md
()Mean diffusivity (MD) calculated from cached eigenvalues.
Returns: |
|
---|
Notes
MD is calculated with the following equation:
odf
(sphere)The diffusion orientation distribution function (dODF). This is an estimate of the diffusion distance in each direction
Parameters: |
|
---|---|
Returns: |
|
Notes
This is based on equation 3 in [Aganj2010]. To re-derive it from scratch, follow steps in [Descoteaux2008], Section 7.9 Equation 7.24 but with an \(r^2\) term in the integral.
References
[Aganj2010] | (1, 2) 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 |
[Descoteaux2008] | (1, 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: |
|
---|
Notes
Sphericity is calculated with the following equation:
References
predict
(gtab, S0=None, step=None)Given a model fit, predict the signal on the vertices of a sphere
Parameters: |
|
---|
Notes
The predicted signal is given by:
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
rd
()Radial diffusivity (RD) calculated from cached eigenvalues.
Returns: |
|
---|
Notes
RD is calculated with the following equation:
sphericity
()Returns: |
|
---|
Notes
Sphericity is calculated with the following equation:
References
dipy.reconst.fwdti.
cholesky_to_lower_triangular
(R)Convert Cholesky decompostion elements to the diffusion tensor elements
Parameters: |
|
---|---|
Returns: |
|
References
[1] | (1, 2) 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 |
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: |
|
---|---|
Returns: |
|
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: |
|
---|---|
Returns: |
|
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: |
|
---|---|
Returns: |
|
dipy.reconst.fwdti.
fwdti_prediction
(params, gtab, S0=1, Diso=0.003)Signal prediction given the free water DTI model parameters.
Parameters: |
|
---|---|
Returns: |
|
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] | (1, 2) Hoy, A.R., Koay, C.G., Kecskemeti, S.R., Alexander, A.L., 2014. Optimization of a free water elimination two-compartmental model for diffusion tensor imaging. NeuroImage 103, 323-333. doi: 10.1016/j.neuroimage.2014.09.053 |
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: |
|
---|---|
Returns: |
|
dipy.reconst.fwdti.
lower_triangular_to_cholesky
(tensor_elements)Perfoms Cholesky decomposition of the diffusion tensor
Parameters: |
|
---|---|
Returns: |
|
References
[1] | (1, 2) 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 |
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: |
|
---|
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)
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: |
|
---|---|
Returns: |
|
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: |
|
---|---|
Returns: |
|
dipy.reconst.fwdti.
vec_val_vect
()Vectorize vecs.diag(vals).`vecs`.T for last 2 dimensions of vecs
Parameters: |
|
---|---|
Returns: |
|
Raises: |
|
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]])
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: |
|
---|---|
Returns: |
|
References
[1] | (1, 2, 3) Hoy, A.R., Koay, C.G., Kecskemeti, S.R., Alexander, A.L., 2014. Optimization of a free water elimination two-compartmental model for diffusion tensor imaging. NeuroImage 103, 323-333. doi: 10.1016/j.neuroimage.2014.09.053 |
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: |
|
---|---|
Returns: |
|
Cache
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. |
cache_get
(tag, key, default=None)Retrieve a value from the cache.
Parameters: |
|
---|---|
Returns: |
|
cache_set
(tag, key, value)Store a value in the cache.
Parameters: |
|
---|
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
dipy.reconst.gqi.
GeneralizedQSamplingFit
(model, data)Bases: dipy.reconst.odf.OdfFit
Methods
odf (sphere) |
Calculates the discrete ODF for a given discrete sphere. |
GeneralizedQSamplingModel
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: |
|
---|
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, 4) Yeh F-C et al., “Generalized Q-Sampling Imaging”, IEEE TMI, 2010 |
[2] | (1, 2, 3) 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)
OdfFit
dipy.reconst.gqi.
OdfFit
(model, data)Bases: dipy.reconst.base.ReconstFit
Methods
odf (sphere) |
To be implemented but specific odf models |
OdfModel
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 |
dipy.reconst.gqi.
gfa
(samples)The general fractional anisotropy of a function evaluated on the unit sphere
Parameters: |
|
---|---|
Returns: |
|
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. |
dipy.reconst.gqi.
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: |
|
---|---|
Returns: |
|
See also
dipy.reconst.gqi.
normalize_qa
(qa, max_qa=None)Normalize quantitative anisotropy.
Used mostly with GQI rather than GQI2.
Parameters: |
|
---|---|
Returns: |
|
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.
dipy.reconst.gqi.
remove_similar_vertices
()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: |
|
---|---|
Returns: |
|
Interpolator
dipy.reconst.interpolate.
Interpolator
(data, voxel_size)Bases: object
Class to be subclassed by different interpolator types
NearestNeighborInterpolator
dipy.reconst.interpolate.
NearestNeighborInterpolator
(data, voxel_size)Bases: dipy.reconst.interpolate.Interpolator
Interpolates data using nearest neighbor interpolation
OutsideImage
dipy.reconst.interpolate.
OutsideImage
Bases: Exception
Attributes: |
|
---|
Methods
with_traceback |
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self. |
TriLinearInterpolator
dipy.reconst.interpolate.
TriLinearInterpolator
(data, voxel_size)Bases: dipy.reconst.interpolate.Interpolator
Interpolates data using trilinear interpolation
interpolate 4d diffusion volume using 3 indices, ie data[x, y, z]
dipy.reconst.interpolate.
array
(object, dtype=None, copy=True, order='K', subok=False, ndmin=0)Create an array.
Parameters: |
|
|||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Returns: |
|
See also
empty_like
ones_like
zeros_like
full_like
empty
ones
zeros
full
Notes
When order is ‘A’ and object is an array in neither ‘C’ nor ‘F’ order, and a copy is forced by a change in dtype, then the order of the result is not necessarily ‘C’ as expected. This is likely a bug.
Examples
>>> np.array([1, 2, 3])
array([1, 2, 3])
Upcasting:
>>> np.array([1, 2, 3.0])
array([ 1., 2., 3.])
More than one dimension:
>>> np.array([[1, 2], [3, 4]])
array([[1, 2],
[3, 4]])
Minimum dimensions 2:
>>> np.array([1, 2, 3], ndmin=2)
array([[1, 2, 3]])
Type provided:
>>> np.array([1, 2, 3], dtype=complex)
array([ 1.+0.j, 2.+0.j, 3.+0.j])
Data-type consisting of more than one element:
>>> x = np.array([(1,2),(3,4)],dtype=[('a','<i4'),('b','<i4')])
>>> x['a']
array([1, 3])
Creating an array from sub-classes:
>>> np.array(np.mat('1 2; 3 4'))
array([[1, 2],
[3, 4]])
>>> np.array(np.mat('1 2; 3 4'), subok=True)
matrix([[1, 2],
[3, 4]])
IvimFit
dipy.reconst.ivim.
IvimFit
(model, model_params)Bases: object
Attributes: |
|
---|
Methods
predict (gtab[, S0]) |
Given a model fit, predict the signal. |
__init__
(model, model_params)Initialize a IvimFit class instance. Parameters ———- model : Model class model_params : array
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.
predict
(gtab, S0=1.0)Given a model fit, predict the signal.
Parameters: |
|
---|---|
Returns: |
|
IvimModelLM
dipy.reconst.ivim.
IvimModelLM
(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: |
|
---|
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: |
|
---|---|
Returns: |
|
estimate_linear_fit
(data, split_b, less_than=True)Estimate a linear fit by taking log of data.
Parameters: |
|
---|---|
Returns: |
|
predict
(ivim_params, gtab, S0=1.0)Predict a signal for this IvimModel class instance given parameters.
Parameters: |
|
---|---|
Returns: |
|
IvimModelVP
dipy.reconst.ivim.
IvimModelVP
(gtab, 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, 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.
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: |
|
---|---|
Returns: |
|
Notes
cost function for differential evolution algorithm:
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: |
|
---|---|
Returns: |
|
Notes
to make cost function for Differential Evolution algorithm: .. math:
(signal - S)^T(signal - S)
References
[1] | (1, 2) 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] | (1, 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: |
|
---|---|
Returns: |
|
Notes
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.
Parameters: |
|
---|---|
Returns: |
|
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: |
|
---|---|
Returns: |
|
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: |
|
---|---|
Returns: |
|
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: |
|
---|---|
Returns: |
|
LooseVersion
dipy.reconst.ivim.
LooseVersion
(vstring=None)Bases: distutils.version.Version
Version numbering for anarchists and software realists. Implements the standard interface for version number classes as described above. A version number consists of a series of numbers, separated by either periods or strings of letters. When comparing version numbers, the numeric components will be compared numerically, and the alphabetic components lexically. The following are all valid version numbers, in no particular order:
1.5.1 1.5.2b2 161 3.10a 8.02 3.4j 1996.07.12 3.2.pl0 3.1.1.6 2g6 11g 0.960923 2.2beta29 1.13++ 5.5.kw 2.0b1pl0
In fact, there is no such thing as an invalid version number under this scheme; the rules for comparison are simple and predictable, but may not always give the results you want (for some definition of “want”).
Methods
parse |
ReconstModel
dipy.reconst.ivim.
ReconstModel
(gtab)Bases: object
Abstract class for signal reconstruction models
Methods
fit |
dipy.reconst.ivim.
IvimModel
(gtab, fit_method='LM', **kwargs)Selector function to switch between the 2-stage Levenberg-Marquardt based NLLS fitting method (also containing the linear fit): LM and the Variable Projections based fitting method: VarPro.
Parameters: |
|
---|
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: |
|
---|---|
Returns: |
|
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: |
|
---|---|
Returns: |
|
dipy.reconst.ivim.
ivim_model_selector
(gtab, fit_method='LM', **kwargs)Selector function to switch between the 2-stage Levenberg-Marquardt based NLLS fitting method (also containing the linear fit): LM and the Variable Projections based fitting method: VarPro.
Parameters: |
|
---|
dipy.reconst.ivim.
ivim_prediction
(params, gtab)The Intravoxel incoherent motion (IVIM) model function.
Parameters: |
|
---|---|
Returns: |
|
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-dimensional 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: |
|
---|---|
Returns: |
|
See also
leastsq
curve_fit
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, 4) 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] | (1, 2) William H. Press et. al., “Numerical Recipes. The Art of Scientific Computing. 3rd edition”, Sec. 5.7. |
[Byrd] | (1, 2, 3) 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] | (1, 2) 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, 4) 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] | (1, 2) 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] | (1, 2) J. Nocedal and S. J. Wright, “Numerical optimization, 2nd edition”, Chapter 4. |
[BA] | (1, 2) 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:
>>> def gen_data(t, a, b, c, noise=0, n_outliers=0, random_state=0):
... y = a + b * np.exp(t * c)
...
... rnd = np.random.RandomState(random_state)
... error = noise * rnd.randn(t.size)
... outliers = rnd.randint(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-dimensional complex function of n complex variables we optimize a 2m-dimensional 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)
dipy.reconst.ivim.
optional_package
(name, trip_msg=None)Return package-like thing and module setup for package name
Parameters: |
|
---|---|
Returns: |
|
Cache
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. |
cache_get
(tag, key, default=None)Retrieve a value from the cache.
Parameters: |
|
---|---|
Returns: |
|
cache_set
(tag, key, value)Store a value in the cache.
Parameters: |
|
---|
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
dipy.reconst.mapmri.
MapmriFit
(model, mapmri_coef, mu, R, lopt, errorcode=0)Bases: dipy.reconst.base.ReconstFit
Attributes: |
|
---|
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: |
|
---|
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
()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] | (1, 2) 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, 3) Ozarslan E. et al., “Mean apparent propagator (MAP) MRI: A novel |
diffusion imaging method for mapping tissue microstructure”, NeuroImage, 2013.
[2] | (1, 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, 3) Ozarslan E. et al., “Mean apparent propagator (MAP) MRI: A novel |
diffusion imaging method for mapping tissue microstructure”, NeuroImage, 2013.
[2] | (1, 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, 3) Ozarslan E. et al., “Mean apparent propagator (MAP) MRI: A novel |
diffusion imaging method for mapping tissue microstructure”, NeuroImage, 2013.
[2] | (1, 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: |
|
---|
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.
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] | (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).
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] | (1, 2) 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, 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).
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, 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).
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, 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).
MapmriModel
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, 3) Ozarslan E. et al., “Mean apparent propagator (MAP) MRI: A novel diffusion imaging method for mapping tissue microstructure”, NeuroImage, 2013. |
[2] | (1, 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, 3) 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: |
|
---|
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. |
[2] | (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. |
[3] | (1, 2, 3, 4) Ozarslan E. et al., “Simple harmonic oscillator based reconstruction and estimation for three-dimensional q-space mri”, ISMRM 2009. |
[4] | (1, 2, 3) 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, get_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 SticksAndBall
>>> data, golden_directions = SticksAndBall(
... 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)
>>> sphere = get_sphere('symmetric724')
>>> odf = mapfit.odf(sphere)
Optimizer
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: |
|
---|
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: |
|
---|
See also
scipy.optimize.minimize
ReconstFit
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.
ReconstModel
dipy.reconst.mapmri.
ReconstModel
(gtab)Bases: object
Abstract class for signal reconstruction models
Methods
fit |
dipy.reconst.mapmri.
b_mat
(index_matrix)Calculates the B coefficients from [1] Eq. (27).
Parameters: |
|
---|---|
Returns: |
|
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.
dipy.reconst.mapmri.
b_mat_isotropic
(index_matrix)Calculates the isotropic B coefficients from [1] Fig 8.
Parameters: |
|
---|---|
Returns: |
|
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.
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: |
|
---|---|
Returns: |
|
dipy.reconst.mapmri.
create_rspace
(gridsize, radius_max)Create the real space table, that contains the points in which to compute the pdf.
Parameters: |
|
---|---|
Returns: |
|
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: |
|
---|---|
Returns: |
|
Examples
>>> from scipy.special import factorial2
>>> factorial2(7, exact=False)
array(105.00000000000001)
>>> factorial2(7, exact=True)
105L
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: |
|
---|---|
Returns: |
|
References
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: |
|
---|
dipy.reconst.mapmri.
genlaguerre
(n, alpha, monic=False)Generalized (associated) Laguerre polynomial.
Defined to be the solution of
where \(\alpha > -1\); \(L_n^{(\alpha)}\) is a polynomial of degree \(n\).
Parameters: |
|
---|---|
Returns: |
|
See also
laguerre
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\).
dipy.reconst.mapmri.
gradient_table
(bvals, bvecs=None, big_delta=None, small_delta=None, 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: |
|
---|---|
Returns: |
|
Notes
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
dipy.reconst.mapmri.
hermite
(n, monic=False)Physicist’s Hermite polynomial.
Defined by
\(H_n\) is a polynomial of degree \(n\).
Parameters: |
|
---|---|
Returns: |
|
Notes
The polynomials \(H_n\) are orthogonal over \((-\infty, \infty)\) with weight function \(e^{-x^2}\).
dipy.reconst.mapmri.
isotropic_scale_factor
(mu_squared)Estimated isotropic scaling factor _[1] Eq. (49).
Parameters: |
|
---|---|
Returns: |
|
References
[1] | Ozarslan E. et al., “Mean apparent propagator (MAP) MRI: A novel |
diffusion imaging method for mapping tissue microstructure”, NeuroImage, 2013.
dipy.reconst.mapmri.
map_laplace_s
(n, m)R(m,n) static matrix for Laplacian regularization [R932dd40ca52e-1] eq. (11). Parameters ———- n, m : unsigned int
basis order of the MAP-MRI basis in different directions
Returns: |
|
---|
References
using Laplacian-regularized MAP-MRI and its application to HCP data.” NeuroImage (2016).
dipy.reconst.mapmri.
map_laplace_t
(n, m)L(m, n) static matrix for Laplacian regularization [Reb78d789d6c4-1] eq. (12). Parameters ———- n, m : unsigned int
basis order of the MAP-MRI basis in different directions
Returns: |
|
---|
References
using Laplacian-regularized MAP-MRI and its application to HCP data.” NeuroImage (2016).
dipy.reconst.mapmri.
map_laplace_u
(n, m)S(n, m) static matrix for Laplacian regularization [Rb93dd9dab8c9-1] eq. (13). Parameters ———- n, m : unsigned int
basis order of the MAP-MRI basis in different directions
Returns: |
|
---|
References
using Laplacian-regularized MAP-MRI and its application to HCP data.” NeuroImage (2016).
dipy.reconst.mapmri.
mapmri_STU_reg_matrices
(radial_order)Generates the static portions of the Laplacian regularization matrix according to [R1d585103467a-1] eq. (11, 12, 13).
Parameters: |
|
---|---|
Returns: |
|
References
using Laplacian-regularized MAP-MRI and its application to HCP data.” NeuroImage (2016).
dipy.reconst.mapmri.
mapmri_index_matrix
(radial_order)Calculates the indices for the MAPMRI [1] basis in x, y and z.
Parameters: |
|
---|---|
Returns: |
|
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.
dipy.reconst.mapmri.
mapmri_isotropic_index_matrix
(radial_order)Calculates the indices for the isotropic MAPMRI basis [1] Fig 8.
Parameters: |
|
---|---|
Returns: |
|
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.
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: |
|
---|---|
Returns: |
|
References
using Laplacian-regularized MAP-MRI and its application to HCP data.” NeuroImage (2016).
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: |
|
---|---|
Returns: |
|
References
using Laplacian-regularized MAP-MRI and its application to HCP data.” NeuroImage (2016).
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: |
|
---|---|
Returns: |
|
References
[1] | (1, 2, 3, 4) 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).
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: |
|
---|---|
Returns: |
|
References
[1] | (1, 2, 3, 4) 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).
dipy.reconst.mapmri.
mapmri_isotropic_phi_matrix
(radial_order, mu, q)Three dimensional isotropic MAPMRI signal basis function from [1] Eq. (61).
Parameters: |
|
---|
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.
dipy.reconst.mapmri.
mapmri_isotropic_psi_matrix
(radial_order, mu, rgrad)Three dimensional isotropic MAPMRI propagator basis function from [1] Eq. (61).
Parameters: |
|
---|
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.
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: |
|
---|
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.
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: |
|
---|
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.
dipy.reconst.mapmri.
mapmri_laplacian_reg_matrix
(ind_mat, mu, S_mat, T_mat, U_mat)Puts 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: |
|
---|---|
Returns: |
|
References
using Laplacian-regularized MAP-MRI and its application to HCP data.” NeuroImage (2016).
dipy.reconst.mapmri.
mapmri_odf_matrix
(radial_order, mu, s, vertices)Compute the MAPMRI ODF matrix [1] Eq. (33).
Parameters: |
|
---|
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.
dipy.reconst.mapmri.
mapmri_phi_1d
(n, q, mu)One dimensional MAPMRI basis function from [1] Eq. (4).
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.
dipy.reconst.mapmri.
mapmri_phi_matrix
(radial_order, mu, q_gradients)Compute the MAPMRI phi matrix for the signal [1] eq. (23).
Parameters: |
|
---|
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.
dipy.reconst.mapmri.
mapmri_psi_1d
(n, x, mu)One dimensional MAPMRI propagator basis function from [1] Eq. (10).
Parameters: |
|
---|
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.
dipy.reconst.mapmri.
mapmri_psi_matrix
(radial_order, mu, rgrad)Compute the MAPMRI psi matrix for the propagator [1] eq. (22).
Parameters: |
|
---|
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.
dipy.reconst.mapmri.
optional_package
(name, trip_msg=None)Return package-like thing and module setup for package name
Parameters: |
|
---|---|
Returns: |
|
dipy.reconst.mapmri.
real_sph_harm
(m, n, theta, phi)Compute real spherical harmonics.
Where the real harmonic \(Y^m_n\) is defined to be:
Imag(\(Y^m_n\)) * sqrt(2) if m > 0 \(Y^0_n\) if m = 0 Real(\(Y^|m|_n\)) * sqrt(2) if m < 0
This may take scalar or array arguments. The inputs will be broadcasted against each other.
Parameters: |
|
---|---|
Returns: |
|
See also
scipy.special.sph_harm
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: |
|
---|---|
Returns: |
|
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:
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)
120L
dipy.reconst.mapmri.
sph_harm_ind_list
(sh_order)Returns the degree (n) and order (m) 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_sph_harm()
.
Parameters: |
|
---|---|
Returns: |
|
See also
CallableArray
dipy.reconst.multi_voxel.
CallableArray
Bases: numpy.ndarray
An array which can be called like a function
Attributes: |
|
---|
Methods
__call__ (*args, **kwargs) |
Call self as a function. |
all ([axis, out, keepdims]) |
Returns True if all elements evaluate to True. |
any ([axis, out, keepdims]) |
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 of a. |
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. |
dot (b[, out]) |
Dot product of two arrays. |
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]) |
Return the maximum along a given axis. |
mean ([axis, dtype, out, keepdims]) |
Returns the average of the array elements along given axis. |
min ([axis, out, keepdims]) |
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]) |
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 single-dimensional entries from the shape of a. |
std ([axis, dtype, out, ddof, keepdims]) |
Returns the standard deviation of the array elements along given axis. |
sum ([axis, dtype, out, keepdims]) |
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 a (possibly nested) list. |
tostring ([order]) |
Construct Python bytes containing the raw data bytes in the array. |
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]) |
Returns the variance of the array elements, along given axis. |
view ([dtype, type]) |
New view of array with the same data. |
MultiVoxelFit
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: |
|
---|
Methods
predict (*args, **kwargs) |
Predict for the multi-voxel object using each single-object’s prediction API, with S0 provided from an array. |
ReconstFit
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.
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: |
|
---|---|
Returns: |
|
See also
broadcast_to
reshape
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.
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: |
|
---|
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
dipy.reconst.odf.
OdfFit
(model, data)Bases: dipy.reconst.base.ReconstFit
Methods
odf (sphere) |
To be implemented but specific odf models |
OdfModel
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 |
ReconstFit
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.
ReconstModel
dipy.reconst.odf.
ReconstModel
(gtab)Bases: object
Abstract class for signal reconstruction models
Methods
fit |
dipy.reconst.odf.
gfa
(samples)The general fractional anisotropy of a function evaluated on the unit sphere
Parameters: |
|
---|---|
Returns: |
|
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. |
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: |
|
---|---|
Returns: |
|
InTemporaryDirectory
dipy.reconst.peaks.
InTemporaryDirectory
(suffix='', prefix='tmp', dir=None)Bases: nibabel.tmpdirs.TemporaryDirectory
Create, return, and change directory to a temporary directory
Examples
>>> import os
>>> my_cwd = os.getcwd()
>>> with InTemporaryDirectory() as tmpdir:
... _ = open('test.txt', 'wt').write('some text')
... assert os.path.isfile('test.txt')
... assert os.path.isfile(os.path.join(tmpdir, 'test.txt'))
>>> os.path.exists(tmpdir)
False
>>> os.getcwd() == my_cwd
True
Methods
cleanup |
PeaksAndMetrics
PeaksAndMetricsDirectionGetter
dipy.reconst.peaks.
PeaksAndMetricsDirectionGetter
Bases: dipy.tracking.local.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: |
|
---|
Methods
initial_direction |
The best starting directions for fiber tracking from point |
get_direction |
Sphere
dipy.reconst.peaks.
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: |
|
---|---|
Attributes: |
|
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)Initialize self. See help(type(self)) for accurate signature.
find_closest
(xyz)Find the index of the vertex in the Sphere closest to the input vector
Parameters: |
|
---|
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/____
/\ / / \ / /____\/____ x c z
Parameters: |
|
---|---|
Returns: |
|
repeat
dipy.reconst.peaks.
repeat
(object[, times]) → create an iterator which returns the objectBases: object
for the specified number of times. If not specified, returns the object endlessly.
dipy.reconst.peaks.
gfa
(samples)The general fractional anisotropy of a function evaluated on the unit sphere
Parameters: |
|
---|---|
Returns: |
|
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. |
dipy.reconst.peaks.
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: |
|
---|---|
Returns: |
|
See also
dipy.reconst.peaks.
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: |
|
---|
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)
dipy.reconst.peaks.
peak_directions
(odf, sphere, relative_peak_threshold=0.5, min_separation_angle=25, minmax_norm=True)Get the directions of odf peaks.
Peaks are defined as points on the odf that are greater than at least one neighbor and greater than or equal to all neighbors. Peaks are sorted in descending order by their values then filtered based on their relative size and spacing on the sphere. An odf may have 0 peaks, for example if the odf is perfectly isotropic.
Parameters: |
|
---|---|
Returns: |
|
Notes
If the odf has any negative values, they will be clipped to zeros.
dipy.reconst.peaks.
peak_directions_nl
(sphere_eval, relative_peak_threshold=0.25, min_separation_angle=25, sphere=<dipy.core.sphere.HemiSphere object>, xtol=1e-07)Non Linear Direction Finder.
Parameters: |
|
---|---|
Returns: |
|
dipy.reconst.peaks.
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, nbr_processes=None)Fit the model to data and computes peaks and metrics
Parameters: |
|
---|---|
Returns: |
|
References
[1] | (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. |
[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. |
dipy.reconst.peaks.
remove_similar_vertices
()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: |
|
---|---|
Returns: |
|
dipy.reconst.peaks.
search_descending
()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: |
|
---|---|
Returns: |
|
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
dipy.reconst.peaks.
sh_to_sf_matrix
(sphere, sh_order, basis_type=None, return_inv=True, smooth=0)Matrix that transforms Spherical harmonics (SH) to spherical function (SF).
Parameters: |
|
---|---|
Returns: |
|
References
[1] | (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. |
[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. |
Cache
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. |
cache_get
(tag, key, default=None)Retrieve a value from the cache.
Parameters: |
|
---|---|
Returns: |
|
cache_set
(tag, key, value)Store a value in the cache.
Parameters: |
|
---|
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
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: |
|
---|
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: |
|
---|
References
[1] | (1, 2) 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: |
|
---|
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. |
[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: |
|
---|
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. |
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: |
|
---|
References
[1] | (1, 2) 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: |
|
---|
References
[1] | (1, 2, 3) 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: |
|
---|
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. |
[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: |
|
---|
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. |
[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: |
|
---|
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. |
[3] | Fick, Rutger HJ, et al. “Non-Parametric GraphNet-Regularized Representation of dMRI in Space and Time”, Medical Image Analysis, 2017. |
QtdmriModel
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,
nowrap: |
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: |
|
---|
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')Initialize self. See help(type(self)) for accurate signature.
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. |
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: |
|
---|---|
Returns: |
|
dipy.reconst.qtdmri.
design_matrix_spatial
(bvecs, qvals, dtype=None)Constructs design matrix for DTI weighted least squares or least squares fitting. (Basser et al., 1994a)
Parameters: |
|
---|---|
Returns: |
|
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.
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: |
|
---|---|
Returns: |
|
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:
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)
120L
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: |
|
---|---|
Returns: |
|
Examples
>>> from scipy.special import factorial2
>>> factorial2(7, exact=False)
array(105.00000000000001)
>>> factorial2(7, exact=True)
105L
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: |
|
---|---|
Returns: |
|
See also
minimize
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
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. |
dipy.reconst.qtdmri.
genlaguerre
(n, alpha, monic=False)Generalized (associated) Laguerre polynomial.
Defined to be the solution of
where \(\alpha > -1\); \(L_n^{(\alpha)}\) is a polynomial of degree \(n\).
Parameters: |
|
---|---|
Returns: |
|
See also
laguerre
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\).
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: |
|
---|---|
Returns: |
|
Notes
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)
dipy.reconst.qtdmri.
optional_package
(name, trip_msg=None)Return package-like thing and module setup for package name
Parameters: |
|
---|---|
Returns: |
|
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. |
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. |
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. |
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. |
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. |
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. |
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. |
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
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. |
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: |
|
---|
References
[1] | Fick, Rutger HJ, et al. “Non-Parametric GraphNet-Regularized Representation of dMRI in Space and Time”, Medical Image Analysis, 2017. |
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. |
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. |
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
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: |
|
---|
References
[1] | Fick, Rutger HJ, et al. “Non-Parametric GraphNet-Regularized Representation of dMRI in Space and Time”, Medical Image Analysis, 2017. |
dipy.reconst.qtdmri.
real_sph_harm
(m, n, theta, phi)Compute real spherical harmonics.
Where the real harmonic \(Y^m_n\) is defined to be:
Imag(\(Y^m_n\)) * sqrt(2) if m > 0 \(Y^0_n\) if m = 0 Real(\(Y^|m|_n\)) * sqrt(2) if m < 0
This may take scalar or array arguments. The inputs will be broadcasted against each other.
Parameters: |
|
---|---|
Returns: |
|
See also
scipy.special.sph_harm
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: |
|
---|
Cache
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. |
cache_get
(tag, key, default=None)Retrieve a value from the cache.
Parameters: |
|
---|---|
Returns: |
|
cache_set
(tag, key, value)Store a value in the cache.
Parameters: |
|
---|
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
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: |
|
---|
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: |
|
---|
ExponentialIsotropicModel
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) |
|
IsotropicFit
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: |
|
---|
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: |
|
---|
IsotropicModel
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) |
Fit an IsotropicModel. |
ReconstFit
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.
ReconstModel
dipy.reconst.sfm.
ReconstModel
(gtab)Bases: object
Abstract class for signal reconstruction models
Methods
fit |
SparseFascicleFit
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: |
|
---|
odf
(sphere)The orientation distribution function of the SFM
Parameters: |
|
---|---|
Returns: |
|
predict
(gtab=None, response=None, S0=None)Predict the signal based on the SFM parameters
Parameters: |
|
---|---|
Returns: |
|
SparseFascicleModel
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)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]) |
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)Initialize a Sparse Fascicle Model
Parameters: |
|
---|
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: |
|
---|
fit
(data, mask=None)Fit the SparseFascicleModel object to data.
Parameters: |
|
---|---|
Returns: |
|
dipy.reconst.sfm.
auto_attr
(func)Decorator to create OneTimeProperty attributes.
Parameters: |
|
---|
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
dipy.reconst.sfm.
nanmean
(a, axis=None, dtype=None, out=None, keepdims=<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: |
|
---|---|
Returns: |
|
See also
average
mean
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])
dipy.reconst.sfm.
optional_package
(name, trip_msg=None)Return package-like thing and module setup for package name
Parameters: |
|
---|---|
Returns: |
|
dipy.reconst.sfm.
sfm_design_matrix
(gtab, sphere, response, mode='signal')Construct the SFM design matrix
Parameters: |
|
---|---|
Returns: |
|
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
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. |
cache_get
(tag, key, default=None)Retrieve a value from the cache.
Parameters: |
|
---|---|
Returns: |
|
cache_set
(tag, key, value)Store a value in the cache.
Parameters: |
|
---|
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
dipy.reconst.shm.
CsaOdfModel
(gtab, sh_order, smooth=0.006, min_signal=1.0, 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. |
LooseVersion
dipy.reconst.shm.
LooseVersion
(vstring=None)Bases: distutils.version.Version
Version numbering for anarchists and software realists. Implements the standard interface for version number classes as described above. A version number consists of a series of numbers, separated by either periods or strings of letters. When comparing version numbers, the numeric components will be compared numerically, and the alphabetic components lexically. The following are all valid version numbers, in no particular order:
1.5.1 1.5.2b2 161 3.10a 8.02 3.4j 1996.07.12 3.2.pl0 3.1.1.6 2g6 11g 0.960923 2.2beta29 1.13++ 5.5.kw 2.0b1pl0
In fact, there is no such thing as an invalid version number under this scheme; the rules for comparison are simple and predictable, but may not always give the results you want (for some definition of “want”).
Methods
parse |
OdfFit
dipy.reconst.shm.
OdfFit
(model, data)Bases: dipy.reconst.base.ReconstFit
Methods
odf (sphere) |
To be implemented but specific odf models |
OdfModel
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 |
OpdtModel
dipy.reconst.shm.
OpdtModel
(gtab, sh_order, smooth=0.006, min_signal=1.0, 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. |
QballBaseModel
dipy.reconst.shm.
QballBaseModel
(gtab, sh_order, smooth=0.006, min_signal=1.0, 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. |
QballModel
dipy.reconst.shm.
QballModel
(gtab, sh_order, smooth=0.006, min_signal=1.0, 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. |
ResidualBootstrapWrapper
dipy.reconst.shm.
ResidualBootstrapWrapper
(signal_object, B, where_dwi, min_signal=1.0)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=1.0)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: |
|
---|
SphHarmFit
dipy.reconst.shm.
SphHarmFit
(model, shm_coef, mask)Bases: dipy.reconst.odf.OdfFit
Diffusion data fit to a spherical harmonic model
Attributes: |
|
---|
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 |
odf
(sphere)Samples the odf function on the points of a sphere
Parameters: |
|
---|---|
Returns: |
|
SphHarmModel
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: |
|
---|
sampling_matrix
(sphere)The matrix needed to sample ODFs from coefficients of the model.
Parameters: |
|
---|---|
Returns: |
|
dipy.reconst.shm.
anisotropic_power
(sh_coeffs, norm_factor=1e-05, power=2, non_negative=True)Calculates anisotropic power map with a given SH coefficient matrix
Parameters: |
|
---|---|
Returns: |
|
rac{1}{2l+1} sum_{m=-l}^l{|a_{l,m}|^n}}
Where the last dimension, C, is made of a flattened array of \(l`x:math:`m\) coefficients, where \(l\) are the SH orders, and \(m = 2l+1\), So l=1 has 1 coeffecient, 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.
dipy.reconst.shm.
auto_attr
(func)Decorator to create OneTimeProperty attributes.
Parameters: |
|
---|
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
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. |
dipy.reconst.shm.
calculate_max_order
(n_coeffs)Parameters: |
|
---|---|
Returns: |
|
rac{1}{2} (L+1) (L+2)
arrow 2n = L^2 + 3L + 2
arrow L^2 + 3L + 2 - 2n = 0
arrow L^2 + 3L + 2(1-n) = 0
arrow L_{1,2} = rac{-3 pm sqrt{9 - 8 (1-n)}}{2}
arrow L{1,2} = rac{-3 pm sqrt{1 + 8n}}{2}
Finally, the positive value is chosen between the two options.
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: |
|
---|---|
Returns: |
|
dipy.reconst.shm.
concatenate
((a1, a2, ...), axis=0, out=None)Join a sequence of arrays along an existing axis.
Parameters: |
|
---|---|
Returns: |
|
See also
ma.concatenate
array_split
split
hsplit
vsplit
dsplit
stack
hstack
vstack
dstack
Notes
When one or more of the arrays to be concatenated is a MaskedArray, this function will return a MaskedArray object instead of an ndarray, but the input masks are not preserved. In cases where a MaskedArray is expected as input, use the ma.concatenate function from the masked array module instead.
Examples
>>> a = np.array([[1, 2], [3, 4]])
>>> b = np.array([[5, 6]])
>>> np.concatenate((a, b), axis=0)
array([[1, 2],
[3, 4],
[5, 6]])
>>> np.concatenate((a, b.T), axis=1)
array([[1, 2, 5],
[3, 4, 6]])
>>> np.concatenate((a, b), axis=None)
array([1, 2, 3, 4, 5, 6])
This function will not preserve masking of MaskedArray inputs.
>>> a = np.ma.arange(3)
>>> a[1] = np.ma.masked
>>> b = np.arange(2, 5)
>>> a
masked_array(data = [0 -- 2],
mask = [False True False],
fill_value = 999999)
>>> b
array([2, 3, 4])
>>> np.concatenate([a, b])
masked_array(data = [0 1 2 2 3 4],
mask = False,
fill_value = 999999)
>>> np.ma.concatenate([a, b])
masked_array(data = [0 -- 2 2 3 4],
mask = [False True False False False False],
fill_value = 999999)
dipy.reconst.shm.
diag
(v, k=0)Extract a diagonal or construct a diagonal array.
See the more detailed documentation for numpy.diagonal
if you use this
function to extract a diagonal and wish to write to the resulting array;
whether it returns a copy or a view depends on what version of numpy you
are using.
Parameters: |
|
---|---|
Returns: |
|
See also
diagonal
diagflat
trace
triu
tril
Examples
>>> x = np.arange(9).reshape((3,3))
>>> x
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> np.diag(x)
array([0, 4, 8])
>>> np.diag(x, k=1)
array([1, 5])
>>> np.diag(x, k=-1)
array([3, 7])
>>> np.diag(np.diag(x))
array([[0, 0, 0],
[0, 4, 0],
[0, 0, 8]])
dipy.reconst.shm.
diff
(a, n=1, axis=-1)Calculate the n-th discrete difference along the given axis.
The first difference is given by out[n] = a[n+1] - a[n]
along
the given axis, higher differences are calculated by using diff
recursively.
Parameters: |
|
---|---|
Returns: |
|
See also
gradient
, ediff1d
, cumsum
Notes
Type is preserved for boolean arrays, so the result will contain False when consecutive elements are the same and True when they differ.
For unsigned integer arrays, the results will also be unsigned. This should not be surprising, as the result is consistent with calculating the difference directly:
>>> u8_arr = np.array([1, 0], dtype=np.uint8)
>>> np.diff(u8_arr)
array([255], dtype=uint8)
>>> u8_arr[1,...] - u8_arr[0,...]
array(255, np.uint8)
If this is not desirable, then the array should be cast to a larger integer type first:
>>> i16_arr = u8_arr.astype(np.int16)
>>> np.diff(i16_arr)
array([-1], dtype=int16)
Examples
>>> x = np.array([1, 2, 4, 7, 0])
>>> np.diff(x)
array([ 1, 2, 3, -7])
>>> np.diff(x, n=2)
array([ 1, 1, -10])
>>> x = np.array([[1, 3, 6, 10], [0, 5, 6, 8]])
>>> np.diff(x)
array([[2, 3, 4],
[5, 1, 2]])
>>> np.diff(x, axis=0)
array([[-1, 2, 0, -2]])
>>> x = np.arange('1066-10-13', '1066-10-16', dtype=np.datetime64)
>>> np.diff(x)
array([1, 1], dtype='timedelta64[D]')
dipy.reconst.shm.
dot
(a, b, out=None)Dot product of two arrays. Specifically,
If both a and b are 1-D arrays, it is inner product of vectors (without complex conjugation).
If both a and b are 2-D arrays, it is matrix multiplication,
but using matmul()
or a @ b
is preferred.
If either a or b is 0-D (scalar), it is equivalent to multiply()
and using numpy.multiply(a, b)
or a * b
is preferred.
If a is an N-D array and b is a 1-D array, it is a sum product over the last axis of a and b.
If a is an N-D array and b is an M-D array (where M>=2
), it is a
sum product over the last axis of a and the second-to-last axis of b:
dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])
Parameters: |
|
---|---|
Returns: |
|
Raises: |
|
See also
vdot
tensordot
einsum
matmul
Examples
>>> np.dot(3, 4)
12
Neither argument is complex-conjugated:
>>> np.dot([2j, 3j], [2j, 3j])
(-13+0j)
For 2-D arrays it is the matrix product:
>>> a = [[1, 0], [0, 1]]
>>> b = [[4, 1], [2, 2]]
>>> np.dot(a, b)
array([[4, 1],
[2, 2]])
>>> a = np.arange(3*4*5*6).reshape((3,4,5,6))
>>> b = np.arange(3*4*5*6)[::-1].reshape((5,4,6,3))
>>> np.dot(a, b)[2,3,2,1,2,2]
499128
>>> sum(a[2,3,2,:] * b[1,2,:,2])
499128
dipy.reconst.shm.
empty
(shape, dtype=float, order='C')Return a new array of given shape and type, without initializing entries.
Parameters: |
|
---|---|
Returns: |
|
See also
empty_like
ones
zeros
full
Notes
empty, unlike zeros, does not set the array values to zero, and may therefore be marginally faster. On the other hand, it requires the user to manually set all the values in the array, and should be used with caution.
Examples
>>> np.empty([2, 2])
array([[ -9.74499359e+001, 6.69583040e-309],
[ 2.13182611e-314, 3.06959433e-309]]) #random
>>> np.empty([2, 2], dtype=int)
array([[-1073741821, -1067949133],
[ 496041986, 19249760]]) #random
dipy.reconst.shm.
eye
(N, M=None, k=0, dtype=<class 'float'>, order='C')Return a 2-D array with ones on the diagonal and zeros elsewhere.
Parameters: |
|
---|---|
Returns: |
|
See also
identity
diag
Examples
>>> np.eye(2, dtype=int)
array([[1, 0],
[0, 1]])
>>> np.eye(3, k=1)
array([[ 0., 1., 0.],
[ 0., 0., 1.],
[ 0., 0., 0.]])
dipy.reconst.shm.
forward_sdeconv_mat
(r_rh, n)Build forward spherical deconvolution matrix
Parameters: |
|
---|---|
Returns: |
|
dipy.reconst.shm.
gen_dirac
(m, n, theta, phi)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 by shm.real_sph_harm.
Parameters: |
|
---|---|
Returns: |
|
See also
shm.real_sph_harm
, shm.real_sym_sh_basis
dipy.reconst.shm.
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 |
dipy.reconst.shm.
pinv
(a, rcond=1e-15)Compute the (Moore-Penrose) pseudo-inverse of a matrix.
Calculate the generalized inverse of a matrix using its singular-value decomposition (SVD) and including all large singular values.
Changed in version 1.14: Can now operate on stacks of matrices
Parameters: |
|
---|---|
Returns: |
|
Raises: |
|
Notes
The pseudo-inverse of a matrix A, denoted \(A^+\), is defined as: “the matrix that ‘solves’ [the least-squares problem] \(Ax = b\),” i.e., if \(\bar{x}\) is said solution, then \(A^+\) is that matrix such that \(\bar{x} = A^+b\).
It can be shown that if \(Q_1 \Sigma Q_2^T = A\) is the singular value decomposition of A, then \(A^+ = Q_2 \Sigma^+ Q_1^T\), where \(Q_{1,2}\) are orthogonal matrices, \(\Sigma\) is a diagonal matrix consisting of A’s so-called singular values, (followed, typically, by zeros), and then \(\Sigma^+\) is simply the diagonal matrix consisting of the reciprocals of A’s singular values (again, followed by zeros). [1]
References
[1] | (1, 2) G. Strang, Linear Algebra and Its Applications, 2nd Ed., Orlando, FL, Academic Press, Inc., 1980, pp. 139-142. |
Examples
The following example checks that a * a+ * a == a
and
a+ * a * a+ == a+
:
>>> a = np.random.randn(9, 6)
>>> B = np.linalg.pinv(a)
>>> np.allclose(a, np.dot(a, np.dot(B, a)))
True
>>> np.allclose(B, np.dot(B, np.dot(a, B)))
True
dipy.reconst.shm.
randint
(low, high=None, size=None, dtype='l')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).
Parameters: |
|
---|---|
Returns: |
|
See also
random.random_integers
Examples
>>> np.random.randint(2, size=10)
array([1, 0, 0, 0, 1, 1, 0, 0, 1, 0])
>>> 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],
[3, 2, 2, 0]])
dipy.reconst.shm.
real_sph_harm
(m, n, theta, phi)Compute real spherical harmonics.
Where the real harmonic \(Y^m_n\) is defined to be:
Imag(\(Y^m_n\)) * sqrt(2) if m > 0 \(Y^0_n\) if m = 0 Real(\(Y^|m|_n\)) * sqrt(2) if m < 0
This may take scalar or array arguments. The inputs will be broadcasted against each other.
Parameters: |
|
---|---|
Returns: |
|
See also
scipy.special.sph_harm
dipy.reconst.shm.
real_sym_sh_basis
(sh_order, theta, phi)Samples a real symmetric spherical harmonic basis at point on the sphere
Samples the basis functions up to order sh_order at points on the sphere given by theta and phi. The basis functions are defined here the same way as in Descoteaux et al. 2007 [1] where the real harmonic \(Y^m_n\) is defined to be:
Imag(\(Y^m_n\)) * sqrt(2) if m > 0 \(Y^0_n\) if m = 0 Real(\(Y^|m|_n\)) * sqrt(2) if m < 0
This may take scalar or array arguments. The inputs will be broadcasted against each other.
Parameters: |
|
---|---|
Returns: |
|
References
[1] | (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. |
dipy.reconst.shm.
real_sym_sh_mrtrix
(sh_order, theta, phi)Compute real 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: |
|
---|---|
Returns: |
References
[1] | (1, 2) 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, 3, 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. |
dipy.reconst.shm.
sf_to_sh
(sf, sphere, sh_order=4, basis_type=None, smooth=0.0)Spherical function to spherical harmonics (SH).
Parameters: |
|
---|---|
Returns: |
|
References
[1] | (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. |
[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. |
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 m, degree n 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: |
|
---|---|
Returns: |
|
See also
shm.real_sph_harm
, shm.real_sym_sh_basis
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 |
dipy.reconst.shm.
sh_to_sf
(sh, sphere, sh_order, basis_type=None)Spherical harmonics (SH) to spherical function (SF).
Parameters: |
|
---|---|
Returns: |
|
References
[1] | (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. |
[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. |
dipy.reconst.shm.
sh_to_sf_matrix
(sphere, sh_order, basis_type=None, return_inv=True, smooth=0)Matrix that transforms Spherical harmonics (SH) to spherical function (SF).
Parameters: |
|
---|---|
Returns: |
|
References
[1] | (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. |
[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. |
dipy.reconst.shm.
smooth_pinv
(B, L)Regularized pseudo-inverse
Computes a regularized least square inverse of B
Parameters: |
|
---|---|
Returns: |
|
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.
dipy.reconst.shm.
sph_harm_ind_list
(sh_order)Returns the degree (n) and order (m) 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_sph_harm()
.
Parameters: |
|
---|---|
Returns: |
|
See also
dipy.reconst.shm.
spherical_harmonics
(m, n, theta, phi)Compute spherical harmonics
This may take scalar or array arguments. The inputs will be broadcasted against each other.
Parameters: |
|
---|---|
Returns: |
|
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
dipy.reconst.shm.
svd
(a, full_matrices=True, compute_uv=True)Singular Value Decomposition.
When a is a 2D array, it is factorized as u @ np.diag(s) @ vh
= (u * s) @ vh
, where u and vh are 2D unitary arrays and s is a 1D
array of a’s singular values. When a is higher-dimensional, SVD is
applied in stacked mode as explained below.
Parameters: |
|
---|---|
Returns: |
|
Raises: |
|
Notes
Changed in version 1.8.0: Broadcasting rules apply, see the numpy.linalg documentation for details.
The decomposition is performed using LAPACK routine _gesdd
.
SVD is usually described for the factorization of a 2D matrix \(A\).
The higher-dimensional case will be discussed below. In the 2D case, SVD is
written as \(A = U S V^H\), where \(A = a\), \(U= u\),
\(S= \mathtt{np.diag}(s)\) and \(V^H = vh\). The 1D array s
contains the singular values of a and u and vh are unitary. The rows
of vh are the eigenvectors of \(A^H A\) and the columns of u are
the eigenvectors of \(A A^H\). In both cases the corresponding
(possibly non-zero) eigenvalues are given by s**2
.
If a has more than two dimensions, then broadcasting rules apply, as
explained in routines.linalg-broadcasting. This means that SVD is
working in “stacked” mode: it iterates over all indices of the first
a.ndim - 2
dimensions and for each combination SVD is applied to the
last two indices. The matrix a can be reconstructed from the
decomposition with either (u * s[..., None, :]) @ vh
or
u @ (s[..., None] * vh)
. (The @
operator can be replaced by the
function np.matmul
for python versions below 3.5.)
If a is a matrix
object (as opposed to an ndarray
), then so are
all the return values.
Examples
>>> a = np.random.randn(9, 6) + 1j*np.random.randn(9, 6)
>>> b = np.random.randn(2, 7, 8, 3) + 1j*np.random.randn(2, 7, 8, 3)
Reconstruction based on full SVD, 2D case:
>>> u, s, vh = np.linalg.svd(a, full_matrices=True)
>>> u.shape, s.shape, vh.shape
((9, 9), (6,), (6, 6))
>>> np.allclose(a, np.dot(u[:, :6] * s, vh))
True
>>> smat = np.zeros((9, 6), dtype=complex)
>>> smat[:6, :6] = np.diag(s)
>>> np.allclose(a, np.dot(u, np.dot(smat, vh)))
True
Reconstruction based on reduced SVD, 2D case:
>>> u, s, vh = np.linalg.svd(a, full_matrices=False)
>>> u.shape, s.shape, vh.shape
((9, 6), (6,), (6, 6))
>>> np.allclose(a, np.dot(u * s, vh))
True
>>> smat = np.diag(s)
>>> np.allclose(a, np.dot(u, np.dot(smat, vh)))
True
Reconstruction based on full SVD, 4D case:
>>> u, s, vh = np.linalg.svd(b, full_matrices=True)
>>> u.shape, s.shape, vh.shape
((2, 7, 8, 8), (2, 7, 3), (2, 7, 3, 3))
>>> np.allclose(b, np.matmul(u[..., :3] * s[..., None, :], vh))
True
>>> np.allclose(b, np.matmul(u[..., :3], s[..., None] * vh))
True
Reconstruction based on reduced SVD, 4D case:
>>> u, s, vh = np.linalg.svd(b, full_matrices=False)
>>> u.shape, s.shape, vh.shape
((2, 7, 8, 3), (2, 7, 3), (2, 7, 3, 3))
>>> np.allclose(b, np.matmul(u * s[..., None, :], vh))
True
>>> np.allclose(b, np.matmul(u, s[..., None] * vh))
True
dipy.reconst.shm.
unique
(ar, return_index=False, return_inverse=False, return_counts=False, axis=None)Find the unique elements of an array.
Returns the sorted unique elements of an array. There are three optional outputs in addition to the unique elements:
Parameters: |
|
---|---|
Returns: |
|
See also
numpy.lib.arraysetops
Notes
When an axis is specified the subarrays indexed by the axis are sorted. This is done by making the specified axis the first dimension of the array and then flattening the subarrays in C order. The flattened subarrays are then viewed as a structured type with each element given a label, with the effect that we end up with a 1-D array of structured types that can be treated in the same way as any other 1-D array. The result is that the flattened subarrays are sorted in lexicographic order starting with the first element.
Examples
>>> np.unique([1, 1, 2, 2, 3, 3])
array([1, 2, 3])
>>> a = np.array([[1, 1], [2, 3]])
>>> np.unique(a)
array([1, 2, 3])
Return the unique rows of a 2D array
>>> a = np.array([[1, 0, 0], [1, 0, 0], [2, 3, 4]])
>>> np.unique(a, axis=0)
array([[1, 0, 0], [2, 3, 4]])
Return the indices of the original array that give the unique values:
>>> a = np.array(['a', 'b', 'b', 'c', 'a'])
>>> u, indices = np.unique(a, return_index=True)
>>> u
array(['a', 'b', 'c'],
dtype='|S1')
>>> indices
array([0, 1, 3])
>>> a[indices]
array(['a', 'b', 'c'],
dtype='|S1')
Reconstruct the input array from the unique values:
>>> a = np.array([1, 2, 6, 4, 2, 3, 2])
>>> u, indices = np.unique(a, return_inverse=True)
>>> u
array([1, 2, 3, 4, 6])
>>> indices
array([0, 1, 4, 3, 1, 2, 1])
>>> u[indices]
array([1, 2, 6, 4, 2, 3, 2])
Cache
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. |
cache_get
(tag, key, default=None)Retrieve a value from the cache.
Parameters: |
|
---|---|
Returns: |
|
cache_set
(tag, key, value)Store a value in the cache.
Parameters: |
|
---|
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
dipy.reconst.shore.
ShoreFit
(model, shore_coef)Bases: object
Attributes: |
|
---|
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: |
|
---|
msd
()Calculates the analytical mean squared displacement (MSD) [1]
nowrap: |
end{equation} |
---|
where \(\hat{\mathbf{r}}\) is a point in the 3D propagator space (see Wu et al. [1]).
References
[1] | (1, 2, 3, 4) Wu Y. et al., “Hybrid diffusion imaging”, NeuroImage, vol 36, |
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: |
|
---|---|
Returns: |
|
rtop_pdf
()Calculates the analytical return to origin probability (RTOP) from the pdf [1].
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.
ShoreModel
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\),
nowrap: |
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, 3) 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] | (1, 2) 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\),
nowrap: |
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: |
|
---|
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.
[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.
from dipy.data import get_fnames,get_sphere sphere = get_sphere(‘symmetric724’) fimg, fbvals, fbvecs = get_fnames(‘ISBI_testing_2shells_table’) bvals, bvecs = read_bvals_bvecs(fbvals, fbvecs) gtab = gradient_table(bvals, bvecs) from dipy.sims.voxel import SticksAndBall data, golden_directions = SticksAndBall(
gtab, d=0.0015, S0=1., angles=[(0, 0), (90, 0)], fractions=[50, 50], snr=None)
from dipy.reconst.canal import ShoreModel radial_order = 4 zeta = 700 asm = ShoreModel(gtab, radial_order=radial_order, zeta=zeta,
lambdaN=1e-8, lambdaL=1e-8)
asmfit = asm.fit(data) odf= asmfit.odf(sphere)
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: |
|
---|---|
Returns: |
|
dipy.reconst.shore.
create_rspace
(gridsize, radius_max)Parameters: |
|
---|---|
Returns: |
|
dipy.reconst.shore.
genlaguerre
(n, alpha, monic=False)Generalized (associated) Laguerre polynomial.
Defined to be the solution of
where \(\alpha > -1\); \(L_n^{(\alpha)}\) is a polynomial of degree \(n\).
Parameters: |
|
---|---|
Returns: |
|
See also
laguerre
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\).
dipy.reconst.shore.
optional_package
(name, trip_msg=None)Return package-like thing and module setup for package name
Parameters: |
|
---|---|
Returns: |
|
dipy.reconst.shore.
real_sph_harm
(m, n, theta, phi)Compute real spherical harmonics.
Where the real harmonic \(Y^m_n\) is defined to be:
Imag(\(Y^m_n\)) * sqrt(2) if m > 0 \(Y^0_n\) if m = 0 Real(\(Y^|m|_n\)) * sqrt(2) if m < 0
This may take scalar or array arguments. The inputs will be broadcasted against each other.
Parameters: |
|
---|---|
Returns: |
|
See also
scipy.special.sph_harm
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: |
|
---|---|
Returns: |
|
dipy.reconst.shore.
shore_matrix
(radial_order, zeta, gtab, tau=0.025330295910584444)Compute the SHORE matrix for modified Merlet’s 3D-SHORE [1]
nowrap: |
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: |
|
---|
References
[1] | (1, 2, 3) Merlet S. et al., “Continuous diffusion signal, EAP and |
ODF estimation via Compressive Sensing in diffusion MRI”, Medical Image Analysis, 2013.
dipy.reconst.shore.
shore_matrix_odf
(radial_order, zeta, sphere_vertices)Compute the SHORE ODF matrix [1]”
Parameters: |
|
---|
References
[1] | (1, 2, 3) Merlet S. et al., “Continuous diffusion signal, EAP and |
ODF estimation via Compressive Sensing in diffusion MRI”, Medical Image Analysis, 2013.
dipy.reconst.shore.
shore_matrix_pdf
(radial_order, zeta, rtab)Compute the SHORE propagator matrix [1]”
Parameters: |
|
---|
References
[1] | (1, 2, 3) Merlet S. et al., “Continuous diffusion signal, EAP and |
ODF estimation via Compressive Sensing in diffusion MRI”, Medical Image Analysis, 2013.
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: |
|
---|---|
Returns: |
|
dipy.reconst.utils.
dki_design_matrix
(gtab)Constructs B design matrix for DKI
Returns: |
|
---|