# `reconst`

## Module: `reconst.base`

Base-classes for reconstruction models and reconstruction fits.

All the models in the reconst module follow the same template: a Model object is used to represent the abstract properties of the model, that are independent of the specifics of the data . These properties are reused whenever fitting a particular set of data (different voxels, for example).

`ReconstModel`(gtab) | Abstract class for signal reconstruction models
`ReconstFit`(model, data) | Abstract class which holds the fit result of ReconstModel

## Module: `reconst.bingham`

Tools for fitting Bingham distributions to orientation distribution functions (ODF), as described in [1]. The resulting distributions can further be used to compute ODF-lobe-specific measures such as the fiber density (FD) and fiber spread (FS) [1] and the orientation dispersion index (ODI) [2].

### References

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

Till W. Riffert, Jan Schreiber, Alfred Anwander, and Thomas R. Knösche. Beyond fractional anisotropy: Extraction of bundle-specific structural metrics from crossing fiber models. NeuroImage, 100:176–191, 2014. URL: https://www.sciencedirect.com/science/article/pii/S1053811914004923, doi:10.1016/j.neuroimage.2014.06.015.

[2] (1,2,3,4,5,6,7,8,9)

Rafael Neto Henriques. Advanced Methods for Diffusion MRI Data Analysis and their Application to the Healthy Ageing Brain. PhD thesis, Cambridge University, Cambridge, United Kingdom, 2018. URL: https://doi.org/10.17863/CAM.29356, doi:10.17863/CAM.29356.

`BinghamMetrics`(model_params) | Class for Bingham Metrics.
`bingham_to_sf`(bingham_params, sphere, *[, mask]) | Reconstruct ODFs from fitted Bingham parameters on multiple voxels.
`bingham_fiber_density`(bingham_params, *[, ...]) | Compute fiber density for each lobe for a given Bingham ODF.
`bingham_fiber_spread`(f0, fd) | Compute fiber spread for each lobe for a given Bingham volume.
`k2odi`(k) | Convert the Bingham/Watson concentration parameter k to the orientation dispersion index (ODI).
`odi2k`(odi) | Convert the orientation dispersion index (ODI) to the Bingham/Watson concentration parameter k.
`weighted_voxel_metric`(bmetric, bfd) | Compute density-weighted scalar maps for metrics of Bingham functions fitted to multiple ODF lobes.
`sf_to_bingham`(odf, sphere, max_search_angle, *) | Fit the Bingham function from an image volume of ODFs.
`sh_to_bingham`(sh, sphere, max_search_angle, *) | Fit the Bingham function from an image volume of spherical harmonics (SH) representing ODFs.

## Module: `reconst.cache`

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

## Module: `reconst.cross_validation`

Cross-validation analysis of diffusion models.

`coeff_of_determination`(data, model, *[, axis]) | Calculate the coefficient of determination for a model prediction, relative to data.
`kfold_xval`(model, data, folds, *model_args, ...) | Perform k-fold cross-validation.

## Module: `reconst.csdeconv`

`AxSymShResponse`(S0, dwi_response, *[, bvalue]) | A simple wrapper for response functions represented using only axially symmetric, even spherical harmonic functions (ie, m == 0 and l is even).
`ConstrainedSphericalDeconvModel`(gtab, ...[, ...]) |
`ConstrainedSDTModel`(gtab, ratio, *[, ...]) |
`estimate_response`(gtab, evals, S0) | Estimate single fiber response function
`forward_sdt_deconv_mat`(ratio, l_values, *[, ...]) | Build forward sharpening deconvolution transform (SDT) matrix
`csdeconv`(dwsignal, X, B_reg, *[, tau, ...]) | Constrained-regularized spherical deconvolution (CSD).
`odf_deconv`(odf_sh, R, B_reg, *[, lambda_, ...]) | ODF constrained-regularized spherical deconvolution using the Sharpening Deconvolution Transform (SDT).
`odf_sh_to_sharp`(odfs_sh, sphere, *[, basis, ...]) | Sharpen odfs using the sharpening deconvolution transform.
`mask_for_response_ssst`(gtab, data, *[, ...]) | Computation of mask for single-shell single-tissue (ssst) response
`response_from_mask_ssst`(gtab, data, mask) | Computation of single-shell single-tissue (ssst) response
`auto_response_ssst`(gtab, data, *[, ...]) | Automatic estimation of single-shell single-tissue (ssst) response
`recursive_response`(gtab, data, *[, mask, ...]) | Recursive calibration of response function using peak threshold.
`fa_trace_to_lambdas`([fa, trace]) |

## Module: `reconst.cti`

Classes and functions for fitting the correlation tensor model

`CorrelationTensorModel`(gtab1, gtab2, *args) | Class for the Correlation Tensor Model
`CorrelationTensorFit`(model, model_params) | Class for fitting the Correlation Tensor Model
`from_qte_to_cti`(C) | Rescales the qte C elements to the C elements used in CTI.
`multi_gaussian_k_from_c`(ccti, MD) | Computes the multiple Gaussian diffusion kurtosis tensor from the covariance tensor.
`split_cti_params`(cti_params) | Splits CTI params into DTI, DKI, CTI portions.
`cti_prediction`(cti_params, gtab1, gtab2, *) | Predict a signal given correlation tensor imaging parameters.
`params_to_cti_params`(result, *[, ...]) |
`ls_fit_cti`(design_matrix, data, ...[, ...]) | Compute the diffusion kurtosis and covariance tensors using an ordinary or weighted linear least squares approach

## Module: `reconst.dki`

Classes and functions for fitting the diffusion kurtosis model.

`DiffusionKurtosisModel`(gtab, *args[, ...]) | Class for the Diffusion Kurtosis Model
`DiffusionKurtosisFit`(model, model_params, *) | Class for fitting the Diffusion Kurtosis Model
`carlson_rf`(x, y, z, *[, errtol]) | Compute the Carlson's incomplete elliptic integral of the first kind.
`carlson_rd`(x, y, z, *[, errtol]) | Compute the Carlson's incomplete elliptic integral of the second kind.
`directional_diffusion`(dt, V, *[, ...]) | Compute apparent diffusion coefficient (adc).
`directional_diffusion_variance`(kt, V) | Calculate the apparent diffusion variance (adv) in each direction of a sphere for a single voxel
`directional_kurtosis`(dt, md, kt, V, *[, ...]) | Calculate the apparent kurtosis coefficient (akc) in each direction of a sphere for a single voxel.
`apparent_kurtosis_coef`(dki_params, sphere, *) | Calculate the apparent kurtosis coefficient (AKC) in each direction of a sphere.
`mean_kurtosis`(dki_params, *[, min_kurtosis, ...]) | Compute mean kurtosis (MK) from the kurtosis tensor.
`radial_kurtosis`(dki_params, *[, ...]) | Compute radial kurtosis (RK) of a diffusion kurtosis tensor.
`axial_kurtosis`(dki_params, *[, ...]) | Compute axial kurtosis (AK) from the kurtosis tensor.
`kurtosis_maximum`(dki_params, *[, sphere, ...]) | Compute kurtosis maximum value.
`mean_kurtosis_tensor`(dki_params, *[, ...]) | Compute mean of the kurtosis tensor (MKT).
`radial_tensor_kurtosis`(dki_params, *[, ...]) | Compute the rescaled radial tensor kurtosis (RTK).
`kurtosis_fractional_anisotropy`(dki_params[, ...]) | Compute the anisotropy of the kurtosis tensor (KFA).
`dki_prediction`(dki_params, gtab, *[, S0]) | Predict a signal given diffusion kurtosis imaging parameters
`params_to_dki_params`(result, *[, ...]) | Convert the 21 unique elements of the diffusion and kurtosis tensors to the parameter format adopted in DIPY
`ls_fit_dki`(design_matrix, data, ...[, ...]) | Compute the diffusion and kurtosis tensors using an ordinary or weighted linear least squares approach.
`cls_fit_dki`(design_matrix, data, ...[, ...]) | Compute the diffusion and kurtosis tensors using a constrained ordinary or weighted linear least squares approach.
`Wrotate`(kt, Basis) | Rotate a kurtosis tensor from the standard Cartesian coordinate system to another coordinate system basis
`Wrotate_element`(kt, indi, indj, indk, indl, B) | Compute the specified index element of a kurtosis tensor rotated to the coordinate system basis B
`Wcons`(k_elements) | Construct the full 4D kurtosis tensors from its 15 independent elements
`split_dki_param`(dki_params) | Extract the diffusion tensor eigenvalues, the diffusion tensor eigenvector matrix, and the 15 independent elements of the kurtosis tensor from the model parameters estimated from the DKI model

## Module: `reconst.dki_micro`

Classes and functions for fitting the DKI-based microstructural model

`KurtosisMicrostructureModel`(gtab, *args[, ...]) | Class for the Diffusion Kurtosis Microstructural Model
`KurtosisMicrostructuralFit`(model, model_params) | Class for fitting the Diffusion Kurtosis Microstructural Model
`axonal_water_fraction`(dki_params, *[, ...]) | Computes the axonal water fraction from DKI.
`diffusion_components`(dki_params, *[, ...]) | Extracts the restricted and hindered diffusion tensors of well aligned fibers from diffusion kurtosis imaging parameters.
`dkimicro_prediction`(params, gtab, *[, S0]) | Signal prediction given the DKI microstructure model parameters.
`tortuosity`(hindered_ad, hindered_rd) | Computes the tortuosity of the hindered diffusion compartment given its axial and radial diffusivities

## Module: `reconst.dsi`

`DiffusionSpectrumModel`(gtab, *[, ...]) |
`DiffusionSpectrumFit`(model, data) |
`DiffusionSpectrumDeconvModel`(gtab, *[, ...]) |
`DiffusionSpectrumDeconvFit`(model, data) |
`create_qspace`(gtab, origin) | create the 3D grid which holds the signal values (q-space)
`create_qtable`(gtab, origin) | create a normalized version of gradients
`hanning_filter`(gtab, filter_width, origin) | create a hanning window
`pdf_interp_coords`(sphere, rradius, origin) | Precompute coordinates for ODF calculation from the PDF
`pdf_odf`(Pr, rradius, interp_coords) | Calculates the real ODF from the diffusion propagator(PDF) Pr
`half_to_full_qspace`(data, gtab) | Half to full Cartesian grid mapping
`project_hemisph_bvecs`(gtab) | Project any near identical bvecs to the other hemisphere
`threshold_propagator`(P, *[, estimated_snr]) | Applies hard threshold on the propagator to remove background noise for the deconvolution.
`gen_PSF`(qgrid_sampling, siz_x, siz_y, siz_z) | Generate a PSF for DSI Deconvolution by taking the ifft of the binary q-space sampling mask and truncating it to keep only the center.
`LR_deconv`(prop, psf, *[, numit, acc_factor]) | Perform Lucy-Richardson deconvolution algorithm on a 3D array.

## Module: `reconst.dti`

Classes and functions for fitting tensors.

`TensorModel`(gtab, *args[, fit_method, ...]) | Diffusion Tensor
`TensorFit`(model, model_params, *[, model_S0]) |
`fractional_anisotropy`(evals, *[, axis]) | Return Fractional anisotropy (FA) of a diffusion tensor.
`geodesic_anisotropy`(evals, *[, axis]) | Geodesic anisotropy (GA) of a diffusion tensor.
`mean_diffusivity`(evals, *[, axis]) | Mean Diffusivity (MD) of a diffusion tensor.
`axial_diffusivity`(evals, *[, axis]) | Axial Diffusivity (AD) of a diffusion tensor.
`radial_diffusivity`(evals, *[, axis]) | Radial Diffusivity (RD) of a diffusion tensor.
`trace`(evals, *[, axis]) | Trace of a diffusion tensor.
`color_fa`(fa, evecs) | Color fractional anisotropy of diffusion tensor
`determinant`(q_form) | The determinant of a tensor, given in quadratic form
`isotropic`(q_form) | Calculate the isotropic part of the tensor.
`deviatoric`(q_form) | Calculate the deviatoric (anisotropic) part of the tensor.
`norm`(q_form) | Calculate the Frobenius norm of a tensor quadratic form
`mode`(q_form) | Mode (MO) of a diffusion tensor.
`linearity`(evals, *[, axis]) | The linearity of the tensor.
`planarity`(evals, *[, axis]) | The planarity of the tensor.
`sphericity`(evals, *[, axis]) | The sphericity of the tensor.
`apparent_diffusion_coef`(q_form, sphere) | Calculate the apparent diffusion coefficient (ADC) in each direction of a sphere.
`tensor_prediction`(dti_params, gtab, S0) | Predict a signal given tensor parameters.
`iter_fit_tensor`(*[, step]) | Wrap a fit_tensor func and iterate over chunks of data with given length
`wls_fit_tensor`(design_matrix, data, *[, ...]) | Computes weighted least squares (WLS) fit to calculate self-diffusion tensor using a linear regression model.
`ols_fit_tensor`(design_matrix, data, *[, ...]) | Computes ordinary least squares (OLS) fit to calculate self-diffusion tensor using a linear regression model.
`nlls_fit_tensor`(design_matrix, data, *[, ...]) | Fit the cumulant expansion params (e.g. DTI, DKI) using non-linear least-squares.
`restore_fit_tensor`(design_matrix, data, *[, ...]) | Compute a robust tensor fit using the RESTORE algorithm.
`iterative_fit_tensor`(design_matrix, data, *) | Iteratively Reweighted fitting for the DTI/DKI model.
`robust_fit_tensor_wls`(design_matrix, data, *) | Iteratively Reweighted fitting for WLS for the DTI/DKI model.
`robust_fit_tensor_nlls`(design_matrix, data, *) | Iteratively Reweighted fitting for NLLS for the DTI/DKI model.
`from_lower_triangular`(D) | Returns a tensor given the six unique tensor elements
`lower_triangular`(tensor, *[, b0]) | Returns the six lower triangular values of the tensor ordered as (Dxx, Dxy, Dyy, Dxz, Dyz, Dzz) and a dummy variable if b0 is not None.
`decompose_tensor`(tensor, *[, min_diffusivity]) | Returns eigenvalues and eigenvectors given a diffusion tensor
`design_matrix`(gtab, *[, dtype]) | Constructs design matrix for DTI weighted least squares or least squares fitting.
`quantize_evecs`(evecs, *[, odf_vertices, ...]) | Find the closest orientation of an evenly distributed sphere
`eig_from_lo_tri`(data, *[, min_diffusivity]) | Calculates tensor eigenvalues/eigenvectors from an array containing the lower diagonal form of the six unique tensor elements.

## Module: `reconst.force`

`SignalIndex`(d) | Index for inner product similarity search.
`FORCEModel`(gtab, *[, simulations, penalty, ...]) | FORCE reconstruction model for signal matching based microstructure.
`FORCEFit`(model, params) | FORCE model fit results for a single voxel.
`normalize_signals`(signals) | L2-normalize signal array for cosine similarity search.
`create_signal_index`(signals_norm) | Create index for cosine similarity search.
`softmax_stable`(x, *[, axis]) | Numerically stable softmax.
`compute_uncertainty_ambiguity`(scores) | Compute uncertainty and ambiguity metrics from match scores.
`compute_microstructure_uncertainty_ambiguity`(...) | Compute per-microstructure uncertainty and ambiguity.
`postprocess_peaks`(preds, target_sphere, fracs) |
`compute_entropy`(weights) | Compute entropy of posterior weights.
`posterior_mean_signal`(signals, weights, indices) | Compute posterior mean signal from neighbors.
`posterior_odf`(odfs, weights, indices, n_dirs) | Compute posterior ODF from neighbors.
`force_peaks`(fitted_object, *[, mask, sh_order]) | Create a PeaksAndMetrics object from a FORCEFit or MultiVoxelFit.

## Module: `reconst.forecast`

`ForecastModel`(gtab, *[, sh_order_max, ...]) | Fiber ORientation Estimated using Continuous Axially Symmetric Tensors (FORECAST).
`ForecastFit`(model, data, sh_coef, d_par, d_perp) |
`find_signal_means`(b_unique, data_norm, ...) | Calculate the mean signal for each shell.
`forecast_error_func`(x, b_unique, E) | Calculates the difference between the mean signal calculated using the parameter vector x and the average signal E using FORECAST and SMT
`psi_l`(ell, b) |
`forecast_matrix`(sh_order_max, d_par, d_perp, ...) | Compute the FORECAST radial matrix
`rho_matrix`(sh_order_max, vecs) | Compute the SH matrix \(\rho\)
`lb_forecast`(sh_order_max) | Returns the Laplace-Beltrami regularization matrix for FORECAST

## Module: `reconst.fwdti`

Classes and functions for fitting tensors without free water contamination

`FreeWaterTensorModel`(gtab, *args[, fit_method]) | Class for the Free Water Elimination Diffusion Tensor Model
`FreeWaterTensorFit`(model, model_params) | Class for fitting the Free Water Tensor Model
`fwdti_prediction`(params, gtab, *[, S0, Diso]) | Signal prediction given the free water DTI model parameters.
`wls_iter`(design_matrix, sig, S0, *[, Diso, ...]) | Applies weighted linear least squares fit of the water free elimination model to single voxel signals.
`wls_fit_tensor`(gtab, data, *[, Diso, mask, ...]) | Computes weighted least squares (WLS) fit to calculate self-diffusion tensor using a linear regression model.
`nls_iter`(design_matrix, sig, S0, *[, Diso, ...]) | Applies non linear least squares fit of the water free elimination model to single voxel signals.
`nls_fit_tensor`(gtab, data, *[, mask, Diso, ...]) | Fit the water elimination tensor model using the non-linear least-squares.
`lower_triangular_to_cholesky`(tensor_elements) | Performs Cholesky decomposition of the diffusion tensor
`cholesky_to_lower_triangular`(R) | Convert Cholesky decomposition elements to the diffusion tensor elements

## Module: `reconst.gqi`

Classes and functions for generalized q-sampling

`GeneralizedQSamplingModel`(gtab, *[, method, ...]) |
`GeneralizedQSamplingFit`(model, data) |
`normalize_qa`(qa, *[, max_qa]) | Normalize quantitative anisotropy.
`squared_radial_component`(x, *[, tol]) | Part of the GQI2 integral
`npa`(self, odf, *[, width]) | non-parametric anisotropy
`equatorial_zone_vertices`(vertices, pole, *) | finds the 'vertices' in the equatorial zone conjugate to 'pole' with width half 'width' degrees
`polar_zone_vertices`(vertices, pole, *[, width]) | finds the 'vertices' in the equatorial band around the 'pole' of radius 'width' degrees
`upper_hemi_map`(v) | maps a 3-vector into the z-upper hemisphere
`equatorial_maximum`(vertices, odf, pole, width) |
`patch_vertices`(vertices, pole, width) | find 'vertices' within the cone of 'width' degrees around 'pole'
`patch_maximum`(vertices, odf, pole, width) |
`odf_sum`(odf) |
`patch_sum`(vertices, odf, pole, width) |
`triple_odf_maxima`(vertices, odf, width) |

## Module: `reconst.ivim`

Classes and functions for fitting ivim model

`IvimModelTRR`(gtab, *[, split_b_D, ...]) | Ivim model
`IvimModelVP`(gtab, *[, bounds, maxiter, xtol]) |
`IvimFit`(model, model_params) |
`ivim_prediction`(params, gtab) | The Intravoxel incoherent motion (IVIM) model function.
`f_D_star_prediction`(params, gtab, S0, D) | Function used to predict IVIM signal when S0 and D are known by considering f and D_star as the unknown parameters.
`f_D_star_error`(params, gtab, signal, S0, D) | Error function used to fit f and D_star keeping S0 and D fixed
`ivim_model_selector`(gtab, *[, fit_method]) | Selector function to switch between the 2-stage Trust-Region Reflective based NLLS fitting method (also containing the linear fit): trr and the Variable Projections based fitting method: varpro.

## Module: `reconst.mapmri`

`MapmriModel`(gtab, *[, radial_order, ...]) | Mean Apparent Propagator MRI (MAPMRI) of the diffusion signal.
`MapmriFit`(model, mapmri_coef, mu, R, lopt, *) |
`isotropic_scale_factor`(mu_squared) | Estimated isotropic scaling factor.
`mapmri_index_matrix`(radial_order) | Calculates the indices for the MAPMRI basis in x, y and z.
`b_mat`(index_matrix) | Calculates the B coefficients from
`b_mat_isotropic`(index_matrix) | Calculates the isotropic B coefficients.
`mapmri_phi_1d`(n, q, mu) | One dimensional MAPMRI basis function.
`mapmri_phi_matrix`(radial_order, mu, q_gradients) | Compute the MAPMRI phi matrix for the signal.
`mapmri_psi_1d`(n, x, mu) | One dimensional MAPMRI propagator basis function.
`mapmri_psi_matrix`(radial_order, mu, rgrad) | Compute the MAPMRI psi matrix for the propagator.
`mapmri_odf_matrix`(radial_order, mu, s, vertices) | Compute the MAPMRI ODF matrix.
`mapmri_isotropic_phi_matrix`(radial_order, mu, q) | Three dimensional isotropic MAPMRI signal basis function
`mapmri_isotropic_radial_signal_basis`(j, ...) | Radial part of the isotropic 1D-SHORE signal basis.
`mapmri_isotropic_M_mu_independent`(...) | Computed the mu independent part of the signal design matrix.
`mapmri_isotropic_M_mu_dependent`(...) | Computed the mu dependent part of the signal design matrix.
`mapmri_isotropic_psi_matrix`(radial_order, ...) | Three dimensional isotropic MAPMRI propagator basis function.
`mapmri_isotropic_radial_pdf_basis`(j, ...) | Radial part of the isotropic 1D-SHORE propagator basis.
`mapmri_isotropic_K_mu_independent`(...) | Computes mu independent part of K.
`mapmri_isotropic_K_mu_dependent`(...) | Computes mu dependent part of M.
`binomialfloat`(n, k) | Custom Binomial function
`mapmri_isotropic_odf_matrix`(radial_order, ...) | Compute the isotropic MAPMRI ODF matrix.
`mapmri_isotropic_odf_sh_matrix`(radial_order, ...) | Compute the isotropic MAPMRI ODF matrix.
`mapmri_isotropic_laplacian_reg_matrix`(...) | Computes the Laplacian regularization matrix for MAP-MRI's isotropic implementation.
`mapmri_isotropic_laplacian_reg_matrix_from_index_matrix`(...) | Computes the Laplacian regularization matrix for MAP-MRI's isotropic implementation.
`mapmri_isotropic_index_matrix`(radial_order) | Calculates the indices for the isotropic MAPMRI basis.
`create_rspace`(gridsize, radius_max) | Create the real space table, that contains the points in which to compute the pdf.
`delta`(n, m) |
`map_laplace_u`(n, m) | S(n, m) static matrix for Laplacian regularization.
`map_laplace_t`(n, m) | L(m, n) static matrix for Laplacian regularization.
`map_laplace_s`(n, m) | R(m,n) static matrix for Laplacian regularization.
`mapmri_STU_reg_matrices`(radial_order) | Generate the static portions of the Laplacian regularization matrix.
`mapmri_laplacian_reg_matrix`(ind_mat, mu, ...) | Put the Laplacian regularization matrix together.
`generalized_crossvalidation_array`(data, M, LR, *) | Generalized Cross Validation Function.
`generalized_crossvalidation`(data, M, LR, *) | Generalized Cross Validation Function.
`gcv_cost_function`(weight, args) | The GCV cost function that is iterated.

## Module: `reconst.mcsd`

`MultiShellResponse`(response, sh_order_max, ...) |
`MultiShellDeconvModel`(gtab, response[, ...]) |
`MSDeconvFit`(model, coeff, mask) |
`QpFitter`(X, reg) |
`multi_tissue_basis`(gtab, sh_order_max, iso_comp) | Builds a basis for multi-shell multi-tissue CSD model.
`solve_qp`(P, Q, G, H) | Helper function to set up and solve the Quadratic Program (QP) in CVXPY.
`multi_shell_fiber_response`(sh_order_max, ...) | Fiber response function estimation for multi-shell data.
`mask_for_response_msmt`(gtab, data, *[, ...]) | Computation of masks for multi-shell multi-tissue (msmt) response
`response_from_mask_msmt`(gtab, data, mask_wm, ...) | Computation of multi-shell multi-tissue (msmt) response
`auto_response_msmt`(gtab, data, *[, tol, ...]) | Automatic estimation of multi-shell multi-tissue (msmt) response

## Module: `reconst.msdki`

Classes and functions for fitting the mean signal diffusion kurtosis model

`MeanDiffusionKurtosisModel`(gtab, *args[, ...]) | Mean signal Diffusion Kurtosis Model
`MeanDiffusionKurtosisFit`(model, model_params, *) |
`mean_signal_bvalue`(data, gtab, *[, bmag]) | Computes the average signal across different diffusion directions for each unique b-value
`msk_from_awf`(f) | Computes mean signal kurtosis from axonal water fraction estimates of the SMT2 model
`awf_from_msk`(msk, *[, mask]) | Computes the axonal water fraction from the mean signal kurtosis assuming the 2-compartmental spherical mean technique model.
`msdki_prediction`(msdki_params, gtab, *[, S0]) | Predict the mean signal given the parameters of the mean signal DKI, an GradientTable object and S0 signal.
`wls_fit_msdki`(design_matrix, msignal, ng, *) | Fits the mean signal diffusion kurtosis imaging based on a weighted least square solution.
`design_matrix`(ubvals) | Constructs design matrix for the mean signal diffusion kurtosis model

## Module: `reconst.multi_voxel`

Tools to easily make multi voxel models

`MultiVoxelFit`(model, fit_array, mask) | Holds an array of fits and allows access to their attributes and methods
`CallableArray`(shape[, dtype, buffer, ...]) | An array which can be called like a function
`multi_voxel_fit`([_func, batched, ...]) | Method decorator to turn a single voxel model fit definition into a multi voxel model fit definition.

## Module: `reconst.odf`

`OdfModel`(gtab) | An abstract class to be sub-classed by specific odf models
`OdfFit`(model, data) |
`gfa`(samples) | The general fractional anisotropy of a function evaluated on the unit sphere
`minmax_normalize`(samples, *[, out]) | Min-max normalization of a function evaluated on the unit sphere

## Module: `reconst.qtdmri`

`QtdmriModel`(gtab, *[, radial_order, ...]) | The q:math:tau-dMRI model to analytically and continuously represent the q:math:tau diffusion signal attenuation over diffusion sensitization q and diffusion time \(\tau\).
`QtdmriFit`(model, qtdmri_coef, us, ut, ...) |
`qtdmri_to_mapmri_matrix`(radial_order, ...) | Generate the matrix that maps the qtdmri coefficients to MAP-MRI coefficients for the anisotropic case.
`qtdmri_isotropic_to_mapmri_matrix`(...) | Generate the matrix that maps the spherical qtdmri coefficients to MAP-MRI coefficients for the isotropic case.
`qtdmri_temporal_normalization`(ut) | Normalization factor for the temporal basis
`qtdmri_mapmri_normalization`(mu) | Normalization factor for Cartesian MAP-MRI basis.
`qtdmri_mapmri_isotropic_normalization`(j, ell, u0) | Normalization factor for Spherical MAP-MRI basis.
`qtdmri_signal_matrix`(radial_order, ...) | Constructs the design matrix as a product of 3 separated radial, angular and temporal design matrices.
`qtdmri_eap_matrix`(radial_order, time_order, ...) | Constructs the design matrix as a product of 3 separated radial, angular and temporal design matrices.
`qtdmri_isotropic_signal_matrix`(radial_order, ...) |
`qtdmri_isotropic_eap_matrix`(radial_order, ...) | Constructs the design matrix as a product of 3 separated radial, angular and temporal design matrices.
`radial_basis_opt`(j, ell, us, q) | Spatial basis dependent on spatial scaling factor us
`angular_basis_opt`(ell, m, q, theta, phi) | Angular basis independent of spatial scaling factor us.
`radial_basis_EAP_opt`(j, ell, us, r) |
`angular_basis_EAP_opt`(j, ell, m, r, theta, phi) |
`temporal_basis`(o, ut, tau) | Temporal basis dependent on temporal scaling factor ut
`qtdmri_index_matrix`(radial_order, time_order) | Computes the SHORE basis order indices according to [1].
`qtdmri_isotropic_index_matrix`(radial_order, ...) | Computes the SHORE basis order indices according to [1].
`qtdmri_laplacian_reg_matrix`(ind_mat, us, ut, *) | Computes the cartesian qt-dMRI Laplacian regularization matrix.
`qtdmri_isotropic_laplacian_reg_matrix`(...[, ...]) | Computes the spherical qt-dMRI Laplacian regularization matrix.
`part23_reg_matrix_q`(ind_mat, U_mat, T_mat, us) | Partial cartesian spatial Laplacian regularization matrix.
`part23_iso_reg_matrix_q`(ind_mat, us) | Partial spherical spatial Laplacian regularization matrix.
`part4_reg_matrix_q`(ind_mat, U_mat, us) | Partial cartesian spatial Laplacian regularization matrix.
`part4_iso_reg_matrix_q`(ind_mat, us) | Partial spherical spatial Laplacian regularization matrix.
`part1_reg_matrix_tau`(ind_mat, ut) | Partial temporal Laplacian regularization matrix.
`part23_reg_matrix_tau`(ind_mat, ut) | Partial temporal Laplacian regularization matrix.
`part4_reg_matrix_tau`(ind_mat, ut) | Partial temporal Laplacian regularization matrix.
`H`(value) | Step function of H(x)=1 if x>=0 and zero otherwise.
`generalized_crossvalidation`(data, M, LR, *) | Generalized Cross Validation Function.
`GCV_cost_function`(weight, arguments) | Generalized Cross Validation Function that is iterated.
`qtdmri_isotropic_scaling`(data, q, tau) | Constructs design matrix for fitting an exponential to the diffusion time points.
`qtdmri_anisotropic_scaling`(data, q, bvecs, tau) | Constructs design matrix for fitting an exponential to the diffusion time points.
`design_matrix_spatial`(bvecs, qvals) | Constructs design matrix for DTI weighted least squares or least squares fitting.
`create_rt_space_grid`(grid_size_r, ...) | Generates EAP grid (for potential positivity constraint).
`qtdmri_number_of_coefficients`(radial_order, ...) | Computes the total number of coefficients of the qtdmri basis given a radial and temporal order.
`l1_crossvalidation`(b0s_mask, E, M, *[, ...]) | cross-validation function to find the optimal weight of alpha for sparsity regularization
`elastic_crossvalidation`(b0s_mask, E, M, L, ...) | cross-validation function to find the optimal weight of alpha for sparsity regularization when also Laplacian regularization is used.
`visualise_gradient_table_G_Delta_rainbow`(gtab, *) | This function visualizes a q-tau acquisition scheme as a function of gradient strength and pulse separation (big_delta).

## Module: `reconst.qti`

Classes and functions for fitting the covariance tensor model of q-space trajectory imaging (QTI) by Westin et al.[3].

### References

[3] (1,2)

Carl-Fredrik Westin, Hans Knutsson, Ofer Pasternak, Filip Szczepankiewicz, Evren Özarslan, Danielle van Westen, Cecilia Mattisson, Mats Bogren, Lauren J. O’Donnell, Marek Kubicki, Daniel Topgaard, and Markus Nilsson. Q-space trajectory imaging for multidimensional diffusion MRI of the human brain. NeuroImage, 135:345–362, 2016. URL: https://doi.org/10.1016/j.neuroimage.2016.02.039, doi:10.1016/j.neuroimage.2016.02.039.

`QtiModel`(gtab, *[, fit_method, cvxpy_solver]) |
`QtiFit`(params) |
`from_3x3_to_6x1`(T) | Convert symmetric 3 x 3 matrices into 6 x 1 vectors.
`from_6x1_to_3x3`(V) | Convert 6 x 1 vectors into symmetric 3 x 3 matrices.
`from_6x6_to_21x1`(T) | Convert symmetric 6 x 6 matrices into 21 x 1 vectors.
`from_21x1_to_6x6`(V) | Convert 21 x 1 vectors into symmetric 6 x 6 matrices.
`cvxpy_1x6_to_3x3`(V) | Convert a 1 x 6 vector into a symmetric 3 x 3 matrix.
`cvxpy_1x21_to_6x6`(V) | Convert 1 x 21 vector into a symmetric 6 x 6 matrix.
`dtd_covariance`(DTD) | Calculate covariance of a diffusion tensor distribution (DTD).
`qti_signal`(gtab, D, C, *[, S0]) | Generate signals using the covariance tensor signal representation.
`design_matrix`(btens) | Calculate the design matrix from the b-tensors.

## Module: `reconst.rumba`

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

`RumbaSDModel`(gtab, *[, wm_response, ...]) |
`RumbaFit`(model, model_params) |
`rumba_deconv`(data, kernel, *[, n_iter, ...]) | Fit fODF and GM/CSF volume fractions for a voxel using RUMBA-SD.
`mbessel_ratio`(n, x) | Fast computation of modified Bessel function ratio (first kind).
`generate_kernel`(gtab, sphere, wm_response, ...) | Generate deconvolution kernel
`rumba_deconv_global`(data, kernel, mask, *[, ...]) | Fit fODF for all voxels simultaneously using RUMBA-SD.

## Module: `reconst.sfm`

The Sparse Fascicle Model.

This is an implementation of the sparse fascicle model described in Rokem et al.[4]. The multi b-value version of this model is described in Rokem et al.[5].

### References

[4]

Ariel Rokem, Jason D. Yeatman, Franco Pestilli, Kendrick N. Kay, Aviv Mezer, Stefan van der Walt, and Brian A. Wandell. Evaluating the Accuracy of Diffusion MRI Models in White Matter. PLOS ONE, 10(4):1–26, April 2015. URL: https://doi.org/10.1371/journal.pone.0123272, doi:10.1371/journal.pone.0123272.

[5] (1,2)

Ariel Rokem, Kimberly L. Chan, Jason D. Yeatman, Franco Pestilli, and Brian A. Wandel. Evaluating the accuracy of diffusion models at multiple b-values with cross-validation. In Joint Annual Meeting ISMRM-ESMRMB 2014 SMRT 23rd Annual Meeting, volume. Milan, Italy, 2014. International Society for Magnetic Resonance in Medicine (ISMRM).

`IsotropicModel`(gtab) | A base-class for the representation of isotropic signals.
`IsotropicFit`(model, params) | A fit object for representing the isotropic signal as the mean of the diffusion-weighted signal.
`ExponentialIsotropicModel`(gtab) | Representing the isotropic signal as a fit to an exponential decay function with b-values
`ExponentialIsotropicFit`(model, params) | A fit to the ExponentialIsotropicModel object, based on data.
`SparseFascicleModel`(gtab, *[, sphere, ...]) |
`SparseFascicleFit`(model, beta, S0, iso) |
`sfm_design_matrix`(gtab, sphere, response, *) | Construct the SFM design matrix

## Module: `reconst.shm`

Tools for using spherical harmonic models to fit diffusion data.

See [6], [7], [8], and [9].

### References

[6] (1,2)

Iman Aganj, Christophe Lenglet, and Guillermo Sapiro. ODF reconstruction in q-ball imaging with solid angle consideration. In 2009 IEEE International Symposium on Biomedical Imaging: From Nano to Macro, volume, 1398–1401. 2009. doi:10.1109/ISBI.2009.5193327.

[7] (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)

Maxime Descoteaux, Elaine Angelino, Shaun Fitzgibbons, and Rachid Deriche. Regularized, fast, and robust analytical Q-ball imaging. Magnetic Resonance in Medicine, 58(3):497–510, 2007. URL: https://doi.org/10.1002/mrm.21277, doi:10.1002/mrm.21277.

[8] (1,2)

Antonio Tristán-Vega, Carl-Fredrik Westin, and Santiago Aja-Fernández. Estimation of fiber Orientation Probability Density Functions in High Angular Resolution Diffusion Imaging. NeuroImage, 47(2):638–650, August 2009. URL: https://doi.org/10.1016/j.neuroimage.2009.04.049, doi:10.1016/j.neuroimage.2009.04.049.

[9] (1,2)

Antonio Tristán-Vega, Carl-Fredrik Westin, and Santiago Aja-Fernández. A new methodology for the estimation of fiber populations in the white matter of the brain with the Funk–Radon transform. NeuroImage, 49(2):1301–1315, 2010. URL: https://doi.org/10.1016/j.neuroimage.2009.09.070, doi:10.1016/j.neuroimage.2009.09.070.

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

`SphHarmModel`(gtab) | To be subclassed by all models that return a SphHarmFit when fit.
`QballBaseModel`(gtab, sh_order_max, *[, ...]) | To be subclassed by Qball type models.
`SphHarmFit`(model, shm_coef, mask) | Diffusion data fit to a spherical harmonic model
`CsaOdfModel`(gtab, sh_order_max, *[, smooth, ...]) | Implementation of Constant Solid Angle reconstruction method.
`OpdtModel`(gtab, sh_order_max, *[, smooth, ...]) | Implementation of Orientation Probability Density Transform reconstruction method.
`QballModel`(gtab, sh_order_max, *[, smooth, ...]) | Implementation of regularized Qball reconstruction method.
`ResidualBootstrapWrapper`(signal_object, B, ...) | Returns a residual bootstrap sample of the signal_object when indexed
`forward_sdeconv_mat`(r_rh, l_values) | Build forward spherical deconvolution matrix
`sh_to_rh`(r_sh, m_values, l_values) | Spherical harmonics (SH) to rotational harmonics (RH)
`gen_dirac`(m_values, l_values, theta, phi, *) | Generate Dirac delta function orientated in (theta, phi) on the sphere
`spherical_harmonics`(m_values, l_values, ...) | Compute spherical harmonics.
`real_sph_harm`(m_values, l_values, theta, phi) | Compute real spherical harmonics.
`real_sh_tournier_from_index`(m_values, ...[, ...]) | Compute real spherical harmonics.
`real_sh_descoteaux_from_index`(m_values, ...) | Compute real spherical harmonics.
`real_sh_tournier`(sh_order_max, theta, phi, *) | Compute real spherical harmonics.
`real_sh_descoteaux`(sh_order_max, theta, phi, *) | Compute real spherical harmonics.
`real_sym_sh_mrtrix`(sh_order_max, theta, phi) | dipy.reconst.shm.real_sym_sh_mrtrix is deprecated, Please use dipy.reconst.shm.real_sh_tournier instead
`real_sym_sh_basis`(sh_order_max, theta, phi) | Samples a real symmetric spherical harmonic basis at point on the sphere
`sph_harm_ind_list`(sh_order_max, *[, full_basis]) | Returns the order (`l`) and phase_factor (`m`) of all the symmetric spherical harmonics of order less then or equal to `sh_order_max`.
`order_from_ncoef`(ncoef, *[, full_basis]) | Given a number `n` of coefficients, calculate back the `sh_order_max`
`smooth_pinv`(B, L) | Regularized pseudo-inverse
`lazy_index`(index) | Produces a lazy index
`normalize_data`(data, where_b0, *[, ...]) | Normalizes the data with respect to the mean b0
`hat`(B) | Returns the hat matrix for the design matrix B
`lcr_matrix`(H) | Returns a matrix for computing leveraged, centered residuals from data
`bootstrap_data_array`(data, H, R, *[, permute]) | Applies the Residual Bootstraps to the data given H and R
`bootstrap_data_voxel`(data, H, R, *[, permute]) | Like bootstrap_data_array but faster when for a single voxel
`sf_to_sh`(sf, sphere, *[, sh_order_max, ...]) | Spherical function to spherical harmonics (SH).
`sh_to_sf`(sh, sphere, *[, sh_order_max, ...]) | Spherical harmonics (SH) to spherical function (SF).
`sh_to_sf_matrix`(sphere, *[, sh_order_max, ...]) | Matrix that transforms Spherical harmonics (SH) to spherical function (SF).
`calculate_max_order`(n_coeffs, *[, full_basis]) | Calculate the maximal harmonic order (l), given that you know the number of parameters that were estimated.
`anisotropic_power`(sh_coeffs, *[, ...]) | Calculate anisotropic power map with a given SH coefficient matrix.
`convert_sh_to_full_basis`(sh_coeffs) | Given an array of SH coeffs from a symmetric basis, returns the coefficients for the full SH basis by filling odd order SH coefficients with zeros
`convert_sh_from_legacy`(sh_coeffs, sh_basis, *) | Convert SH coefficients in legacy SH basis to SH coefficients of the new SH basis for `descoteaux07` or `tournier07` bases.
`convert_sh_to_legacy`(sh_coeffs, sh_basis, *) | Convert SH coefficients in new SH basis to SH coefficients for the legacy SH basis for `descoteaux07` or `tournier07` bases.
`convert_sh_descoteaux_tournier`(sh_coeffs) | Convert SH coefficients between legacy-descoteaux07 and tournier07.

## Module: `reconst.shore`

`ShoreModel`(gtab, *[, radial_order, zeta, ...]) | Simple Harmonic Oscillator based Reconstruction and Estimation (SHORE) of the diffusion signal.
`ShoreFit`(model, shore_coef) |
`shore_matrix`(radial_order, zeta, gtab, *[, tau]) | Compute the SHORE matrix for modified Merlet's 3D-SHORE.
`shore_matrix_pdf`(radial_order, zeta, rtab) | Compute the SHORE propagator matrix.
`shore_matrix_odf`(radial_order, zeta, ...) | Compute the SHORE ODF matrix.
`l_shore`(radial_order) | Returns the angular regularisation matrix for SHORE basis
`n_shore`(radial_order) | Returns the angular regularisation matrix for SHORE basis
`create_rspace`(gridsize, radius_max) | Create the real space table, that contains the points in which
`shore_indices`(radial_order, index) | Given the basis order and the index, return the shore indices n, l, m for modified Merlet's 3D-SHORE
`shore_order`(n, ell, m) | Given the indices (n,l,m) of the basis, return the minimum order for those indices and their index for modified Merlet's 3D-SHORE.

## Module: `reconst.utils`

`dki_design_matrix`(gtab) | Construct B design matrix for DKI.
`cti_design_matrix`(gtab1, gtab2) | Construct B design matrix for CTI.
`convert_tensors`(tensor, from_format, to_format) | Convert tensors from one format to another.

## Module: `reconst.weights_method`

Functions for defining weights for iterative fitting methods.

`simple_cutoff`(residuals, log_residuals, ...) | Define outliers based on the signal (rather than the log-signal).
`two_eyes_cutoff`(residuals, log_residuals, ...) | Define outliers with two-eyes approach.
`weights_method_wls_m_est`(data, pred_sig, ...) | Calculate M-estimator weights for WLS model.
`weights_method_nlls_m_est`(data, pred_sig, ...) | Calculate M-estimator weights for NLLS model.

### `ReconstModel`

class dipy.reconst.base.ReconstModel(gtab)

  Bases: `object`

  Abstract class for signal reconstruction models

  Methods

  fit |

### `ReconstFit`

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

  Bases: `object`

  Abstract class which holds the fit result of ReconstModel

  For example that could be holding FA or GFA etc.

### `BinghamMetrics`

class dipy.reconst.bingham.BinghamMetrics(model_params)

  Bases: `object`

  Class for Bingham Metrics.

  Methods

  `amplitude_lobe`() | Maximum Bingham Amplitude for each ODF lobe.
  `fd_lobe`() | Fiber Density computed as the integral of the Bingham functions fitted for each ODF lobe.
  `fd_voxel`() | Voxel fiber density (sum of fd estimates of all ODF lobes).
  `fs_lobe`() | Fiber spread computed for each ODF lobe.
  `fs_voxel`() | Voxel fiber spread (weighted average of fiber spread across all lobes where the weights are each lobe's fd estimate).
  `kappa1_lobe`() | Concentration parameter k1 for each ODF lobe.
  `kappa2_lobe`() | Concentration parameter k2 for each ODF lobe.
  `kappa_total_lobe`() | Overall concentration parameters for an ODF peak.
  `odf`(sphere) | Reconstruct ODFs from fitted Bingham parameters on multiple voxels.
  `odi1_lobe`() | Orientation Dispersion index 1 computed for each ODF lobe from concentration parameter kappa1.
  `odi1_voxel`() | Voxel Orientation Dispersion Index 1 (weighted average of odi1 across all lobes where the weights are each lobe's fd estimate).
  `odi2_lobe`() | Orientation Dispersion index 2 computed for each ODF lobe from concentration parameter kappa2.
  `odi2_voxel`() | Voxel Orientation Dispersion Index 2 (weighted average of odi2 across all lobes where the weights are each lobe's fd estimate).
  `odi_total_lobe`() | Overall Orientation Dispersion Index (ODI) for an ODF lobe.
  `odi_total_voxel`() | Voxel total Orientation Dispersion Index (weighted average of odf_total across all lobes where the weights are each lobe's fd estimate).

  amplitude_lobe()

    Maximum Bingham Amplitude for each ODF lobe. Measured in the unit 1/mm^3*rad.

  fd_lobe()

    Fiber Density computed as the integral of the Bingham functions fitted for each ODF lobe.

  fd_voxel()

    Voxel fiber density (sum of fd estimates of all ODF lobes).

  fs_lobe()

    Fiber spread computed for each ODF lobe.

    Notes

    Fiber spread (fs) is defined as fs = fd/f0 and characterizes the spread of the lobe, i.e. the higher the fs, the wider the lobe [1].

    References

  fs_voxel()

    Voxel fiber spread (weighted average of fiber spread across all lobes where the weights are each lobe’s fd estimate).

  kappa1_lobe()

    Concentration parameter k1 for each ODF lobe.

  kappa2_lobe()

    Concentration parameter k2 for each ODF lobe.

  kappa_total_lobe()

    Overall concentration parameters for an ODF peak.

    The overall (combined) concentration parameters for each lobe is defined by equation 19 in [10] as

    \[k_{total} = sqrt{(k_1 * k_2)}\]

    References

    [10] (1,2)

    Maira Tariq, Torben Schneider, Daniel C. Alexander, Claudia A. Gandini Wheeler-Kingshott, and Hui Zhang. Bingham-Noddi: Mapping anisotropic orientation dispersion of neurites using diffusion MRI. NeuroImage, 133:207–223, 2016. URL: https://doi.org/10.1016/j.neuroimage.2016.01.046, doi:10.1016/j.neuroimage.2016.01.046.

  odf(sphere)

    Reconstruct ODFs from fitted Bingham parameters on multiple voxels.

    Parameters:
      sphere: `Sphere` class instance

        The Sphere providing the discrete directions for ODF reconstruction.

    Returns:
      ODF ndarray (…, n_directions)

        The value of the odf on each point of sphere.

  odi1_lobe()

    Orientation Dispersion index 1 computed for each ODF lobe from concentration parameter kappa1.

  odi1_voxel()

    Voxel Orientation Dispersion Index 1 (weighted average of odi1 across all lobes where the weights are each lobe’s fd estimate).

  odi2_lobe()

    Orientation Dispersion index 2 computed for each ODF lobe from concentration parameter kappa2.

  odi2_voxel()

    Voxel Orientation Dispersion Index 2 (weighted average of odi2 across all lobes where the weights are each lobe’s fd estimate).

  odi_total_lobe()

    Overall Orientation Dispersion Index (ODI) for an ODF lobe.

    Overall Orientation Dispersion Index (ODI) computed for an ODF lobe from the overall concentration parameter (k_total). Defined by equation 20 in [10].

    References

  odi_total_voxel()

    Voxel total Orientation Dispersion Index (weighted average of odf_total across all lobes where the weights are each lobe’s fd estimate).

### bingham_to_sf

dipy.reconst.bingham.bingham_to_sf(bingham_params, sphere, *, mask=None)

  Reconstruct ODFs from fitted Bingham parameters on multiple voxels.

  Parameters:
    bingham_params ndarray (…., nl, 12)

      ndarray containing the model parameters of Binghams fitted to ODFs in the following order: - Maximum value of the Bingham function (f0, index 0); - concentration parameters k1 and k2 (indexes 1 and 2); - elements of Bingham’s main direction (indexes 3-5); - elements of Bingham’s dispersion major axis (indexes 6-8); - elements of Bingham’s dispersion minor axis (indexes 9-11).

    sphere: `Sphere` class instance

      The Sphere providing the odf’s discrete directions

    mask: ndarray, optional

      Map marking the coordinates in the data that should be analyzed. Default (None) means all voxels in the volume will be analyzed.

  Returns:
    ODF ndarray (…, n_directions)

      The value of the odf on each point of sphere.

### bingham_fiber_density

dipy.reconst.bingham.bingham_fiber_density(bingham_params, *, subdivide=5, mask=None)

  Compute fiber density for each lobe for a given Bingham ODF. Measured in the unit 1/mm^3.

  Parameters:
    bingham_params ndarray (…., nl, 12)

      ndarray containing the model parameters of Bingham’s fitted to ODFs in the following order: - Maximum value of the Bingham function (f0, index 0); - Concentration parameters k1 and k2 (indexes 1 and 2); - Elements of Bingham’s main direction (indexes 3-5); - Elements of Bingham’s dispersion major axis (indexes 6-8); - Elements of Bingham’s dispersion minor axis (indexes 9-11).

    subdivide: int >= 0, optional

      Number of times the unit icosahedron used for integration should be subdivided. The higher this value the more precise the approximation will be, at the cost of longer execution times. The default results in a sphere of 10242 points.

    mask: ndarray, optional

      Map marking the coordinates in the data that should be analyzed. Default (None) means all voxels in the volume will be analyzed.

  Returns:
    fd: ndarray (…., nl)

      Fiber density for each Bingham function.

  Notes

  Fiber density (fd) is given by the surface integral of the Bingham function [1].

  References

### bingham_fiber_spread

dipy.reconst.bingham.bingham_fiber_spread(f0, fd)

  Compute fiber spread for each lobe for a given Bingham volume. Measured in radians.

  Parameters:
    f0: ndarray

      Peak amplitude (f0) of each Bingham function.

    fd: ndarray

      Fiber density (fd) of each Bingham function.

  Returns:
    fs: list of floats

      Fiber spread (fs) of each each Bingham function.

  Notes

  Fiber spread (fs) is defined as fs = fd/f0 and characterizes the spread of the lobe, i.e. the higher the fs, the wider the lobe [1].

  References

### k2odi

dipy.reconst.bingham.k2odi(k)

  Convert the Bingham/Watson concentration parameter k to the orientation dispersion index (ODI).

  Parameters:
    k: ndarray

      Watson/Bingham concentration parameter

  Returns:
    ODI: float or ndarray

      Orientation Dispersion Index

  Notes

  Orientation Dispersion Index for Watson/Bingham functions are defined as [2], [11]:

  \[ODI = \frac{2}{pi} \arctan{( \frac{1}{k})}\]

  References

  [11] (1,2)

  Hui Zhang, Torben Schneider, Claudia A. Wheeler-Kingshott, and Daniel C. Alexander. Noddi: practical in vivo neurite orientation dispersion and density imaging of the human brain. NeuroImage, 61(4):1000–1016, 2012. URL: https://doi.org/10.1016/j.neuroimage.2012.03.072, doi:10.1016/j.neuroimage.2012.03.072.

### odi2k

dipy.reconst.bingham.odi2k(odi)

  Convert the orientation dispersion index (ODI) to the Bingham/Watson concentration parameter k.

  Parameters:
    ODI: ndarray

      Orientation Dispersion Index

  Returns:
    k: float or ndarray

      Watson/Bingham concentration parameter

  Notes

  Orientation Dispersion Index for Watson/Bingham functions are defined as [2], [11]:

  \[ODI = \frac{2}{pi} \arctan ( \frac{1}{k} )\]

  References

### weighted_voxel_metric

dipy.reconst.bingham.weighted_voxel_metric(bmetric, bfd)

  Compute density-weighted scalar maps for metrics of Bingham functions fitted to multiple ODF lobes. The metric is computed as the weighted average of a given metric across the multiple ODF lobes (weights are defined by the Bingham fiber density estimates).

  Parameters:
    bmetric: ndarray(…, nl)

      Any metric with values for nl ODF lobes.

    bfd: ndarray(…, nl)

      Bingham’s fiber density estimates for the nl ODF lobes

  Returns:
    wmetric: ndarray(…)

      Weight-averaged Bingham metric

### sf_to_bingham

dipy.reconst.bingham.sf_to_bingham(odf, sphere, max_search_angle, *, mask=None, npeaks=5, min_sep_angle=60, rel_th=0.1)

  Fit the Bingham function from an image volume of ODFs.

  Parameters:
    odf: ndarray (Nx, Ny, Nz, Ndirs)

      Orientation Distribution Function sampled on the vertices of a sphere.

    sphere: `Sphere` class instance

      The Sphere providing the odf’s discrete directions.

    max_search_angle: float.

      Maximum angle between a peak and its neighbour directions for fitting the Bingham distribution.

    mask: ndarray, optional

      Map marking the coordinates in the data that should be analyzed.

    npeak: int, optional

      Maximum number of peaks found.

    min_sep_angle: float, optional

      Minimum separation angle between two peaks for peak extraction.

    rel_th: float, optional

      Relative threshold used for peak extraction.

  Returns:
    BinghamMetrics: class instance

      Class instance containing metrics computed from Bingham functions fitted to ODF lobes.

### sh_to_bingham

dipy.reconst.bingham.sh_to_bingham(sh, sphere, max_search_angle, *, mask=None, sh_basis='descoteaux07', legacy=True, npeaks=5, min_sep_angle=60, rel_th=0.1)

  Fit the Bingham function from an image volume of spherical harmonics (SH) representing ODFs.

  Parameters:
    sh ndarray

      SH coefficients representing a spherical function.

    sphere Sphere class instance

      The Sphere providing the odf’s discrete directions.

    max_search_angle: float.

      Maximum angle between a peak and its neighbour directions for fitting the Bingham distribution.

    mask: ndarray, optional

      Map marking the coordinates in the data that should be analyzed.

    sh_basis: str, optional

      SH basis. Either descoteaux07 or tournier07.

    legacy: bool, optional

      Use legacy SH basis definitions.

    npeak: int, optional

      Maximum number of peaks found.

    min_sep_angle: float, optional

      Minimum separation angle between two peaks for peak extraction.

    rel_th: float, optional

      Relative threshold used for peak extraction.

  Returns:
    BinghamMetrics: class instance

      Class instance containing metrics computed from Bingham functions fitted to ODF lobes.

### `Cache`

class dipy.reconst.cache.Cache

  Bases: `object`

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

  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.

  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)

  cache_clear()

    Clear the cache.

  cache_get(tag, key, *, default=None)

    Retrieve a value from the cache.

    Parameters:
      tag str

        Description of the cached value.

      key object

        Key object used to look up the cached value.

      default object

        Value to be returned if no cached entry is found.

    Returns:
      v object

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

  cache_set(tag, key, value)

    Store a value in the cache.

    Parameters:
      tag str

        Description of the cached value.

      key object

        Key object used to look up the cached value.

      value object

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

    Examples

        >>> def compute_expensive_matrix(parameters):
        ...     # Imagine the following computation is very expensive
        ...     return (p**2 for p in parameters)

        >>> c = Cache()

        >>> parameters = (1, 2, 3)
        >>> X1 = compute_expensive_matrix(parameters)

        >>> c.cache_set('expensive_matrix', parameters, X1)
        >>> X2 = c.cache_get('expensive_matrix', parameters)

        >>> X1 is X2
        True

### coeff_of_determination

dipy.reconst.cross_validation.coeff_of_determination(data, model, *, axis=-1)

  Calculate the coefficient of determination for a model prediction, relative to data.

  Parameters:
    data ndarray

      The data

    model ndarray

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

    axis: int, optional

      The axis along which different samples are laid out.

  Returns:
    COD ndarray

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

  Notes

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

  The coefficient of determination is calculated as:

  \[R^2 = 100 * (1 - \frac{SSE}{SSD})\]

  where SSE is the sum of the squared error between the model and the data (sum of the squared residuals) and SSD is the sum of the squares of the deviations of the data from the mean of the data (variance * N).

### kfold_xval

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

  Perform k-fold cross-validation.

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

  See [5] for further details about the method.

  Parameters:
    model Model class instance

      The type of the model to use for prediction. The corresponding Fit object must have a predict function implemented One of the following: reconst.dti.TensorModel or reconst.csdeconv.ConstrainedSphericalDeconvModel.

    data ndarray

      Diffusion MRI data acquired with the GradientTable of the model. Shape will typically be (x, y, z, b) where xyz are spatial dimensions and b is the number of bvals/bvecs in the GradientTable.

    folds int

      The number of divisions to apply to the data

    model_args list

      Additional arguments to the model initialization

    model_kwargs dict

      Additional key-word arguments to the model initialization. If contains the kwarg mask, this will be used as a key-word argument to the fit method of the model object, rather than being used in the initialization of the model object

  Notes

  This function assumes that a prediction API is implemented in the Model class for which prediction is conducted. That is, the Fit object that gets generated upon fitting the model needs to have a predict method, which receives a GradientTable class instance as input and produces a predicted signal as output.

  It also assumes that the model object has bval and bvec attributes holding b-values and corresponding unit vectors.

  References

### `AxSymShResponse`

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

  Bases: `object`

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

  Parameters:
    S0 float

      Signal with no diffusion weighting.

    dwi_response array

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

  Methods

  `basis`(sphere) | A basis that maps the response coefficients onto a sphere.
  `on_sphere`(sphere) | Evaluates the response function on sphere.

  basis(sphere)

    A basis that maps the response coefficients onto a sphere.

  on_sphere(sphere)

    Evaluates the response function on sphere.

### `ConstrainedSphericalDeconvModel`

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

  Bases: `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.

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

    Fit method for every voxel in data

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

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

    Parameters:
      sh_coeff ndarray

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

      gtab GradientTable

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

      S0 ndarray or float

        The non diffusion-weighted signal value.

    Returns:
      pred_sig ndarray

        The predicted signal.

### `ConstrainedSDTModel`

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

  Bases: `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.

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

    Fit method for every voxel in data

### estimate_response

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

  Estimate single fiber response function

  Parameters:
    gtab GradientTable

      Gradient table.

    evals ndarray

      Eigenvalues.

    S0 float

      non diffusion weighted

  Returns:
    S estimated signal

### forward_sdt_deconv_mat

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

  Build forward sharpening deconvolution transform (SDT) matrix

  Parameters:
    ratio float

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

    l_values ndarray (N,)

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

    r2_term bool

      True if ODF comes from an ODF computed from a model using the \(r^2\) term in the integral. For example, DSI, GQI, SHORE, CSA, Tensor, Multi-tensor ODFs. This results in using the proper analytical response function solution solving from the single-fiber ODF with the r^2 term. This derivation is not published anywhere but is very similar to [12].

  Returns:
    R ndarray (N, N)

      SDT deconvolution matrix

    P ndarray (N, N)

      Funk-Radon Transform (FRT) matrix

  References

  [12] (1,2,3)

  Maxime Descoteaux. High Angular Resolution Diffusion MRI: from Local Estimation to Segmentation and Tractography. PhD thesis, Université Nice Sophia Antipolis, Valbonne, France, 2007. URL: https://theses.hal.science/tel-00457458, doi:.

### csdeconv

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

  Constrained-regularized spherical deconvolution (CSD).

  Deconvolves the axially symmetric single fiber response function r_rh in rotational harmonics coefficients from the diffusion weighted signal in dwsignal [13].

  Parameters:
    dwsignal array

      Diffusion weighted signals to be deconvolved.

    X array

      Prediction matrix which estimates diffusion weighted signals from FOD coefficients.

    B_reg array (N, B)

      SH basis matrix which maps FOD coefficients to FOD values on the surface of the sphere. B_reg should be scaled to account for lambda.

    tau float

      Threshold controlling the amplitude below which the corresponding fODF is assumed to be zero. Ideally, tau should be set to zero. However, to improve the stability of the algorithm, tau is set to tau*100 % of the max fODF amplitude (here, 10% by default). This is similar to peak detection where peaks below 0.1 amplitude are usually considered noise peaks. Because SDT is based on a q-ball ODF deconvolution, and not signal deconvolution, using the max instead of mean (as in CSD), is more stable.

    convergence int

      Maximum number of iterations to allow the deconvolution to converge.

    P ndarray

      This is an optimization to avoid computing `dot(X.T, X)` many times. If the same `X` is used many times, `P` can be precomputed and passed to this function.

  Returns:
    fodf_sh ndarray (`(sh_order_max + 1)*(sh_order_max + 2)/2`,)

      Spherical harmonics coefficients of the constrained-regularized fiber ODF.

    _num_it int

      Number of iterations in the constrained-regularization used for convergence.

  Notes

  This section describes how the fitting of the SH coefficients is done. Problem is to minimise per iteration:

  \(F(f_n) = ||Xf_n - S||^2 + \lambda^2 ||H_{n-1} f_n||^2\)

  Where \(X\) maps current FOD SH coefficients \(f_n\) to DW signals \(s\) and \(H_{n-1}\) maps FOD SH coefficients \(f_n\) to amplitudes along set of negative directions identified in previous iteration, i.e. the matrix formed by the rows of \(B_{reg}\) for which \(Hf_{n-1}<0\) where \(B_{reg}\) maps \(f_n\) to FOD amplitude on a sphere.

  Solve by differentiating and setting to zero:

  \(\Rightarrow \frac{\delta F}{\delta f_n} = 2X^T(Xf_n - S) + 2 \lambda^2 H_{n-1}^TH_{n-1}f_n=0\)

  Or:

  \((X^TX + \lambda^2 H_{n-1}^TH_{n-1})f_n = X^Ts\)

  Define \(Q = X^TX + \lambda^2 H_{n-1}^TH_{n-1}\) , which by construction is a square positive definite symmetric matrix of size \(n_{SH} by n_{SH}\). If needed, positive definiteness can be enforced with a small minimum norm regulariser (helps a lot with poorly conditioned direction sets and/or superresolution):

  \(Q = X^TX + (\lambda H_{n-1}^T) (\lambda H_{n-1}) + \mu I\)

  Solve \(Qf_n = X^Ts\) using Cholesky decomposition:

  \(Q = LL^T\)

  where \(L\) is lower triangular. Then problem can be solved by back-substitution:

  \(L_y = X^Ts\)

  \(L^Tf_n = y\)

  To speeds things up further, form \(P = X^TX + \mu I\), and update to form \(Q\) by rankn update with \(H_{n-1}\). The dipy implementation looks like:

  > form initially \(P = X^T X + \mu I\) and \(\lambda B_{reg}\)

  > for each voxel: form \(z = X^Ts\)

  > > estimate \(f_0\) by solving \(Pf_0=z\). We use a simplified \(l_{max}=4\) solution here, but it might not make a big difference.

  > > Then iterate until no change in rows of \(H\) used in \(H_n\)

  > > > form \(H_{n}\) given \(f_{n-1}\)

  > > > form \(Q = P + (\lambda H_{n-1}^T) (\lambda H_{n-1}\)) (this can be done by rankn update, but we currently do not use rankn update).

  > > > solve \(Qf_n = z\) using Cholesky decomposition

  We would like to thank Donald Tournier for his help with describing and implementing this algorithm.

  References

  [13] (1,2,3,4,5,6,7,8,9,10,11,12,13,14)

  Jacques-Donald Tournier, Fernando Calamante, and Alan Connelly. Robust determination of the fibre orientation distribution in diffusion MRI: Non-negativity constrained super-resolved spherical deconvolution. NeuroImage, 35(4):1459–1472, May 2007. URL: https://doi.org/10.1016/j.neuroimage.2012.06.005, doi:10.1016/j.neuroimage.2007.02.016.

### odf_deconv

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

  ODF constrained-regularized spherical deconvolution using the Sharpening Deconvolution Transform (SDT).

  See [14] and [15] for further details about the method.

  Parameters:
    odf_sh ndarray (`(sh_order_max + 1)*(sh_order_max + 2)/2`,)

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

    R ndarray (`(sh_order_max + 1)(sh_order_max + 2)/2`,

      `(sh_order_max + 1)(sh_order_max + 2)/2`) SDT matrix in SH basis

    B_reg ndarray (`(sh_order_max + 1)(sh_order_max + 2)/2`,

      `(sh_order_max + 1)(sh_order_max + 2)/2`) SH basis matrix used for deconvolution

    lambda_float, optional

      lambda parameter in minimization equation

    tau float, optional

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

    r2_term bool, optional

      True if ODF is computed from model that uses the \(r^2\) term in the integral. Recall that Tuch’s ODF (used in Q-ball Imaging [14]) and the true normalized ODF definition differ from a \(r^2\) term in the ODF integral. The original Sharpening Deconvolution Transform (SDT) technique [15] is expecting Tuch’s ODF without the \(r^2\) (see [12] for the mathematical details). Now, this function supports ODF that have been computed using the \(r^2\) term because the proper analytical response function has be derived. For example, models such as DSI, GQI, SHORE, CSA, Tensor, Multi-tensor ODFs, should now be deconvolved with the r2_term=True.

  Returns:
    fodf_sh ndarray (`(sh_order_max + 1)(sh_order_max + 2)/2`,)

      Spherical harmonics coefficients of the constrained-regularized fiber ODF

    num_it int

      Number of iterations in the constrained-regularization used for convergence

  References

  [14] (1,2,3)

  David S. Tuch. Q-ball imaging. Magnetic Resonance in Medicine, 52(6):1358–1372, 2004. URL: https://doi.org/10.1002/mrm.20279, doi:10.1002/mrm.20279.

  [15] (1,2,3,4)

  Maxime Descoteaux, Rachid Deriche, Thomas R. Knösche, and Alfred Anwander. Deterministic and Probabilistic Tractography Based on Complex Fibre Orientation Distributions. IEEE Transactions on Medical Imaging, 28(2):269–286, February 2009. URL: https://doi.org/10.1109/TMI.2008.2004424, doi:10.1109/TMI.2008.2004424.

### odf_sh_to_sharp

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

  Sharpen odfs using the sharpening deconvolution transform.

  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.

  See [15] for further details about the method.

  Parameters:
    odfs_sh ndarray (`(sh_order_max + 1)*(sh_order_max + 2)/2`, )

      array of odfs expressed as spherical harmonics coefficients

    sphere Sphere

      sphere used to build the regularization matrix

    basis{None, ‘tournier07’, ‘descoteaux07’}, optional

      different spherical harmonic basis: `None` for the default DIPY basis, `tournier07` for the Tournier 2007 [13] basis, and `descoteaux07` for the Descoteaux 2007 [7] basis (`None` defaults to `descoteaux07`).

    ratio float, optional

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

    sh_order_max int, optional

      maximal SH order (\(l\)) of the SH representation

    lambda_float, optional

      lambda parameter (see odfdeconv)

    tau float, optional

      tau parameter in the L matrix construction (see odfdeconv)

    r2_term bool, optional

      True if ODF is computed from model that uses the \(r^2\) term in the integral. Recall that Tuch’s ODF (used in Q-ball Imaging [14]) and the true normalized ODF definition differ from a \(r^2\) term in the ODF integral. The original Sharpening Deconvolution Transform (SDT) technique [15] is expecting Tuch’s ODF without the \(r^2\) (see [7] for the mathematical details). Now, this function supports ODF that have been computed using the \(r^2\) term because the proper analytical response function has be derived. For example, models such as DSI, GQI, SHORE, CSA, Tensor, Multi-tensor ODFs, should now be deconvolved with the r2_term=True.

  Returns:
    fodf_sh ndarray

      sharpened odf expressed as spherical harmonics coefficients

  References

### mask_for_response_ssst

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

    function using FA.

  Parameters:
    gtab GradientTable

      Gradient table.

    data ndarray

      diffusion data (4D)

    roi_center array-like, (3,)

      Center of ROI in data. If center is None, it is assumed that it is the center of the volume with shape data.shape[:3].

    roi_radii int or array-like, (3,)

      radii of cuboid ROI

    fa_thr float

      FA threshold

  Returns:
    mask ndarray

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

  Notes

  In CSD there is an important pre-processing step: the estimation of the fiber response function. In order to do this, we look for voxels with very anisotropic configurations. This function aims to accomplish that by returning a mask of voxels within a ROI, that have a FA value above a given threshold. For example we can use a ROI (20x20x20) at the center of the volume and store the signal values for the voxels with FA values higher than 0.7 (see [16]).

  References

  [16] (1,2,3)

  Jacques-Donald Tournier, Fernando Calamante, David G. Gadian, and Alan Connelly. Direct estimation of the fiber orientation density function from diffusion-weighted MRI data using spherical deconvolution. NeuroImage, 23(3):1176–1185, November 2004. URL: https://doi.org/10.1016/j.neuroimage.2004.07.037, doi:10.1016/j.neuroimage.2004.07.037.

### response_from_mask_ssst

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

    function from a given mask.

  Parameters:
    gtab GradientTable

      Gradient table.

    data ndarray

      diffusion data

    mask ndarray

      mask from where to compute the response function

  Returns:
    response tuple, (2,)

      (evals, S0)

    ratio float

      The ratio between smallest versus largest eigenvalue of the response.

  Notes

  In CSD there is an important pre-processing step: the estimation of the fiber response function. In order to do this, we look for voxels with very anisotropic configurations. This information can be obtained by using csdeconv.mask_for_response_ssst() through a mask of selected voxels (see [16]). The present function uses such a mask to compute the ssst response function.

  For the response we also need to find the average S0 in the ROI. This is possible using gtab.b0s_mask() we can find all the S0 volumes (which correspond to b-values equal 0) in the dataset.

  The response consists always of a prolate tensor created by averaging the highest and second highest eigenvalues in the ROI with FA higher than threshold. We also include the average S0s.

  We also return the ratio which is used for the SDT models.

  References

### auto_response_ssst

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

    function using FA.

  Parameters:
    gtab GradientTable

      Gradient table.

    data ndarray

      diffusion data

    roi_center array-like, (3,)

      Center of ROI in data. If center is None, it is assumed that it is the center of the volume with shape data.shape[:3].

    roi_radii int or array-like, (3,)

      radii of cuboid ROI

    fa_thr float

      FA threshold

  Returns:
    response tuple, (2,)

      (evals, S0)

    ratio float

      The ratio between smallest versus largest eigenvalue of the response.

  Notes

  In CSD there is an important pre-processing step: the estimation of the fiber response function. In order to do this, we look for voxels with very anisotropic configurations. We get this information from csdeconv.mask_for_response_ssst(), which returns a mask of selected voxels (more details are available in the description of the function).

  With the mask, we compute the response function by using csdeconv.response_from_mask_ssst(), which returns the response and the ratio (more details are available in the description of the function).

### recursive_response

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

  Recursive calibration of response function using peak threshold.

  See [17] for further details about the method.

  Parameters:
    gtab GradientTable

      Gradient table.

    data ndarray

      diffusion data

    mask ndarray, optional

      mask for recursive calibration, for example a white matter mask. It has shape data.shape[0:3] and dtype=bool. Default: use the entire data array.

    sh_order_max int, optional

      maximal spherical harmonics order (l).

    peak_thr float, optional

      peak threshold, how large the second peak can be relative to the first peak in order to call it a single fiber population [17].

    init_fa float, optional

      FA of the initial ‘fat’ response function (tensor).

    init_trace float, optional

      trace of the initial ‘fat’ response function (tensor).

    iter int, optional

      maximum number of iterations for calibration.

    convergence float, optional

      convergence criterion, maximum relative change of SH coefficients.

    parallel bool, optional

      Whether to use parallelization in peak-finding during the calibration procedure.

    num_processes int, optional

      If parallel is True, the number of subprocesses to use (default multiprocessing.cpu_count()). If < 0 the maximal number of cores minus `num_processes + 1` is used (enter -1 to use as many cores as possible). 0 raises an error.

    sphere Sphere, optional.

      The sphere used for peak finding.

  Returns:
    response ndarray

      response function in SH coefficients

  Notes

  In CSD there is an important pre-processing step: the estimation of the fiber response function. Using an FA threshold is not a very robust method. It is dependent on the dataset (non-informed used subjectivity), and still depends on the diffusion tensor (FA and first eigenvector), which has low accuracy at high b-value. This function recursively calibrates the response function, for more information see [17].

  References

  [17] (1,2,3)

  Chantal M.W. Tax, Ben Jeurissen, Sjoerd B. Vos, Max A. Viergever, and Alexander Leemans. Recursive calibration of the fiber response function for spherical deconvolution of diffusion MRI data. NeuroImage, 86:67–80, 2014. URL: https://doi.org/10.1016/j.neuroimage.2013.07.067, doi:10.1016/j.neuroimage.2013.07.067.

### fa_trace_to_lambdas

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

### `CorrelationTensorModel`

class dipy.reconst.cti.CorrelationTensorModel(gtab1, gtab2, *args, fit_method='WLS', **kwargs)

  Bases: `ReconstModel`

  Class for the Correlation Tensor Model

  Methods

  `fit`(data, *[, mask]) | Fit method for every voxel in data
  `predict`(cti_params, *[, S0]) | Predict a signal for the CTI model class instance given parameters

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

    Fit method for every voxel in data

  predict(cti_params, *, S0=1)

    Predict a signal for the CTI model class instance given parameters

    Parameters:
      cti_params: numpy.ndarray (…, 48)

        All parameters estimated from the correlation tensor model. Parameters are ordered as follows:

        > 1. Three diffusion tensor’s eigenvalues

        > 2. Three lines of the eigenvector matrix each containing the first, second and third coordinates of the eigenvector

        > 3. Fifteen elements of the kurtosis tensor

        > 4. Twenty-One elements of the covariance tensor

      gtab1: dipy.core.gradients.GradientTable

        A GradientTable class instance for first DDE diffusion epoch

      gtab2: dipy.core.gradients.GradientTable

        A GradientTable class instance for second DDE diffusion epoch

      S0 float or ndarray, optional

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

    Returns:
      S numpy.ndarray

        Predicted signal based on the CTI model

### `CorrelationTensorFit`

class dipy.reconst.cti.CorrelationTensorFit(model, model_params)

  Bases: `DiffusionKurtosisFit`

  Class for fitting the Correlation Tensor Model

  Attributes:
    `K_aniso`

      Returns the anisotropic Source of Kurtosis ($K_{aniso}$)

    `K_iso`

      Returns the isotropic Source of Kurtosis ($K_{iso}$)

    `K_micro`

      Returns Microscopic Source of Kurtosis.

    S0_hat
    `ct`

      Returns the 21 independent elements of the covariance tensor as an

    `directions`

      For tracking - return the primary direction in each voxel

    `evals`

      Returns the eigenvalues of the tensor as an array

    `evecs`

      Returns the eigenvectors of the tensor as an array, columnwise

    `kfa`

      Return the kurtosis tensor (KFA).

    `kt`

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

    `quadratic_form`

      Calculates the 3x3 diffusion tensor for each voxel

    shape

  Methods

  `K_total`() | Returns the total excess kurtosis.
  `ad`() | Axial diffusivity (AD) calculated from cached eigenvalues.
  `adc`(sphere) | Calculate the apparent diffusion coefficient (ADC) in each direction on the sphere for each voxel in the data
  `ak`(*[, min_kurtosis, max_kurtosis, ...]) | Compute axial kurtosis (AK) of a diffusion kurtosis tensor.
  `akc`(sphere) | Calculate 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]) | Compute the maximum value of a single voxel kurtosis tensor
  `linearity`() |
  `md`() | Mean diffusivity (MD) calculated from cached eigenvalues.
  `mk`(*[, min_kurtosis, max_kurtosis, ...]) | Compute mean kurtosis (MK) from the kurtosis tensor.
  `mkt`(*[, min_kurtosis, max_kurtosis]) | Compute mean of the kurtosis tensor (MKT).
  `mode`() | Tensor mode calculated from cached eigenvalues.
  `odf`(sphere) | The diffusion orientation distribution function (dODF).
  `planarity`() |
  `predict`(gtab1, gtab2, *[, S0]) | Given a CTI 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, ...]) | Compute radial kurtosis (RK) of a diffusion kurtosis tensor.
  `rtk`(*[, min_kurtosis, max_kurtosis]) | Compute the rescaled radial tensor kurtosis (RTK).
  `sphericity`() |
  `trace`() | Trace of the tensor calculated from cached eigenvalues.

  lower_triangular |

  property K_aniso

    Returns the anisotropic Source of Kurtosis (\(K_{aniso}\))

    Notes

    The \(K_{aniso}\) is defined as [18]:

    \[\[K_{aniso} = \frac{6}{5} \cdot \frac{\langle V_{\lambda}(D_c) \rangle}{\overline{D}^2}\]\]

    where \(K_{aniso}\) is the anisotropic kurtosis, \(\langle V_{\lambda}(D_c) \rangle\) represents the mean of the variance of eigenvalues of the diffusion tensor, \(\overline{D}\) is the mean of the diffusion tensor.

    References

    [18]

    Rafael Neto Henriques, Sune N. Jespersen, and Noam Shemesh. Correlation tensor magnetic resonance imaging. NeuroImage, 211:116605, 2020. URL: https://doi.org/10.1016/j.neuroimage.2020.116605, doi:10.1016/j.neuroimage.2020.116605.

  property K_iso

    Returns the isotropic Source of Kurtosis (\(K_{iso}\))

    Notes

    The \(K_{iso}\) is defined as :

    \[K_{\text{iso}} = 3 \cdot \frac{V(\overline{D}^c)}{\overline{D}^2}\]

    where: \(K_{\text{iso}}\) is the isotropic kurtosis, \(V({\overline{D}^c})\) represents the variance of the diffusion tensor raised to the power \(c\), \(\overline{D}\) is the mean of the diffusion tensor.

  property K_micro

    Returns Microscopic Source of Kurtosis.

  K_total()

    Returns the total excess kurtosis.

    Notes

    \(K_{total}\) is defined as:

    \[\[\Psi = \frac{2}{5} \cdot \frac{D_{11}^2 + D_{22}^2 + D_{33}^2 + 2D_{12}^2 + 2D_{13}^2 + 2D_{23}^2{\overline{D}^2} - \frac{6}{5} \] \[{\overline{W}} = \frac{1}{5} \cdot (W_{1111} + W_{2222} + W_{3333} + 2W_{1122} + 2W_{1133} + 2W_{2233})\ ]\]

    where \(\Psi\) is a variable representing a part of the total excess kurtosis, \(D_{ij}\) are elements of the diffusion tensor, \(\overline{D}\) is the mean of the diffusion tensor. \(\overline{W}\) is the mean kurtosis, \(W_{ijkl}\) are elements of the kurtosis tensor.

  property ct

    Returns the 21 independent elements of the covariance tensor as an array

  predict(gtab1, gtab2, *, S0=1)

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

    Parameters:
      gtab1: dipy.core.gradients.GradientTable

        A GradientTable class instance for first DDE diffusion epoch

      gtab2: dipy.core.gradients.GradientTable

        A GradientTable class instance for second DDE diffusion epoch

      S0 float or ndarray, optional

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

    Returns:
      S numpy.ndarray

        Predicted signal based on the CTI model

### from_qte_to_cti

dipy.reconst.cti.from_qte_to_cti(C)

  Rescales the qte C elements to the C elements used in CTI.

  Parameters:
    C: array(…, 21)

      Twenty-one elements of the covariance tensor in voigt notation plus some extra scaling factors.

  Returns:
    ccti: array(…, 21)

      Covariance Tensor Elements with no hidden factors.

### multi_gaussian_k_from_c

dipy.reconst.cti.multi_gaussian_k_from_c(ccti, MD)

  Computes the multiple Gaussian diffusion kurtosis tensor from the covariance tensor.

  Parameters:
    ccti: array(…, 21)

      Covariance Tensor Elements with no hidden factors.

    MD ndarray

      Mean Diffusivity (MD) of a diffusion tensor.

  Returns:
    K: array (…, 15)

      Fifteen elements of the kurtosis tensor

### split_cti_params

dipy.reconst.cti.split_cti_params(cti_params)

  Splits CTI params into DTI, DKI, CTI portions.

  Extract the diffusion tensor eigenvalues, the diffusion tensor eigenvector matrix, and the 21 independent elements of the covariance tensor, and the 15 independent elements of the kurtosis tensor from the model parameters estimated from the CTI model

  Parameters:
    cti_params: numpy.ndarray (…, 48)

      All parameters estimated from the correlation tensor model. Parameters are ordered as follows:

      > 1. Three diffusion tensor’s eigenvalues

      > 2. Three lines of the eigenvector matrix each containing the first, second and third coordinates of the eigenvector

      > 3. Fifteen elements of the kurtosis tensor

      > 4. Twenty-One elements of the covariance tensor

  Returns:
    evals array (…, 3)

      Eigenvalues from eigen decomposition of the tensor.

    evecs array (…, 3)

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

    kt array (…, 15)

      Fifteen elements of the kurtosis tensor

    ct: array(…, 21)

      Twenty-one elements of the covariance tensor

### cti_prediction

dipy.reconst.cti.cti_prediction(cti_params, gtab1, gtab2, *, S0=1)

  Predict a signal given correlation tensor imaging parameters.

  Parameters:
    cti_params: numpy.ndarray (…, 48)

      All parameters estimated from the correlation tensor model. Parameters are ordered as follows:

      > 1. Three diffusion tensor’s eigenvalues

      > 2. Three lines of the eigenvector matrix each containing the first, second and third coordinates of the eigenvector

      > 3. Fifteen elements of the kurtosis tensor

      > 4. Twenty-One elements of the covariance tensor

    gtab1: dipy.core.gradients.GradientTable

      A GradientTable class instance for first DDE diffusion epoch

    gtab2: dipy.core.gradients.GradientTable

      A GradientTable class instance for second DDE diffusion epoch

    S0 float or ndarray, optional

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

  Returns:
    S ndarray

      Simulated signal based on the CTI model

### params_to_cti_params

dipy.reconst.cti.params_to_cti_params(result, *, min_diffusivity=0)

### ls_fit_cti

dipy.reconst.cti.ls_fit_cti(design_matrix, data, inverse_design_matrix, *, weights=True, min_diffusivity=0)

  Compute the diffusion kurtosis and covariance tensors using an ordinary or weighted linear least squares approach

  Parameters:
    design_matrix array (g, 43)

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

    data array (g)

      Data or response variables holding the data.

    inverse_design_matrix array (43, g)

      Inverse of the design matrix.

    weights bool, optional

      Parameter indicating whether weights are used.

    min_diffusivity float, optional

      Because negative eigenvalues are not physical and small eigenvalues, much smaller than the diffusion weighting, cause quite a lot of noise in metrics such as fa, diffusivity values smaller than min_diffusivity are replaced with min_diffusivity.

  Returns:
    cti_params array (48)

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

      > 1. Three diffusion tensor eigenvalues.

      > 2. Three blocks of three elements, containing the first second and

      >      third coordinates of the diffusion tensor eigenvectors.

      > 3. Fifteen elements of the kurtosis tensor.

      > 4. Twenty One elements of the covariance tensor.

### `DiffusionKurtosisModel`

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

  Bases: `ReconstModel`

  Class for the Diffusion Kurtosis Model

  Methods

  `fit`(data, *[, mask]) | Fit method of the DKI model.
  `iterative_fit`(data_thres, *[, mask, ...]) | Iteratively Reweighted fitting for the DKI model.
  `multi_fit`(data, *[, mask]) | Fit method for every voxel in data
  `predict`(dki_params, *[, S0]) | Predict a signal for this DKI model class instance given parameters

  fit(data, *, mask=None)

    Fit method of the DKI model.

    Parameters:
      data array

        The measured signal.

      mask array

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

  iterative_fit(data_thres, *, mask=None, num_iter=4, weights_method=<function weights_method_wls_m_est>)

    Iteratively Reweighted fitting for the DKI model.

    Parameters:
      data_thres array

        The measured signal.

      mask array, optional

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

      num_iter int, optional

        Number of times to iterate.

      weights_method callable, optional

        A function with args and returns as follows:

        (weights, robust) =
          weights_method(data, pred_sig,

            design_matrix, leverages, idx, num_iter, robust)

    Notes

    On the first iteration, (C)WLS fit is performed. Subsequent iterations will be weighted according to weights_method. Outlier rejection should be handled within weights_method by setting the corresponding weights to zero (if weights_method implements outlier rejection).

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

    Fit method for every voxel in data

  predict(dki_params, *, S0=1.0)

    Predict a signal for this DKI model class instance given parameters

    See [19] and [20] for further details about the method.

    Parameters:
      dki_params ndarray (x, y, z, 27) or (n, 27)

        All parameters estimated from the diffusion kurtosis model. Parameters are ordered as follows:

        > 1. Three diffusion tensor’s eigenvalues

        > 2. Three lines of the eigenvector matrix each containing the first, second and third coordinates of the eigenvector

        > 3. Fifteen elements of the kurtosis tensor

      S0 float or ndarray, optional

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

    References

    [19] (1,2,3,4,5,6,7,8,9,10,11,12,13,14)

    Jens H. Jensen, Joseph A. Helpern, Anita Ramani, Hanzhang Lu, and Kyle Kaczynski. Diffusional kurtosis imaging: The quantification of non-gaussian water diffusion by means of magnetic resonance imaging. Magnetic Resonance in Medicine, 53(6):1432–1440, 2005. URL: https://onlinelibrary.wiley.com/doi/abs/10.1002/mrm.20508, doi:https://doi.org/10.1002/mrm.20508.

    [20] (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24)

    Rafael Neto Henriques, Marta M. Correia, Maurizio Marrale, Elizabeth Huber, John Kruper, Serge Koudoro, Jason D. Yeatman, Eleftherios Garyfallidis, and Ariel Rokem. Diffusional Kurtosis Imaging in the Diffusion Imaging in Python Project. Frontiers in Human Neuroscience, July 2021. Sec. Brain Imaging and Stimulation. Advanced Diffusion MRI for Brain Microstructure: Methodology, Consistency, and Application. URL: https://doi.org/10.3389/fnhum.2021.675433, doi:10.3389/fnhum.2021.675433.

### `DiffusionKurtosisFit`

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

  Bases: `TensorFit`

  Class for fitting the Diffusion Kurtosis Model

  Attributes:
    S0_hat
    `directions`

      For tracking - return the primary direction in each voxel

    `evals`

      Returns the eigenvalues of the tensor as an array

    `evecs`

      Returns the eigenvectors of the tensor as an array, columnwise

    `kfa`

      Return the kurtosis tensor (KFA).

    `kt`

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

    `quadratic_form`

      Calculates the 3x3 diffusion tensor for each voxel

    shape

  Methods

  `ad`() | Axial diffusivity (AD) calculated from cached eigenvalues.
  `adc`(sphere) | Calculate the apparent diffusion coefficient (ADC) in each direction on the sphere for each voxel in the data
  `ak`(*[, min_kurtosis, max_kurtosis, ...]) | Compute axial kurtosis (AK) of a diffusion kurtosis tensor.
  `akc`(sphere) | Calculate 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]) | Compute the maximum value of a single voxel kurtosis tensor
  `linearity`() |
  `md`() | Mean diffusivity (MD) calculated from cached eigenvalues.
  `mk`(*[, min_kurtosis, max_kurtosis, ...]) | Compute mean kurtosis (MK) from the kurtosis tensor.
  `mkt`(*[, min_kurtosis, max_kurtosis]) | Compute mean of the kurtosis tensor (MKT).
  `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, ...]) | Compute radial kurtosis (RK) of a diffusion kurtosis tensor.
  `rtk`(*[, min_kurtosis, max_kurtosis]) | Compute the rescaled radial tensor kurtosis (RTK).
  `sphericity`() |
  `trace`() | Trace of the tensor calculated from cached eigenvalues.

  lower_triangular |

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

    Compute axial kurtosis (AK) of a diffusion kurtosis tensor.

    See [21] and [20] for further details about the method.

    Parameters:
      min_kurtosis float, optional

        To keep kurtosis values within a plausible biophysical range, axial kurtosis values that are smaller than min_kurtosis are replaced with -3./7 (theoretical kurtosis limit for regions that consist of water confined to spherical pores [19]).

      max_kurtosis float, optional

        To keep kurtosis values within a plausible biophysical range, axial kurtosis values that are larger than max_kurtosis are replaced with max_kurtosis.

      analytical bool, optional

        If True, AK is calculated from rotated diffusion kurtosis tensor, otherwise it will be computed from the apparent diffusion kurtosis values along the principal axis of the diffusion tensor (see notes).

      fast bool, optional

        If True and analytical is True, use the Cython-optimized analytical solution.

    Returns:
      ak array

        Calculated AK.

    Notes

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

    1. AK is calculated from rotated diffusion kurtosis tensor, i.e.:

    \[AK = \hat{W}_{1111} \frac{(\lambda_{1}+\lambda_{2}+\lambda_{3})^2}{(9 \lambda_{1}^2)}\]

    2. AK can be sampled from the principal axis of the diffusion tensor:

    \[AK = K(\mathbf{e}_1)\]

    Although both approaches leads to an exact calculation of AK, the first approach will be referred to as the analytical method while the second approach will be referred to as the numerical method based on their analogy to the estimation strategies for MK and RK.

    References

    [21] (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17)

    Ali Tabesh, Jens H. Jensen, Babak A. Ardekani, and Joseph A. Helpern. Estimation of tensors and tensor-derived measures in diffusional kurtosis imaging. Magnetic Resonance in Medicine, 65(3):823–836, 2011. URL: https://doi.org/10.1002/mrm.22655, doi:10.1002/mrm.22655.

  akc(sphere)

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

    Parameters:
      sphere Sphere class instance

        Sphere providing sample directions to compute the apparent kurtosis coefficient.

    Returns:
      akc ndarray

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

    Notes

    For each sphere direction with coordinates \((n_{1}, n_{2}, n_{3})\), the calculation of AKC is done using formula:

    \[AKC(n)=\frac{MD^{2}}{ADC(n)^{2}}\sum_{i=1}^{3}\sum_{j=1}^{3} \sum_{k=1}^{3}\sum_{l=1}^{3}n_{i}n_{j}n_{k}n_{l}W_{ijkl}\]

    where \(W_{ijkl}\) are the elements of the kurtosis tensor, MD the mean diffusivity and ADC the apparent diffusion coefficient computed as:

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

    where \(D_{ij}\) are the elements of the diffusion tensor.

  property kfa

    Return the kurtosis tensor (KFA).

    See [22] for further details about the method.

    Notes

    The KFA is defined as [22]:

    \[KFA \equiv \frac{||\mathbf{W} - MKT \mathbf{I}^{(4)}||_F}{||\mathbf{W}||_F}\]

    where \(W\) is the kurtosis tensor, MKT the kurtosis tensor mean, \(I^{(4)}\) is the fully symmetric rank 2 isotropic tensor and \(||...||_F\) is the tensor’s Frobenius norm [22].

    References

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

    Compute the maximum value of a single voxel kurtosis tensor

    See [20] for further details about the method.

    Parameters:
      sphere Sphere class instance, optional

        The sphere providing sample directions for the initial search of the maximum value of kurtosis.

      gtol float, optional

        This input is to refine kurtosis maximum under the precision of the directions sampled on the sphere class instance. The gradient of the convergence procedure must be less than gtol before successful termination. If gtol is None, fiber direction is directly taken from the initial sampled directions of the given sphere object

    Returns:
      max_value float

        kurtosis tensor maximum value

    References

    [22] (1,2,3,4,5,6)

    G. Russell Glenn, Joseph A. Helpern, Ali Tabesh, and Jens H. Jensen. Quantitative assessment of diffusional kurtosis anisotropy. NMR in Biomedicine, 28(4):448–459, 2015. URL: https://doi.org/10.1002/nbm.3271, doi:10.1002/nbm.3271.

  property kt

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

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

    Compute mean kurtosis (MK) from the kurtosis tensor.

    See Tabesh et al.[21] and [20] for further details about the method.

    Parameters:
      min_kurtosis float, optional

        To keep kurtosis values within a plausible biophysical range, mean kurtosis values that are smaller than min_kurtosis are replaced with min_kurtosis. Default = -3./7 (theoretical kurtosis limit for regions that consist of water confined to spherical pores [19]).

      max_kurtosis float, optional

        To keep kurtosis values within a plausible biophysical range, mean kurtosis values that are larger than max_kurtosis are replaced with max_kurtosis.

      analytical bool, optional

        If True, MK is calculated using its analytical solution, otherwise an exact numerical estimator is used (see Notes).

      fast bool, optional

        If True and analytical is True, use the Cython-optimized analytical solution.

    Returns:
      mk array

        Calculated MK.

    Notes

    The MK is defined as the average of directional kurtosis coefficients across all spatial directions, which can be formulated by the following surface integral [21], [20]:

    \[MK \equiv \frac{1}{4\pi} \int d\Omega_\mathbf{n} K(\mathbf{n})\]

    This integral can be numerically solved by averaging directional kurtosis values sampled for directions of a spherical t-design [23].

    Alternatively, MK can be solved from the analytical solution derived by Tabesh et al.[21]. This solution is given by:

    \[\begin{split}MK=F_1(\lambda_1,\lambda_2,\lambda_3)\hat{W}_{1111}+ F_1(\lambda_2,\lambda_1,\lambda_3)\hat{W}_{2222}+ F_1(\lambda_3,\lambda_2,\lambda_1)\hat{W}_{3333}+ \\ F_2(\lambda_1,\lambda_2,\lambda_3)\hat{W}_{2233}+ F_2(\lambda_2,\lambda_1,\lambda_3)\hat{W}_{1133}+ F_2(\lambda_3,\lambda_2,\lambda_1)\hat{W}_{1122}\end{split}\]

    where \(\hat{W}_{ijkl}\) are the components of the \(W\) tensor in the coordinates system defined by the eigenvectors of the diffusion tensor \(\mathbf{D}\) and

    \[ \begin{align}\begin{aligned}\begin{split}F_1(\lambda_1,\lambda_2,\lambda_3)= \frac{(\lambda_1+\lambda_2+\lambda_3)^2} {18(\lambda_1-\lambda_2)(\lambda_1-\lambda_3)} [\frac{\sqrt{\lambda_2\lambda_3}}{\lambda_1} R_F(\frac{\lambda_1}{\lambda_2},\frac{\lambda_1}{\lambda_3},1)+\\ \frac{3\lambda_1^2-\lambda_1\lambda_2-\lambda_2\lambda_3- \lambda_1\lambda_3} {3\lambda_1 \sqrt{\lambda_2 \lambda_3}} R_D(\frac{\lambda_1}{\lambda_2},\frac{\lambda_1}{\lambda_3},1)-1 ]\end{split}\\\begin{split}F_2(\lambda_1,\lambda_2,\lambda_3)= \frac{(\lambda_1+\lambda_2+\lambda_3)^2} {3(\lambda_2-\lambda_3)^2} [\frac{\lambda_2+\lambda_3}{\sqrt{\lambda_2\lambda_3}} R_F(\frac{\lambda_1}{\lambda_2},\frac{\lambda_1}{\lambda_3},1)+\\ \frac{2\lambda_1-\lambda_2-\lambda_3}{3\sqrt{\lambda_2 \lambda_3}} R_D(\frac{\lambda_1}{\lambda_2},\frac{\lambda_1}{\lambda_3},1)-2]\end{split}\end{aligned}\end{align} \]

    where \(R_f\) and \(R_d\) are the Carlson’s elliptic integrals.

    References

    [23] (1,2)

    Ronald H. Hardin and Neil J. A. Sloane. Mclaren’s improved snub cube and other new spherical designs in three dimensions. Discrete & Computational Geometry, 15(4):429–441, 1996. URL: https://doi.org/10.1007/BF02711518, doi:10.1007/BF02711518.

  mkt(*, min_kurtosis=-0.42857142857142855, max_kurtosis=10)

    Compute mean of the kurtosis tensor (MKT).

    See [24] for further details about the method.

    Parameters:
      min_kurtosis float, optional

        To keep kurtosis values within a plausible biophysical range, mean kurtosis values that are smaller than min_kurtosis are replaced with min_kurtosis. Default = -3./7 (theoretical kurtosis limit for regions that consist of water confined to spherical pores [19]).

      max_kurtosis float, optional

        To keep kurtosis values within a plausible biophysical range, mean kurtosis values that are larger than max_kurtosis are replaced with max_kurtosis.

    Returns:
      mkt array

        Calculated mean kurtosis tensor.

    Notes

    The MKT is defined as [24]:

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

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

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

    References

    [24] (1,2,3,4,5,6)

    Brian Hansen, Torben E. Lund, Ryan Sangill, and Sune Nørhøj Jespersen. Experimentally and computationally fast method for estimation of a mean kurtosis. Magnetic Resonance in Medicine, 69(6):1754–1760, 2013. URL: https://doi.org/10.1002/mrm.24743, doi:10.1002/mrm.24743.

  predict(gtab, *, S0=1.0)

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

    See [19] and [20] for further details about the method.

    Parameters:
      gtab a GradientTable class instance

        The gradient table for this prediction

      S0 float or ndarray, optional

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

    Notes

    The predicted signal is given by:

    \[S(n,b)=S_{0}e^{-bD(n)+\frac{1}{6}b^{2}D(n)^{2}K(n)}\]

    \(\mathbf{D(n)}\) and \(\mathbf{K(n)}\) can be computed from the DT and KT using the following equations:

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

    and

    \[K(n)=\frac{MD^{2}}{D(n)^{2}}\sum_{i=1}^{3}\sum_{j=1}^{3} \sum_{k=1}^{3}\sum_{l=1}^{3}n_{i}n_{j}n_{k}n_{l}W_{ijkl}\]

    where \(D_{ij}\) and \(W_{ijkl}\) are the elements of the second-order DT and the fourth-order KT tensors, respectively, and \(MD\) is the mean diffusivity.

    References

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

    Compute radial kurtosis (RK) of a diffusion kurtosis tensor.

    See [21] for further details about the method.

    Parameters:
      min_kurtosis float, optional

        To keep kurtosis values within a plausible biophysical range, radial kurtosis values that are smaller than min_kurtosis are replaced with min_kurtosis. Default = -3./7 (theoretical kurtosis limit for regions that consist of water confined to spherical pores [19]).

      max_kurtosis float, optional

        To keep kurtosis values within a plausible biophysical range, radial kurtosis values that are larger than max_kurtosis are replaced with max_kurtosis.

      analytical bool, optional

        If True, RK is calculated using its analytical solution, otherwise an exact numerical estimator is used (see Notes).

      fast bool, optional

        If True and analytical is True, use the Cython-optimized analytical solution.

    Returns:
      rk array

        Calculated RK.

    Notes

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

    \[RK \equiv \frac{1}{2\pi} \int d\Omega _\mathbf{\theta} K(\mathbf{\theta}) \delta (\mathbf{\theta}\cdot \mathbf{e}_1)\]

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

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

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

    where:

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

    and

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

    References

  rtk(*, min_kurtosis=-0.42857142857142855, max_kurtosis=10)

    Compute the rescaled radial tensor kurtosis (RTK).

    See [25] for further details about the method.

    Parameters:
      min_kurtosis float, optional

        To keep kurtosis values within a plausible biophysical range, radial kurtosis values that are smaller than min_kurtosis are replaced with min_kurtosis.

      max_kurtosis float, optional

        To keep kurtosis values within a plausible biophysical range, radial kurtosis values that are larger than max_kurtosis are replaced with max_kurtosis.

    Returns:
      rtk array

        Calculated escaled radial tensor kurtosis (RTK).

    Notes

    Rescaled radial tensor kurtosis (RTK) is defined as [25]:

    \[\]

    RKT = frac{3}{8}frac{MD^2}{RD^2} (W_{2222}+ W_{3333}+2*W_{2233})

    where W is the kurtosis tensor rotated to a coordinate system in which the 3 orthonormal eigenvectors of DT are the base coordinate, MD is the mean diffusivity, and RD is the radial diffusivity.

    References

    [25] (1,2)

    Brian Hansen, Noam Shemesh, and Sune Nørhøj Jespersen. Fast imaging of mean, axial and radial diffusion kurtosis. NeuroImage, 142:381–393, November 2016. URL: https://doi.org/10.1016/j.neuroimage.2016.08.022, doi:10.1016/j.neuroimage.2016.08.022.

### carlson_rf

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

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

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

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

      First independent variable of the integral.

    y ndarray

      Second independent variable of the integral.

    z ndarray

      Third independent variable of the integral.

    errtol float

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

  Returns:
    RF ndarray

      Value of the incomplete first order elliptic integral

  Notes

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

  References

  [26] (1,2)

  Billie C. Carlson. Numerical computation of real or complex elliptic integrals. Numerical Algorithms, 10(1):13–26, 1995. URL: https://doi.org/10.1007/BF02198293, doi:10.1007/BF02198293.

### carlson_rd

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

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

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

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

      First independent variable of the integral.

    y ndarray

      Second independent variable of the integral.

    z ndarray

      Third independent variable of the integral.

    errtol float

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

  Returns:
    RD ndarray

      Value of the incomplete second order elliptic integral

  Notes

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

  References

### directional_diffusion

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

  Compute apparent diffusion coefficient (adc).

  Calculate the apparent diffusion coefficient (adc) in each direction of a sphere for a single voxel Neto Henriques et al.[27].

  Parameters:
    dt array (6,)

      elements of the diffusion tensor of the voxel.

    V array (g, 3)

      g directions of a Sphere in Cartesian coordinates

    min_diffusivity float, optional

      Because negative eigenvalues are not physical and small eigenvalues cause quite a lot of noise in diffusion-based metrics, diffusivity values smaller than min_diffusivity are replaced with min_diffusivity. Default = 0

  Returns:
    adc ndarray (g,)

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

  References

  [27] (1,2,3,4,5)

  Rafael Neto Henriques, Marta Morgado Correia, Rita Gouveia Nunes, and Hugo Alexandre Ferreira. Exploring the 3D geometry of the diffusion kurtosis tensor—Impact on the development of robust tractography procedures and novel biomarkers. NeuroImage, 111:85–99, 2015. URL: https://doi.org/10.1016/j.neuroimage.2015.02.004, doi:10.1016/j.neuroimage.2015.02.004.

### directional_diffusion_variance

dipy.reconst.dki.directional_diffusion_variance(kt, V)

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

  See [19], [27], and [20] for further details about the method.

  Parameters:
    kt array (15,)

      elements of the kurtosis tensor of the voxel.

    V array (g, 3)

      g directions of a Sphere in Cartesian coordinates.

  Returns:
    adv ndarray (g,)

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

  References

### directional_kurtosis

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

  Calculate the apparent kurtosis coefficient (akc) in each direction of a sphere for a single voxel.

  See [27] and [20] for further details about the method.

  Parameters:
    dt array (6,)

      elements of the diffusion tensor of the voxel.

    md float

      mean diffusivity of the voxel

    kt array (15,)

      elements of the kurtosis tensor of the voxel.

    V array (g, 3)

      g directions of a Sphere in Cartesian coordinates

    min_diffusivity float, optional

      Because negative eigenvalues are not physical and small eigenvalues cause quite a lot of noise in diffusion-based metrics, diffusivity values smaller than min_diffusivity are replaced with min_diffusivity. Default = 0

    min_kurtosis float, optional

      Because high-amplitude negative values of kurtosis are not physically and biologically plausible, and these cause artifacts in kurtosis-based measures, directional kurtosis values smaller than min_kurtosis are replaced with min_kurtosis. (theoretical kurtosis limit for regions that consist of water confined to spherical pores [19]).

    adc ndarray(g,), optional

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

    adv ndarray(g,), optional

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

  Returns:
    akc ndarray (g,)

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

  References

### apparent_kurtosis_coef

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

  Calculate the apparent kurtosis coefficient (AKC) in each direction of a sphere.

  See [27] and [20] for further details about the method.

  Parameters:
    dki_params ndarray (x, y, z, 27) or (n, 27)

      All parameters estimated from the diffusion kurtosis model. Parameters are ordered as follows:

      > 1. Three diffusion tensor’s eigenvalues

      > 2. Three lines of the eigenvector matrix each containing the first, second and third coordinates of the eigenvectors respectively

      > 3. Fifteen elements of the kurtosis tensor

    sphere a Sphere class instance

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

    min_diffusivity float, optional

      Because negative eigenvalues are not physical and small eigenvalues cause quite a lot of noise in diffusion-based metrics, diffusivity values smaller than min_diffusivity are replaced with min_diffusivity.

    min_kurtosis float, optional

      Because high-amplitude negative values of kurtosis are not physically and biologically plausible, and these cause artifacts in kurtosis-based measures, directional kurtosis values smaller than min_kurtosis are replaced with min_kurtosis. Default = -3./7 (theoretical kurtosis limit for regions that consist of water confined to spherical pores [19]).

  Returns:
    akc ndarray (x, y, z, g) or (n, g)

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

  Notes

  For each sphere direction with coordinates \((n_{1}, n_{2}, n_{3})\), the calculation of AKC is done using formula [27]:

  \[AKC(n)=\frac{MD^{2}}{ADC(n)^{2}}\sum_{i=1}^{3}\sum_{j=1}^{3} \sum_{k=1}^{3}\sum_{l=1}^{3}n_{i}n_{j}n_{k}n_{l}W_{ijkl}\]

  where \(W_{ijkl}\) are the elements of the kurtosis tensor, MD the mean diffusivity and ADC the apparent diffusion coefficient computed as:

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

  where \(D_{ij}\) are the elements of the diffusion tensor.

  References

### mean_kurtosis

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

  Compute mean kurtosis (MK) from the kurtosis tensor.

  See [21] and [20] for further details about the method.

  Parameters:
    dki_params ndarray (x, y, z, 27) or (n, 27)

      All parameters estimated from the diffusion kurtosis model. Parameters are ordered as follows:

      > 1. Three diffusion tensor’s eigenvalues

      > 2. Three lines of the eigenvector matrix each containing the first, second and third coordinates of the eigenvector

      > 3. Fifteen elements of the kurtosis tensor

    min_kurtosis float, optional

      To keep kurtosis values within a plausible biophysical range, mean kurtosis values that are smaller than min_kurtosis are replaced with min_kurtosis. Default = -3./7 (theoretical kurtosis limit for regions that consist of water confined to spherical pores [19]).

    max_kurtosis float, optional

      To keep kurtosis values within a plausible biophysical range, mean kurtosis values that are larger than max_kurtosis are replaced with max_kurtosis.

    analytical bool, optional

      If True, MK is calculated using its analytical solution, otherwise an exact numerical estimator is used (see Notes).

    fast bool, optional

      If True and analytical is True, use the Cython-optimized analytical solution. If False, use the pure Python analytical solution. Both produce identical results.

  Returns:
    mk array

      Calculated MK.

  Notes

  The MK is defined as the average of directional kurtosis coefficients across all spatial directions, which can be formulated by the following surface integral [21], [20]:

  \[MK \equiv \frac{1}{4\pi} \int d\Omega_\mathbf{n} K(\mathbf{n})\]

  This integral can be numerically solved by averaging directional kurtosis values sampled for directions of a spherical t-design [23].

  Alternatively, MK can be solved from the analytical solution derived by [21], [20]. This solution is given by:

  \[\begin{split}MK=F_1(\lambda_1,\lambda_2,\lambda_3)\hat{W}_{1111}+ F_1(\lambda_2,\lambda_1,\lambda_3)\hat{W}_{2222}+ F_1(\lambda_3,\lambda_2,\lambda_1)\hat{W}_{3333}+ \\ F_2(\lambda_1,\lambda_2,\lambda_3)\hat{W}_{2233}+ F_2(\lambda_2,\lambda_1,\lambda_3)\hat{W}_{1133}+ F_2(\lambda_3,\lambda_2,\lambda_1)\hat{W}_{1122}\end{split}\]

  where \(\hat{W}_{ijkl}\) are the components of the \(W\) tensor in the coordinates system defined by the eigenvectors of the diffusion tensor \(\mathbf{D}\) and

  \[ \begin{align}\begin{aligned}\begin{split}F_1(\lambda_1,\lambda_2,\lambda_3)= \frac{(\lambda_1+\lambda_2+\lambda_3)^2} {18(\lambda_1-\lambda_2)(\lambda_1-\lambda_3)} [\frac{\sqrt{\lambda_2\lambda_3}}{\lambda_1} R_F(\frac{\lambda_1}{\lambda_2},\frac{\lambda_1}{\lambda_3},1)+\\ \frac{3\lambda_1^2-\lambda_1\lambda_2-\lambda_2\lambda_3- \lambda_1\lambda_3} {3\lambda_1 \sqrt{\lambda_2 \lambda_3}} R_D(\frac{\lambda_1}{\lambda_2},\frac{\lambda_1}{\lambda_3},1)-1 ]\end{split}\\\begin{split}F_2(\lambda_1,\lambda_2,\lambda_3)= \frac{(\lambda_1+\lambda_2+\lambda_3)^2} {3(\lambda_2-\lambda_3)^2} [\frac{\lambda_2+\lambda_3}{\sqrt{\lambda_2\lambda_3}} R_F(\frac{\lambda_1}{\lambda_2},\frac{\lambda_1}{\lambda_3},1)+\\ \frac{2\lambda_1-\lambda_2-\lambda_3}{3\sqrt{\lambda_2 \lambda_3}} R_D(\frac{\lambda_1}{\lambda_2},\frac{\lambda_1}{\lambda_3},1)-2]\end{split}\end{aligned}\end{align} \]

  where \(R_f\) and \(R_d\) are the Carlson’s elliptic integrals.

  References

### radial_kurtosis

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

  Compute radial kurtosis (RK) of a diffusion kurtosis tensor.

  See [21] and [20] for further details about the method.

  Parameters:
    dki_params ndarray (x, y, z, 27) or (n, 27)

      All parameters estimated from the diffusion kurtosis model. Parameters are ordered as follows:

      > 1. Three diffusion tensor’s eigenvalues

      > 2. Three lines of the eigenvector matrix each containing the first, second and third coordinates of the eigenvector

      > 3. Fifteen elements of the kurtosis tensor

    min_kurtosis float, optional

      To keep kurtosis values within a plausible biophysical range, radial kurtosis values that are smaller than min_kurtosis are replaced with min_kurtosis. Default = -3./7 (theoretical kurtosis limit for regions that consist of water confined to spherical pores [19]).

    max_kurtosis float, optional

      To keep kurtosis values within a plausible biophysical range, radial kurtosis values that are larger than max_kurtosis are replaced with max_kurtosis.

    analytical bool, optional

      If True, RK is calculated using its analytical solution, otherwise an exact numerical estimator is used (see Notes). Default is set to True.

    fast bool, optional

      If True and analytical is True, use the Cython-optimized analytical solution. If False, use the pure Python analytical solution. Both produce identical results.

  Returns:
    rk array

      Calculated RK.

  Notes

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

  \[RK \equiv \frac{1}{2\pi} \int d\Omega _\mathbf{\theta} K(\mathbf{\theta}) \delta (\mathbf{\theta}\cdot \mathbf{e}_1)\]

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

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

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

  where:

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

  and

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

  References

### axial_kurtosis

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

  Compute axial kurtosis (AK) from the kurtosis tensor.

  See [21] and [20] for further details about the method.

  Parameters:
    dki_params ndarray (x, y, z, 27) or (n, 27)

      All parameters estimated from the diffusion kurtosis model. Parameters are ordered as follows:

      > 1. Three diffusion tensor’s eigenvalues

      > 2. Three lines of the eigenvector matrix each containing the first, second and third coordinates of the eigenvector

      > 3. Fifteen elements of the kurtosis tensor

    min_kurtosis float, optional

      To keep kurtosis values within a plausible biophysical range, axial kurtosis values that are smaller than min_kurtosis are replaced with min_kurtosis. Default = -3./7 (theoretical kurtosis limit for regions that consist of water confined to spherical pores [19]).

    max_kurtosis float, optional

      To keep kurtosis values within a plausible biophysical range, axial kurtosis values that are larger than max_kurtosis are replaced with max_kurtosis.

    analytical bool, optional

      If True, AK is calculated from rotated diffusion kurtosis tensor, otherwise it will be computed from the apparent diffusion kurtosis values along the principal axis of the diffusion tensor (see notes).

    fast bool, optional

      If True and analytical is True, use the Cython-optimized analytical solution. If False, use the pure Python analytical solution. Both produce identical results.

  Returns:
    ak array

      Calculated AK.

  Notes

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

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

  \[AK = \hat{W}_{1111} \frac{(\lambda_{1}+\lambda_{2}+\lambda_{3})^2}{(9 \lambda_{1}^2)}\]

  2. AK can be sampled from the principal axis of the diffusion tensor [20]:

  \[AK = K(\mathbf{e}_1)\]

  Although both approaches leads to an exact calculation of AK, the first approach will be referred to as the analytical method while the second approach will be referred to as the numerical method based on their analogy to the estimation strategies for MK and RK.

  References

### kurtosis_maximum

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

  Compute kurtosis maximum value.

  See [20] for further details about the method.

  Parameters:
    dki_params ndarray (x, y, z, 27) or (n, 27)

      All parameters estimated from the diffusion kurtosis model. Parameters are ordered as follows:

      > 1. Three diffusion tensor’s eingenvalues

      > 2. Three lines of the eigenvector matrix each containing the first, second and third coordinates of the eigenvector

      > 3. Fifteen elements of the kurtosis tensor

    sphere Sphere class instance, optional

      The sphere providing sample directions for the initial search of the maximal value of kurtosis.

    gtol float, optional

      This input is to refine kurtosis maximum under the precision of the directions sampled on the sphere class instance. The gradient of the convergence procedure must be less than gtol before successful termination. If gtol is None, fiber direction is directly taken from the initial sampled directions of the given sphere object

    mask ndarray

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

  Returns:
    max_value float

      kurtosis tensor maximum value

    max_dir array (3,)

      Cartesian coordinates of the direction of the maximal kurtosis value

  References

### mean_kurtosis_tensor

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

  Compute mean of the kurtosis tensor (MKT).

  See [24] for further details about the method.

  Parameters:
    dki_params ndarray (x, y, z, 27) or (n, 27)

      All parameters estimated from the diffusion kurtosis model. Parameters are ordered as follows:

      > 1. Three diffusion tensor’s eigenvalues

      > 2. Three lines of the eigenvector matrix each containing the first, second and third coordinates of the eigenvector

      > 3. Fifteen elements of the kurtosis tensor

    min_kurtosis float, optional

      To keep kurtosis values within a plausible biophysical range, mean kurtosis values that are smaller than min_kurtosis are replaced with min_kurtosis. Default = -3./7 (theoretical kurtosis limit for regions that consist of water confined to spherical pores [19]).

    max_kurtosis float, optional

      To keep kurtosis values within a plausible biophysical range, mean kurtosis values that are larger than max_kurtosis are replaced with max_kurtosis.

  Returns:
    mkt array

      Calculated mean kurtosis tensor.

  Notes

  The MKT is defined as [24]:

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

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

  \[\]

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

  References

### radial_tensor_kurtosis

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

  Compute the rescaled radial tensor kurtosis (RTK).

  See [24] for further details about the method.

  Parameters:
    dki_params ndarray (x, y, z, 27) or (n, 27)

      All parameters estimated from the diffusion kurtosis model. Parameters are ordered as follows:

      > 1. Three diffusion tensor’s eigenvalues

      > 2. Three lines of the eigenvector matrix each containing the first, second and third coordinates of the eigenvector

      > 3. Fifteen elements of the kurtosis tensor

    min_kurtosis float, optional

      To keep kurtosis values within a plausible biophysical range, radial kurtosis values that are smaller than min_kurtosis are replaced with min_kurtosis.

    max_kurtosis float, optional

      To keep kurtosis values within a plausible biophysical range, radial kurtosis values that are larger than max_kurtosis are replaced with max_kurtosis.

  Returns:
    rtk array

      Calculated rescaled radial tensor kurtosis (RTK).

  Notes

  Rescaled radial tensor kurtosis (RTK) is defined as [24]:

  \[\]

  RKT = frac{3}{8} frac{MD^2}{RD^2} (W_{2222} + W_{3333} + 2*W_{2233})

  where W is the kurtosis tensor rotated to a coordinate system in which the 3 orthonormal eigenvectors of DT are the base coordinate, MD is the mean diffusivity, and RD is the radial diffusivity.

  References

### kurtosis_fractional_anisotropy

dipy.reconst.dki.kurtosis_fractional_anisotropy(dki_params, fast=True)

  Compute the anisotropy of the kurtosis tensor (KFA).

  See [22] and [20] for further details about the method.

  Parameters:
    dki_params ndarray (x, y, z, 27) or (n, 27)

      All parameters estimated from the diffusion kurtosis model. Parameters are ordered as follows:

      > 1. Three diffusion tensor’s eigenvalues

      > 2. Three lines of the eigenvector matrix each containing the first, second and third coordinates of the eigenvector

      > 3. Fifteen elements of the kurtosis tensor

    fast bool, optional

      If True, use the Cython-optimized implementation. If False, use the pure Python implementation. Both produce identical results.

  Returns:
    kfa array

      Calculated mean kurtosis tensor.

  Notes

  The KFA is defined as [22]:

  \[KFA \equiv \frac{||\mathbf{W} - MKT \mathbf{I}^{(4)}||_F}{||\mathbf{W}||_F}\]

  where \(W\) is the kurtosis tensor, MKT the kurtosis tensor mean, \(I^{(4)}\) is the fully symmetric rank 2 isotropic tensor and \(||...||_F\) is the tensor’s Frobenius norm [22].

  References

### dki_prediction

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

  Predict a signal given diffusion kurtosis imaging parameters

  The predicted signal is given by:

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

  See [19] and [20] for further details about the method.

  Parameters:
    dki_params ndarray (x, y, z, 27) or (n, 27)

      All parameters estimated from the diffusion kurtosis model. Parameters are ordered as follows:

      > 1. Three diffusion tensor’s eigenvalues

      > 2. Three lines of the eigenvector matrix each containing the first, second and third coordinates of the eigenvector

      > 3. Fifteen elements of the kurtosis tensor

    gtab a GradientTable class instance

      The gradient table for this prediction

    S0 float or ndarray, optional

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

  Returns:
    pred_sig(…, N) ndarray

      Simulated signal based on the DKI model.

  References

### params_to_dki_params

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

  Convert the 21 unique elements of the diffusion and kurtosis tensors to the parameter format adopted in DIPY

  Parameters:
    results array (21)

      Unique elements of the diffusion and kurtosis tensors in the following order: 1) six unique lower triangular DT elements; and 2) Fifteen unique elements of the kurtosis tensor.

    min_diffusivity float, optional

      Because negative eigenvalues are not physical and small eigenvalues, much smaller than the diffusion weighting, cause quite a lot of noise in metrics such as fa, diffusivity values smaller than min_diffusivity are replaced with min_diffusivity.

  Returns:
    dki_params array (27)

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

      > 1. Three diffusion tensor eigenvalues.

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

      > 3. Fifteen elements of the kurtosis tensor.

### ls_fit_dki

dipy.reconst.dki.ls_fit_dki(design_matrix, data, inverse_design_matrix, *, return_S0_hat=False, weights=True, min_diffusivity=0, return_lower_triangular=False, return_leverages=False)

  Compute the diffusion and kurtosis tensors using an ordinary or weighted linear least squares approach.

  See [28] for further details about the method.

  Parameters:
    design_matrix array (g, 22)

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

    data array (g)

      Data or response variables holding the data.

    inverse_design_matrix array (22, g)

      Inverse of the design matrix.

    return_S0_hat bool, optional

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

    weights bool or array-like, shape (g,), optional

      Parameter indicating whether per-voxel weights are used. If True, weights are estimated as the squared predicted signal from an initial OLS fit. If an array is provided, these weights must correspond to the squared residuals such that \(S = \sum_i w_i r_i^2\) for the g measurements of the current voxel. If False, no weights are used.

    min_diffusivity float, optional

      Because negative eigenvalues are not physical and small eigenvalues, much smaller than the diffusion weighting, cause quite a lot of noise in metrics such as fa, diffusivity values smaller than min_diffusivity are replaced with min_diffusivity.

    return_lower_triangular bool, optional

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

    return_leverages bool, optional

      Boolean to return (True) or not (False) the fitting leverages.

  Returns:
    dki_params array (27)

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

      > 1. Three diffusion tensor eigenvalues.

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

      > 3. Fifteen elements of the kurtosis tensor.

    leverages array (g)

      Leverages of the fitting problem (if return_leverages is True)

  References

  [28]

  Jelle Veraart, Jan Sijbers, Stefan Sunaert, Alexander Leemans, and Ben Jeurissen. Weighted linear least squares estimation of diffusion MRI parameters: Strengths, limitations, and pitfalls. NeuroImage, 81:335–346, 2013. URL: https://doi.org/10.1016/j.neuroimage.2013.05.028, doi:10.1016/j.neuroimage.2013.05.028.

### cls_fit_dki

dipy.reconst.dki.cls_fit_dki(design_matrix, data, inverse_design_matrix, sdp, *, return_S0_hat=False, weights=True, min_diffusivity=0, return_lower_triangular=False, return_leverages=False, cvxpy_solver=None)

  Compute the diffusion and kurtosis tensors using a constrained ordinary or weighted linear least squares approach.

  See [29] for further details about the method.

  Parameters:
    design_matrix array (g, 22)

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

    data array (g)

      Data or response variables holding the data.

    inverse_design_matrix array (22, g)

      Inverse of the design matrix.

    sdp PositiveDefiniteLeastSquares instance

      A CVXPY representation of a regularized least squares optimization problem.

    return_S0_hat bool, optional

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

    weights bool or array-like, shape (g,), optional

      Parameter indicating whether per-voxel weights are used. If True, weights are estimated as the squared predicted signal from an initial OLS fit. If an array is provided, these weights must correspond to the squared residuals such that \(S = \sum_i w_i r_i^2\) for the g measurements of the current voxel. If False, no weights are used.

    min_diffusivity float, optional

      Because negative eigenvalues are not physical and small eigenvalues, much smaller than the diffusion weighting, cause quite a lot of noise in metrics such as fa, diffusivity values smaller than min_diffusivity are replaced with min_diffusivity.

    return_lower_triangular bool, optional

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

    return_leverages bool, optional

      Boolean to return (True) or not (False) the fitting leverages.

    cvxpy_solver str, optional

      cvxpy solver name. Optionally optimize the positivity constraint with a particular cvxpy solver. See https://www.cvxpy.org/ for details. Default: None (cvxpy chooses its own solver).

  Returns:
    dki_params array (27)

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

      > 1. Three diffusion tensor eigenvalues.

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

      > 3. Fifteen elements of the kurtosis tensor.

    leverages array (g)

      Leverages of the fitting problem (if return_leverages is True)

  References

  [29]

  Tom Dela Haije, Evren Özarslan, and Aasa Feragen. Enforcing necessary non-negativity constraints for common diffusion MRI models using sum of squares programming. NeuroImage, 209:116405, 2020. URL: https://doi.org/10.1016/j.neuroimage.2019.116405, doi:10.1016/j.neuroimage.2019.116405.

### Wrotate

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

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

  See [30] for further details about the method.

  Parameters:
    kt(15,)

      Vector with the 15 independent elements of the kurtosis tensor

    Basis array (3, 3)

      Vectors of the basis column-wise oriented

    inds array(m, 4), optional

      Array of vectors containing the four indexes of m specific elements of the rotated kurtosis tensor. If not specified all 15 elements of the rotated kurtosis tensor are computed.

  Returns:
    Wrot array (m,) or (15,)

      Vector with the m independent elements of the rotated kurtosis tensor. If ‘indices’ is not specified all 15 elements of the rotated kurtosis tensor are computed.

  Notes

  The kurtosis tensor elements are assumed to be ordered as follows:

  \[\begin{split}KT = \begin{pmatrix} W_{xxxx} & W_{yyyy} & W_{zzzz} & W_{xxxy} & W_{xxxz} \\ W_{xyyy} & W_{yyyz} & W_{xzzz} & W_{yzzz} & W_{xxyy} \\ W_{xxzz} & W_{yyzz} & W_{xxyz} & W_{xyyz} & W_{xyzz} \end{pmatrix}\end{split}\]

  References

  [30] (1,2)

  Edward S. Hui, Matthew M. Cheung, Liqun Qi, and Ed X. Wu. Towards better MR characterization of neural tissues using directional diffusion kurtosis analysis. NeuroImage, 42(1):122–134, 2008. URL: https://doi.org/10.1016/j.neuroimage.2008.04.237, doi:10.1016/j.neuroimage.2008.04.237.

### Wrotate_element

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

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

  See [30] for further details about the method.

  Parameters:
    kt ndarray (x, y, z, 15) or (n, 15)

      Array containing the 15 independent elements of the kurtosis tensor

    indi int

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

    indj int

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

    indk int

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

    indl: int

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

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

      Vectors of the basis column-wise oriented

  Returns:
    Wre float

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

  Notes

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

  References

### Wcons

dipy.reconst.dki.Wcons(k_elements)

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

  Parameters:
    k_elements(15,)

      elements of the kurtosis tensor in the following order:

    .. math::
    KT =
    begin{pmatrix}

      W_{xxxx} & W_{yyyy} & W_{zzzz} & W_{xxxy} & W_{xxxz} \ W_{xyyy} & W_{yyyz} & W_{xzzz} & W_{yzzz} & W_{xxyy} \ W_{xxzz} & W_{yyzz} & W_{xxyz} & W_{xyyz} & W_{xyzz}

    end{pmatrix}
  Returns:
    W array(3, 3, 3, 3)

      Full 4D kurtosis tensor

### split_dki_param

dipy.reconst.dki.split_dki_param(dki_params)

  Extract the diffusion tensor eigenvalues, the diffusion tensor eigenvector matrix, and the 15 independent elements of the kurtosis tensor from the model parameters estimated from the DKI model

  Parameters:
    dki_params ndarray (x, y, z, 27) or (n, 27)

      All parameters estimated from the diffusion kurtosis model. Parameters are ordered as follows:

      > 1. Three diffusion tensor’s eigenvalues

      > 2. Three lines of the eigenvector matrix each containing the first, second and third coordinates of the eigenvector

      > 3. Fifteen elements of the kurtosis tensor

  Returns:
    eigvals array (x, y, z, 3) or (n, 3)

      Eigenvalues from eigen decomposition of the tensor.

    eigvecs array (x, y, z, 3, 3) or (n, 3, 3)

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

    kt array (x, y, z, 15) or (n, 15)

      Fifteen elements of the kurtosis tensor

### `KurtosisMicrostructureModel`

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

  Bases: `DiffusionKurtosisModel`

  Class for the Diffusion Kurtosis Microstructural Model

  Methods

  `fit`(data, *[, mask, sphere, gtol, awf_only]) | Fit method of the Diffusion Kurtosis Microstructural Model
  `iterative_fit`(data_thres, *[, mask, ...]) | Iteratively Reweighted fitting for the DKI model.
  `multi_fit`(data, *[, mask]) | Fit method for every voxel in data
  `predict`(params, *[, S0]) | Predict a signal for the DKI microstructural model class instance given parameters.

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

    Fit method of the Diffusion Kurtosis Microstructural Model

    Parameters:
      data array

        An 4D matrix containing the diffusion-weighted data.

      mask array

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

      sphere Sphere class instance, optional

        The sphere providing sample directions for the initial search of the maximal value of kurtosis.

      gtol float, optional

        This input is to refine kurtosis maxima under the precision of the directions sampled on the sphere class instance. The gradient of the convergence procedure must be less than gtol before successful termination. If gtol is None, fiber direction is directly taken from the initial sampled directions of the given sphere object

      awf_only bool, optiomal

        If set to true only the axonal volume fraction is computed from the kurtosis tensor. Default = False

  predict(params, *, S0=1.0)

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

    Parameters:
      params ndarray (x, y, z, 40) or (n, 40)

        All parameters estimated from the diffusion kurtosis microstructural model. Parameters are ordered as follows:

        > 1. Three diffusion tensor’s eigenvalues

        > 2. Three lines of the eigenvector matrix each containing the first, second and third coordinates of the eigenvector

        > 3. Fifteen elements of the kurtosis tensor

        > 4. Six elements of the hindered diffusion tensor

        > 5. Six elements of the restricted diffusion tensor

        > 6. Axonal water fraction

      S0 float or ndarray, optional

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

    Notes

    In the original article of DKI microstructural model [31], the hindered and restricted tensors were defined as the intra-cellular and extra-cellular diffusion compartments respectively.

    References

    [31] (1,2,3,4,5,6,7,8,9,10,11,12,13,14)

    Els Fieremans, Jens H. Jensen, and Joseph A. Helpern. White matter characterization with diffusional kurtosis imaging. NeuroImage, 58(1):177–188, 2011. URL: https://doi.org/10.1016/j.neuroimage.2011.06.006, doi:10.1016/j.neuroimage.2011.06.006.

### `KurtosisMicrostructuralFit`

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

  Bases: `DiffusionKurtosisFit`

  Class for fitting the Diffusion Kurtosis Microstructural Model

  Attributes:
    S0_hat
    `awf`

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

    `axonal_diffusivity`

      Returns the axonal diffusivity defined as the restricted diffusion tensor trace.

    `directions`

      For tracking - return the primary direction in each voxel

    `evals`

      Returns the eigenvalues of the tensor as an array

    `evecs`

      Returns the eigenvectors of the tensor as an array, columnwise

    `hindered_ad`

      Returns the axial diffusivity of the hindered compartment.

    `hindered_evals`

      Returns the eigenvalues of the hindered diffusion compartment.

    `hindered_rd`

      Returns the radial diffusivity of the hindered compartment.

    `kfa`

      Return the kurtosis tensor (KFA).

    `kt`

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

    `quadratic_form`

      Calculates the 3x3 diffusion tensor for each voxel

    `restricted_evals`

      Returns the eigenvalues of the restricted diffusion compartment.

    shape
    `tortuosity`

      Returns the tortuosity of the hindered diffusion which is defined by ADe / RDe, where ADe and RDe are the axial and radial diffusivities of the hindered compartment.

  Methods

  `ad`() | Axial diffusivity (AD) calculated from cached eigenvalues.
  `adc`(sphere) | Calculate the apparent diffusion coefficient (ADC) in each direction on the sphere for each voxel in the data
  `ak`(*[, min_kurtosis, max_kurtosis, ...]) | Compute axial kurtosis (AK) of a diffusion kurtosis tensor.
  `akc`(sphere) | Calculate 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]) | Compute the maximum value of a single voxel kurtosis tensor
  `linearity`() |
  `md`() | Mean diffusivity (MD) calculated from cached eigenvalues.
  `mk`(*[, min_kurtosis, max_kurtosis, ...]) | Compute mean kurtosis (MK) from the kurtosis tensor.
  `mkt`(*[, min_kurtosis, max_kurtosis]) | Compute mean of the kurtosis tensor (MKT).
  `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, ...]) | Compute radial kurtosis (RK) of a diffusion kurtosis tensor.
  `rtk`(*[, min_kurtosis, max_kurtosis]) | Compute the rescaled radial tensor kurtosis (RTK).
  `sphericity`() |
  `trace`() | Trace of the tensor calculated from cached eigenvalues.

  lower_triangular |

  property awf

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

    Notes

    The volume fraction of the restricted diffusion compartment can be seen as the volume fraction of the intra-cellular compartment [31].

    References

  property axonal_diffusivity

    Returns the axonal diffusivity defined as the restricted diffusion tensor trace.

    See [31] for further details about the method.

    References

  property hindered_ad

    Returns the axial diffusivity of the hindered compartment.

    Notes

    The hindered diffusion tensor can be seen as the tissue’s extra-cellular diffusion compartment [31].

    References

  property hindered_evals

    Returns the eigenvalues of the hindered diffusion compartment.

    Notes

    The hindered diffusion tensor can be seen as the tissue’s extra-cellular diffusion compartment [31].

    References

  property hindered_rd

    Returns the radial diffusivity of the hindered compartment.

    Notes

    The hindered diffusion tensor can be seen as the tissue’s extra-cellular diffusion compartment [31].

    References

  predict(gtab, *, S0=1.0)

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

    gtaba GradientTable class instance

      The gradient table for this prediction

    S0float or ndarray, optional

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

    Notes

    The predicted signal is given by:

    \[S(\theta, b) = S_0 * [f * e^{-b ADC_{r}} + (1-f) * e^{-b ADC_{h}]\]

    where \(ADC_{r}\) and \(ADC_{h}\) are the apparent diffusion coefficients of the diffusion hindered and restricted compartment for a given direction \(\theta\), \(b\) is the b value provided in the GradientTable input for that direction, \(f\) is the volume fraction of the restricted diffusion compartment (also known as the axonal water fraction).

  property restricted_evals

    Returns the eigenvalues of the restricted diffusion compartment.

    Notes

    The restricted diffusion tensor can be seen as the tissue’s intra-cellular diffusion compartment [31].

    References

  property tortuosity

    Returns the tortuosity of the hindered diffusion which is defined by ADe / RDe, where ADe and RDe are the axial and radial diffusivities of the hindered compartment.

    See [31] for further details about the method.

    Notes

    The hindered diffusion tensor can be seen as the tissue’s extra-cellular diffusion compartment [31].

    References

### axonal_water_fraction

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

  Computes the axonal water fraction from DKI.

  See [31] for further details about the method.

  Parameters:
    dki_params ndarray (x, y, z, 27) or (n, 27)

      All parameters estimated from the diffusion kurtosis model. Parameters are ordered as follows:

      > 1. Three diffusion tensor’s eigenvalues

      > 2. Three lines of the eigenvector matrix each containing the first, second and third coordinates of the eigenvector

      > 3. Fifteen elements of the kurtosis tensor

    sphere Sphere class instance, optional

      The sphere providing sample directions for the initial search of the maximal value of kurtosis.

    gtol float, optional

      This input is to refine kurtosis maxima under the precision of the directions sampled on the sphere class instance. The gradient of the convergence procedure must be less than gtol before successful termination. If gtol is None, fiber direction is directly taken from the initial sampled directions of the given sphere object

    mask ndarray

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

  Returns:
    awf ndarray (x, y, z) or (n)

      Axonal Water Fraction

  References

### diffusion_components

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

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

  See [31] for further details about the method.

  Parameters:
    dki_params ndarray (x, y, z, 27) or (n, 27)

      All parameters estimated from the diffusion kurtosis model. Parameters are ordered as follows:

      > 1. Three diffusion tensor’s eigenvalues

      > 2. Three lines of the eigenvector matrix each containing the first, second and third coordinates of the eigenvector

      > 3. Fifteen elements of the kurtosis tensor

    sphere Sphere class instance, optional

      The sphere providing sample directions to sample the restricted and hindered cellular diffusion tensors. For more details see [31].

    awf ndarray, optional

      Array containing values of the axonal water fraction that has the shape dki_params.shape[:-1]. If not given this will be automatically computed using `axonal_water_fraction()` with function’s default precision.

    mask ndarray, optional

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

  Returns:
    edt ndarray (x, y, z, 6) or (n, 6)

      Parameters of the hindered diffusion tensor.

    idt ndarray (x, y, z, 6) or (n, 6)

      Parameters of the restricted diffusion tensor.

  Notes

  In the original article of DKI microstructural model [31], the hindered and restricted tensors were defined as the intra-cellular and extra-cellular diffusion compartments respectively.

  References

### dkimicro_prediction

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

  Signal prediction given the DKI microstructure model parameters.

  Parameters:
    params ndarray (x, y, z, 40) or (n, 40)

      All parameters estimated from the diffusion kurtosis microstructure model. Parameters are ordered as follows:

      > 1. Three diffusion tensor’s eigenvalues

      > 2. Three lines of the eigenvector matrix each containing the first, second and third coordinates of the eigenvector

      > 3. Fifteen elements of the kurtosis tensor

      > 4. Six elements of the hindered diffusion tensor

      > 5. Six elements of the restricted diffusion tensor

      > 6. Axonal water fraction

    gtab a GradientTable class instance

      The gradient table for this prediction

    S0 float or ndarray, optional

      The non diffusion-weighted signal in every voxel, or across all voxels

  Returns:
    S(…, N) ndarray

      Simulated signal based on the DKI microstructure model

  Notes

  1. The predicted signal is given by: .. math:

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

  2. In the original article of DKI microstructural model [31], the hindered and restricted tensors were defined as the intra-cellular and extra-cellular diffusion compartments respectively.

  References

### tortuosity

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

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

  Parameters:
    hindered_ad: ndarray

      Array containing the values of the hindered axial diffusivity.

    hindered_rd: ndarray

      Array containing the values of the hindered radial diffusivity.

  Returns:
    Tortuosity of the hindered diffusion compartment

### `DiffusionSpectrumModel`

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

  Bases: `OdfModel`, `Cache`

  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

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

    Fit method for every voxel in data

### `DiffusionSpectrumFit`

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

  Bases: `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.
  `rtop_signal`(*[, filtering]) | Calculates the return to origin probability (rtop) from the signal rtop equals to the sum of all signal values

  msd_discrete(*, normalized=True)

    Calculates the mean squared displacement on the discrete propagator

    MSD:{DSI}=\int_{-\infty}^{\infty}\int_{-\infty}^{\infty}\int_{-\infty}^{\infty} P(\hat{\mathbf{r}}) \cdot \hat{\mathbf{r}}^{2} \ dr_x \ dr_y \ dr_z

    where \(\hat{\mathbf{r}}\) is a point in the 3D Propagator space (see [32]).

    Parameters:
      normalized boolean, optional

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

    Returns:
      msd float

        the mean square displacement

    References

    [32] (1,2,3)

    Yu-Chien Wu and Andrew L. Alexander. Hybrid diffusion imaging. NeuroImage, 36(3):617–629, 2007. URL: https://doi.org/10.1016/j.neuroimage.2007.02.050, doi:10.1016/j.neuroimage.2007.02.050.

  odf(sphere)

    Calculates the real discrete odf for a given discrete sphere

    \[\psi_{DSI}(\hat{\mathbf{u}})=\int_{0}^{\infty}P(r\hat{\mathbf{u}})r^{2}dr\]

    where \(\hat{\mathbf{u}}\) is the unit vector which corresponds to a sphere point.

  pdf(*, normalized=True)

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

  rtop_pdf(*, normalized=True)

    Calculates the return to origin probability from the propagator, which is the propagator evaluated at zero.

    rtop = P(0)

    See [33], [34] and [35] for further details about the method.

    Parameters:
      normalized boolean, optional

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

    Returns:
      rtop float

        the return to origin probability

    References

    [33]

    Maxime Descoteaux, Rachid Deriche, Denis Le Bihan, Jean-François Mangin, and Cyril Poupon. Multiple q-shell diffusion propagator imaging. Medical Image Analysis, 15(4):603–621, 2011. Special section on IPMI 2009. URL: https://doi.org/10.1016/j.media.2010.07.001, doi:10.1016/j.media.2010.07.001.

    [34]

    David S. Tuch. Diffusion MRI of Complex Tissue Structure. PhD thesis, Massachusetts Institute of Technology, Cambridge, USA, 2002. URL: http://hdl.handle.net/1721.1/8348, doi:.

    [35]

    Yu-Chien Wu, Aaron S. Field, and Andrew L. Alexander. Computation of Diffusion Function Measures in $q$-Space Using Magnetic Resonance Hybrid Diffusion Imaging. IEEE Transactions on Medical Imaging, 27(6):858–865, 2008. doi:10.1109/TMI.2008.922696.

  rtop_signal(*, filtering=True)

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

    Parameters:
      filtering boolean, optional

        Whether to perform Hanning filtering.

    Returns:
      rtop float

        the return to origin probability

### `DiffusionSpectrumDeconvModel`

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

  Bases: `DiffusionSpectrumModel`

  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

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

    Fit method for every voxel in data

### `DiffusionSpectrumDeconvFit`

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

  Bases: `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.
  `rtop_signal`(*[, filtering]) | Calculates the return to origin probability (rtop) from the signal rtop equals to the sum of all signal values

  pdf()

    Applies the 3D FFT in the q-space grid to generate the DSI diffusion propagator, remove the background noise with a hard threshold and then deconvolve the propagator with the Lucy-Richardson deconvolution algorithm

### create_qspace

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

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

  Parameters:
    gtab GradientTable

      Gradient table.

    origin(3,) ndarray

      center of qspace

  Returns:
    qgrid ndarray

      qspace coordinates

### create_qtable

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

  create a normalized version of gradients

  Parameters:
    gtab GradientTable

      Gradient table.

    origin(3,) ndarray

      center of qspace

  Returns:
    qtable ndarray

### hanning_filter

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

  create a hanning window

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

  Parameters:
    gtab GradientTable

      Gradient table.

    filter_width int

      Strength of the Hanning filter.

    origin(3,) ndarray

      center of qspace

  Returns:
    filter(N,) ndarray

      where N is the number of non-b0 gradient directions

### pdf_interp_coords

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

  Precompute coordinates for ODF calculation from the PDF

  Parameters:
    sphere object,

      Sphere

    rradius array, shape (N,)

      line interpolation points

    origin array, shape (3,)

      center of the grid

### pdf_odf

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

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

  Parameters:
    Pr array, shape (X, X, X)

      probability density function

    rradius array, shape (N,)

      interpolation range on the radius

    interp_coords array, shape (3, M, N)

      coordinates in the pdf for interpolating the odf

### half_to_full_qspace

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

  Half to full Cartesian grid mapping

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

  Parameters:
    data array, shape (X, Y, Z, W)

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

    gtab GradientTable

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

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

      DWI data across the full Cartesian space.

    new_gtab GradientTable

      Gradient table.

  Notes

  We assume here that only on b0 is provided with the initial data. If that is not the case then you will need to write your own preparation function before providing the gradients and the data to the DiffusionSpectrumModel class.

### project_hemisph_bvecs

dipy.reconst.dsi.project_hemisph_bvecs(gtab)

  Project any near identical bvecs to the other hemisphere

  Parameters:
    gtab object,

      GradientTable

  Notes

  Useful only when working with some types of dsi data.

### threshold_propagator

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

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

### gen_PSF

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

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

### LR_deconv

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

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

  Parameters:
    prop 3-D ndarray of dtype float

      The 3D volume to be deconvolve

    psf 3-D ndarray of dtype float

      The filter that will be used for the deconvolution.

    numit int

      Number of Lucy-Richardson iteration to perform.

    acc_factor float

      Exponential acceleration factor as in [36].

  References

  [36]

  David S. C. Biggs and Mark Andrews. Acceleration of iterative image restoration algorithms. Applied Optics, 36(8):1766–1775, March 1997. URL: https://doi.org/10.1364/AO.36.001766, doi:10.1364/AO.36.001766.

### `TensorModel`

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

  Bases: `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.

  fit(data, *, mask=None)

    Fit method of the DTI model class

    Parameters:
      data array

        The measured signal from one voxel.

      mask array, optional

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

  predict(dti_params, *, S0=1.0)

    Predict a signal for this TensorModel class instance given parameters.

    Parameters:
      dti_params ndarray

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

      S0 float or ndarray, optional

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

### `TensorFit`

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

  Bases: `object`

  Attributes:
    S0_hat
    `directions`

      For tracking - return the primary direction in each voxel

    `evals`

      Returns the eigenvalues of the tensor as an array

    `evecs`

      Returns the eigenvectors of the tensor as an array, columnwise

    `quadratic_form`

      Calculates the 3x3 diffusion tensor for each voxel

    shape

  Methods

  `ad`() | Axial diffusivity (AD) calculated from cached eigenvalues.
  `adc`(sphere) | Calculate the apparent diffusion coefficient (ADC) in each direction on 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.
  `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:
      ad array (V, 1)

        Calculated AD.

    Notes

    AD is calculated with the following equation:

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

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

    Parameters:
      sphere Sphere class instance

        Sphere providing sample directions to compute the apparent diffusion coefficient.

    Returns:
      adc ndarray

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

    Notes

    The calculation of ADC, relies on the following relationship:

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

    Where Q is the quadratic form of the tensor.

  color_fa()

    Color fractional anisotropy of diffusion tensor

  property directions

    For tracking - return the primary direction in each voxel

  property evals

    Returns the eigenvalues of the tensor as an array

  property evecs

    Returns the eigenvectors of the tensor as an array, columnwise

  fa()

    Fractional anisotropy (FA) calculated from cached eigenvalues.

  ga()

    Geodesic anisotropy (GA) calculated from cached eigenvalues.

  linearity()
    Returns:
      linearity array

        Calculated linearity of the diffusion tensor [37].

    Notes

    Linearity is calculated with the following equation:

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

    References

    [37] (1,2,3,4,5,6)

    Carl-Fredrik Westin, Sharon Peled, Hákon Gudbjartsson, Ron Kikinis, and Ferenc Jolesz. Geometrical diffusion measures for MRI from tensor basis analysis. In 5th Scientific Meeting and Exhibition, volume. Vancouver, Canada, 1997. International Society for Magnetic Resonance in Medicine (ISMRM).

  md()

    Mean diffusivity (MD) calculated from cached eigenvalues.

    Returns:
      md array (V, 1)

        Calculated MD.

    Notes

    MD is calculated with the following equation:

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

    Tensor mode calculated from cached eigenvalues.

  odf(sphere)

    The diffusion orientation distribution function (dODF). This is an estimate of the diffusion distance in each direction

    Parameters:
      sphere Sphere class instance.

        The dODF is calculated in the vertices of this input.

    Returns:
      odf ndarray

        The diffusion distance in every direction of the sphere in every voxel in the input data.

    Notes

    This is based on equation 3 in [38]. To re-derive it from scratch, follow steps in [12], Section 7.9 Equation 7.24 but with an \(r^2\) term in the integral.

    References

    [38]

    Iman Aganj, Christophe Lenglet, Guillermo Sapiro, Essa Yacoub, Kamil Ugurbil, and Noam Harel. 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, 2010. URL: https://onlinelibrary.wiley.com/doi/abs/10.1002/mrm.22365, doi:https://doi.org/10.1002/mrm.22365.

  planarity()
    Returns:
      sphericity array

        Calculated sphericity of the diffusion tensor [37].

    Notes

    Sphericity is calculated with the following equation:

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

    References

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

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

    Parameters:
      gtab a GradientTable class instance

        This encodes the directions for which a prediction is made

      S0 float array, optional

        The mean non-diffusion weighted signal in each voxel. Default: The fitted S0 value in all voxels if it was fitted. Otherwise 1 in all voxels.

      step int, optional

        The chunk size as a number of voxels. Optional parameter with default value 10,000.

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

    Notes

    The predicted signal is given by:

    \[S(\theta, b) = S_0 * e^{-b ADC}\]

    Where: .. math:

        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 and \(b\) is the b value provided in the GradientTable input for that direction

  property quadratic_form

    Calculates the 3x3 diffusion tensor for each voxel

  rd()

    Radial diffusivity (RD) calculated from cached eigenvalues.

    Returns:
      rd array (V, 1)

        Calculated RD.

    Notes

    RD is calculated with the following equation:

    \[RD = \frac{\lambda_2 + \lambda_3}{2}\]
  sphericity()
    Returns:
      sphericity array

        Calculated sphericity of the diffusion tensor [37].

    Notes

    Sphericity is calculated with the following equation:

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

    References

  trace()

    Trace of the tensor calculated from cached eigenvalues.

    Returns:
      trace array (V, 1)

        Calculated trace.

    Notes

    The trace is calculated with the following equation:

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

### fractional_anisotropy

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

  Return Fractional anisotropy (FA) of a diffusion tensor.

  Parameters:
    evals array-like

      Eigenvalues of a diffusion tensor.

    axis int, optional

      Axis of evals which contains 3 eigenvalues.

  Returns:
    fa array

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

  Notes

  FA is calculated using the following equation:

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

### geodesic_anisotropy

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

  Geodesic anisotropy (GA) of a diffusion tensor.

  Parameters:
    evals array-like

      Eigenvalues of a diffusion tensor.

    axis int, optional

      Axis of evals which contains 3 eigenvalues.

  Returns:
    ga array

      Calculated GA. In the range 0 to +infinity

  Notes

  GA is calculated using the following equation given in [39]:

  \[GA = \sqrt{\sum_{i=1}^3 \log^2{\left ( \lambda_i/<\mathbf{D}> \right )}}, \quad \textrm{where} \quad <\mathbf{D}> = (\lambda_1\lambda_2\lambda_3)^{1/3}\]

  Note that the notation, \(<D>\), is often used as the mean diffusivity (MD) of the diffusion tensor and can lead to confusions in the literature (see [39] versus [40] versus [41] for example). [40] defines geodesic anisotropy (GA) with \(<D>\) as the MD in the denominator of the sum. This is wrong. The original paper [39] 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 [39] and log-Euclidean derivations from [41] are clear on this. Hence, all that to say that \(<D> = det(D)^{1/3}\) here for the GA definition and not MD.

  See also [42].

  References

  [39] (1,2,3,4)

  Phillipp G. Batchelor, Maher Moakher, David Atkinson, Fernando Calamante, and Alan Connelly. A rigorous framework for diffusion tensor calculus. Magnetic Resonance in Medicine, 53(1):221–225, 2005. URL: https://doi.org/10.1002/mrm.20334, doi:10.1002/mrm.20334.

  [40] (1,2)

  Marta Morgado Correia, Virginia F. J. Newcombe, and Guy B. Williams. Contrast-to-noise ratios for indices of anisotropy obtained from diffusion MRI: A study with standard clinical b-values at 3T. NeuroImage, 57(3):1103–1115, August 2011. Special Issue: Educational Neuroscience. URL: https://doi.org/10.1016/j.neuroimage.2011.03.004, doi:10.1016/j.neuroimage.2011.03.004.

  [41] (1,2)

  Agatha D. Lee, Natasha Lepore, Marina Barysheva, Yi-Yu Chou, Caroline Brun, Sarah K. Madsen, Katie L. McMahon, Greig I. de Zubicaray, Matthew Meredith, Margaret J. Wright, Arthur W. Toga, and Paul M. Thompson. Comparison of fractional and geodesic anisotropy in diffusion tensor images of 90 monozygotic and dizygotic twins. In 2008 5th IEEE International Symposium on Biomedical Imaging: From Nano to Macro, volume, 943–946. May 2008. doi:10.1109/ISBI.2008.4541153.

  [42]

  Vincent Arsigny, Pierre Fillard, Xavier Pennec, and Nicholas Ayache. Log-Euclidean metrics for fast and simple calculus on diffusion tensors. Magnetic Resonance in Medicine, 56(2):411–421, 2006. URL: https://doi.org/10.1002/mrm.20965, doi:10.1002/mrm.20965.

### mean_diffusivity

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

  Mean Diffusivity (MD) of a diffusion tensor.

  Parameters:
    evals array-like

      Eigenvalues of a diffusion tensor.

    axis int, optional

      Axis of evals which contains 3 eigenvalues.

  Returns:
    md array

      Calculated MD.

  Notes

  MD is calculated with the following equation:

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

### axial_diffusivity

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

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

  Parameters:
    evals array-like

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

    axis int, optional

      Axis of evals which contains 3 eigenvalues.

  Returns:
    ad array

      Calculated AD.

  Notes

  AD is calculated with the following equation:

  \[AD = \lambda_1\]

### radial_diffusivity

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

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

  Parameters:
    evals array-like

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

    axis int, optional

      Axis of evals which contains 3 eigenvalues.

  Returns:
    rd array

      Calculated RD.

  Notes

  RD is calculated with the following equation:

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

### trace

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

  Trace of a diffusion tensor.

  Parameters:
    evals array-like

      Eigenvalues of a diffusion tensor.

    axis int, optional

      Axis of evals which contains 3 eigenvalues.

  Returns:
    trace array

      Calculated trace of the diffusion tensor.

  Notes

  Trace is calculated with the following equation:

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

### color_fa

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

  Color fractional anisotropy of diffusion tensor

  Parameters:
    fa array-like

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

    evecs array-like

      eigen vectors from the tensor model

  Returns:
    rgb Array with 3 channels for each color as the last dimension.

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

  Notes

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

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

### determinant

dipy.reconst.dti.determinant(q_form)

  The determinant of a tensor, given in quadratic form

  Parameters:
    q_form ndarray

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

  Returns:
    det array

      The determinant of the tensor in each spatial coordinate

### isotropic

dipy.reconst.dti.isotropic(q_form)

  Calculate the isotropic part of the tensor.

  See [43] for further details about the method.

  Parameters:
    q_form ndarray

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

  Returns:
    A_hat: ndarray

      The isotropic part of the tensor in each spatial coordinate

  Notes

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

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

  References

  [43] (1,2,3,4,5,6)

  Daniel B. Ennis and Gordon Kindlmann. Orthogonal tensor invariants and the analysis of diffusion tensor magnetic resonance images. Magnetic Resonance in Medicine, 55(1):136–146, 2006. URL: https://doi.org/10.1002/mrm.20741, doi:10.1002/mrm.20741.

### deviatoric

dipy.reconst.dti.deviatoric(q_form)

  Calculate the deviatoric (anisotropic) part of the tensor.

  See [43] for further details about the method.

  Parameters:
    q_form ndarray

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

  Returns:
    A_squiggle ndarray

      The deviatoric part of the tensor in each spatial coordinate.

  Notes

  The deviatoric part of the tensor is defined as (equations 3-5 in [43]):

  \[\widetilde{A} = A - \bar{A}\]

  Where \(A\) is the tensor quadratic form and \(\bar{A}\) is the anisotropic part of the tensor.

  References

### norm

dipy.reconst.dti.norm(q_form)

  Calculate the Frobenius norm of a tensor quadratic form

  Parameters:
    q_form: ndarray

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

  Returns:
    norm ndarray

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

  See also

  `np.linalg.norm`

  Notes

  The Frobenius norm is defined as:

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

### mode

dipy.reconst.dti.mode(q_form)

  Mode (MO) of a diffusion tensor.

  See [43] for further details about the method.

  Parameters:
    q_form ndarray

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

  Returns:
    mode array

      Calculated tensor mode in each spatial coordinate.

  Notes

  Mode ranges between -1 (planar anisotropy) and +1 (linear anisotropy) with 0 representing isotropy. Mode is calculated with the following equation (equation 9 in [43]):

  \[Mode = 3*\sqrt{6}*det(\widetilde{A}/norm(\widetilde{A}))\]

  Where \(\widetilde{A}\) is the deviatoric part of the tensor quadratic form.

  References

### linearity

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

  The linearity of the tensor.

  See [37] for further details about the method.

  Parameters:
    evals array-like

      Eigenvalues of a diffusion tensor.

    axis int, optional

      Axis of evals which contains 3 eigenvalues.

  Returns:
    linearity array

      Calculated linearity of the diffusion tensor.

  Notes

  Linearity is calculated with the following equation:

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

  References

### planarity

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

  The planarity of the tensor.

  See [37] for further details about the method.

  Parameters:
    evals array-like

      Eigenvalues of a diffusion tensor.

    axis int, optional

      Axis of evals which contains 3 eigenvalues.

  Returns:
    linearity array

      Calculated linearity of the diffusion tensor.

  Notes

  Planarity is calculated with the following equation:

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

  References

### sphericity

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

  The sphericity of the tensor.

  See [37] for further details about the method.

  Parameters:
    evals array-like

      Eigenvalues of a diffusion tensor.

    axis int, optional

      Axis of evals which contains 3 eigenvalues.

  Returns:
    sphericity array

      Calculated sphericity of the diffusion tensor.

  Notes

  Sphericity is calculated with the following equation:

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

  References

### apparent_diffusion_coef

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

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

  Parameters:
    q_form ndarray

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

    sphere a Sphere class instance

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

  Notes

  The calculation of ADC, relies on the following relationship:

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

  Where Q is the quadratic form of the tensor.

### tensor_prediction

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

  Predict a signal given tensor parameters.

  Parameters:
    dti_params ndarray

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

    gtab a GradientTable class instance

      The gradient table for this prediction

    S0 float or ndarray

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

  Notes

  The predicted signal is given by:

  \[S(\theta, b) = S_0 * e^{-b ADC}\]

  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.

### iter_fit_tensor

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

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

  Splits data into a number of chunks of specified size and iterates the decorated fit_tensor function over them. This is useful to counteract the temporary but significant memory usage increase in fit_tensor functions that use vectorized operations and need to store large temporary arrays for their vectorized operations.

  Parameters:
    step int, optional

      The chunk size as a number of voxels. Optional parameter with default value 10,000.

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

### wls_fit_tensor

dipy.reconst.dti.wls_fit_tensor(design_matrix, data, *, weights=None, return_S0_hat=False, return_lower_triangular=False, return_leverages=False)

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

  See [44] for further details about the method.

  Parameters:
    design_matrix array (g, 7)

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

    data array ([X, Y, Z, …], g)

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

    weights array ([X, Y, Z, …], g), optional

      Weights to apply for fitting. These weights must correspond to the squared residuals such that \(S = \sum_i w_i r_i^2\). If not provided, weights are estimated as the squared predicted signal from an initial OLS fit [44].

    return_S0_hat bool, optional

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

    return_lower_triangular bool, optional

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

    return_leverages bool, optional

      Boolean to return (True) or not (False) the fitting leverages.

  Returns:
    eigvals array (…, 3)

      Eigenvalues from eigen decomposition of the tensor.

    eigvecs array (…, 3, 3)

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

    leverages array (g)

      Leverages of the fitting problem (if return_leverages is True)

  See also

  `decompose_tensor`

  Notes

  In Chung, et al. 2006, the regression of the WLS fit needed an unbiased preliminary estimate of the weights and therefore the ordinary least squares (OLS) estimates were used. A “two pass” method was implemented:

  > 1. calculate OLS estimates of the data

  > 2. apply the OLS estimates as weights to the WLS fit of the data

  This ensured heteroscedasticity could be properly modeled for various types of bootstrap resampling (namely residual bootstrap).

  \[\begin{split}y = \mathrm{data} \\ X = \mathrm{design matrix} \\ \hat{\beta}_\mathrm{WLS} = \mathrm{desired regression coefficients (e.g. tensor)}\\ \\ \hat{\beta}_\mathrm{WLS} = (X^T W X)^{-1} X^T W y \\ \\ W = \mathrm{diag}((X \hat{\beta}_\mathrm{OLS})^2), \mathrm{where} \hat{\beta}_\mathrm{OLS} = (X^T X)^{-1} X^T y\end{split}\]

  References

  [44] (1,2,3)

  SungWon Chung, Ying Lu, and Roland G. Henry. Comparison of bootstrap approaches for estimation of uncertainties of DTI parameters. NeuroImage, 33(2):531–541, 2006. URL: https://doi.org/10.1016/j.neuroimage.2006.07.001, doi:10.1016/j.neuroimage.2006.07.001.

### ols_fit_tensor

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

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

  See [44] for further details about the method.

  Parameters:
    design_matrix array (g, 7)

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

    data array ([X, Y, Z, …], g)

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

    return_S0_hat bool, optional

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

    return_lower_triangular bool, optional

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

    return_leverages bool, optional

      Boolean to return (True) or not (False) the fitting leverages.

  Returns:
    eigvals array (…, 3)

      Eigenvalues from eigen decomposition of the tensor.

    eigvecs array (…, 3, 3)

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

    leverages array (g)

      Leverages of the fitting problem (if return_leverages is True)

  See also

  `WLS_fit_tensor`, `decompose_tensor`, `design_matrix`

  Notes

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

  References

### nlls_fit_tensor

dipy.reconst.dti.nlls_fit_tensor(design_matrix, data, *, weights=None, jac=True, return_S0_hat=False, fail_is_nan=False, return_lower_triangular=False, return_leverages=False, init_params=None)

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

  Parameters:
    design_matrix array (g, Npar)

      Design matrix holding the covariants used to solve for the regression coefficients. First six parameters of design matrix should correspond to the six unique diffusion tensor elements in the lower triangular order (Dxx, Dxy, Dyy, Dxz, Dyz, Dzz), while last parameter to -log(S0)

    data array ([X, Y, Z, …], g)

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

    weights array ([X, Y, Z, …], g), optional

      Weights to apply for fitting. These weights must correspond to the squared residuals such that \(S = \sum_i w_i r_i^2\).

    jac bool, optional

      Use the Jacobian?

    return_S0_hat bool, optional

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

    fail_is_nan bool, optional

      Boolean to set failed NL fitting to NaN (True) or LS (False, default).

    return_lower_triangular bool, optional

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

    return_leverages bool, optional

      Boolean to return (True) or not (False) the fitting leverages.

    init_params array ([X, Y, Z, …], Npar), optional

      Parameters in lower triangular form as initial optimization guess.

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

      voxel.

### restore_fit_tensor

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

  Compute a robust tensor fit using the RESTORE algorithm.

  Note that the RESTORE algorithm defined in [45] does not define Geman–McClure M-estimator weights as claimed (instead, Cauchy M-estimator weights are defined), but this function does define correct Geman–McClure M-estimator weights.

  Parameters:
    design_matrix array of shape (g, 7)

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

    data array of shape ([X, Y, Z, n_directions], g)

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

    sigma float, optional

      An estimate of the variance. [45] recommend to use 1.5267 * std(background_noise), where background_noise is estimated from some part of the image known to contain no signal (only noise). If not provided, will be estimated per voxel as: sigma = 1.4826 * sqrt(N / (N - p)) * MAD(residuals) as in [46] but with the additional correction factor 1.4826 required to link standard deviation to MAD.

    jac bool, optional

      Whether to use the Jacobian of the tensor to speed the non-linear optimization procedure used to fit the tensor parameters (see also `nlls_fit_tensor()`).

    return_S0_hat bool, optional

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

    fail_is_nan bool, optional

      Boolean to set failed NL fitting to NaN (True) or LS (False).

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

  References

  [45] (1,2,3,4)

  Lin-Ching Chang, Derek K. Jones, and Carlo Pierpaoli. RESTORE: Robust estimation of tensors by outlier rejection. Magnetic Resonance in Medicine, 53(5):1088–1095, 2005. URL: https://doi.org/10.1002/mrm.20426, doi:10.1002/mrm.20426.

  [46]

  Lin-Ching Chang, Lindsay Walker, and Carlo Pierpaoli. Informed RESTORE: A method for robust estimation of diffusion tensor from low redundancy datasets in the presence of physiological noise artifacts. Magnetic Resonance in Medicine, 68(5):1654–1663, 2012. URL: https://doi.org/10.1002/mrm.24173, doi:10.1002/mrm.24173.

### iterative_fit_tensor

dipy.reconst.dti.iterative_fit_tensor(design_matrix, data, *, jac=True, return_S0_hat=False, fit_type=None, num_iter=4, weights_method=None)

  Iteratively Reweighted fitting for the DTI/DKI model.

  Parameters:
    design_matrix ndarray of shape (g, …)

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

    data ndarray of shape ([X, Y, Z, n_directions], g)

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

    jac bool, optional

      Use the Jacobian for NLLS fitting (does nothing for WLS fitting).

    return_S0_hat bool, optional

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

    fit_type str, optional

      Whether to use NLLS or WLS fitting scheme.

    num_iter int, optional

      Number of times to iterate.

    weights_method callable, optional

      A function with args and returns as follows:

          (weights, robust) = weights_method(data, pred_sig, design_matrix,
                                             leverages, idx, num_iter, robust)

  Notes

  Take care to supply an appropriate weights_method for the fit_type. It is possible to use NLLS fitting with weights designed for WLS fitting, but this is a user error.

### robust_fit_tensor_wls

dipy.reconst.dti.robust_fit_tensor_wls(design_matrix, data, *, return_S0_hat=False, num_iter=4)

  Iteratively Reweighted fitting for WLS for the DTI/DKI model.

  Parameters:
    design_matrix ndarray of shape (g, …)

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

    data ndarray of shape ([X, Y, Z, n_directions], g)

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

    return_S0_hat bool, optional

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

    num_iter int, optional

      Number of times to iterate.

  Notes

  This is a convenience function that does:

      iterative_fit_tensor(*args, **kwargs, fit_type="WLS",
                           weights_method=weights_method_wls)

### robust_fit_tensor_nlls

dipy.reconst.dti.robust_fit_tensor_nlls(design_matrix, data, *, jac=True, return_S0_hat=False, num_iter=4)

  Iteratively Reweighted fitting for NLLS for the DTI/DKI model.

  Parameters:
    design_matrix ndarray of shape (g, …)

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

    data ndarray of shape ([X, Y, Z, n_directions], g)

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

    jac bool, optional

      Use the Jacobian?

    return_S0_hat bool, optional

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

    num_iter int, optional

      Number of times to iterate.

  Notes

  This is a convenience function that does:

      iterative_fit_tensor(*args, **kwargs, fit_type="NLLS",
      weights_method=weights_method_nlls)

### from_lower_triangular

dipy.reconst.dti.from_lower_triangular(D)

  Returns a tensor given the six unique tensor elements

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

  Parameters:
    D array_like, (…, >6)

      Unique elements of the tensors

  Returns:
    tensor ndarray (…, 3, 3)

      3 by 3 tensors

### lower_triangular

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

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

  Parameters:
    tensor array_like (…, 3, 3)

      a collection of 3, 3 diffusion tensors

    b0 float, optional

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

  Returns:
    D ndarray

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

### decompose_tensor

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

  Returns eigenvalues and eigenvectors given a diffusion tensor

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

  Parameters:
    tensor array (…, 3, 3)

      Hermitian matrix representing a diffusion tensor.

    min_diffusivity float, optional

      Because negative eigenvalues are not physical and small eigenvalues, much smaller than the diffusion weighting, cause quite a lot of noise in metrics such as fa, diffusivity values smaller than min_diffusivity are replaced with min_diffusivity.

  Returns:
    eigvals array (…, 3)

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

    eigvecs array (…, 3, 3)

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

### design_matrix

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

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

  Parameters:
    gtab A GradientTable class instance
    dtype str, optional

      Parameter to control the dtype of returned designed matrix

  Returns:
    design_matrix array (g,7)

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

### quantize_evecs

dipy.reconst.dti.quantize_evecs(evecs, *, odf_vertices=None, idx=0, n_jobs=-1, engine='serial')

  Find the closest orientation of an evenly distributed sphere

  Parameters:
    evecs ndarray

      Eigenvectors of shape (…, 3, n_evecs)

    odf_vertices ndarray, optional

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

    idx int, optional

      Use idx-th eigenvector as the primary eigenvector for fiber tracking. If 0, uses the largest eigenvalue.

    n_jobs int, optional

      Number of parallel jobs.

    engine str, optional

      Parallel engine to use. Choose from {“serial”, “ray”, “dask”, “joblib”}. “ray” is recommended but requires the ray library to be installed.

  Returns:
    ndarray

      Indices of the closest vertices in the odf_vertices for each principal eigenvector.

### eig_from_lo_tri

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

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

  Parameters:
    data array_like (…, 6)

      diffusion tensors elements stored in lower triangular order

    min_diffusivity float, optional

      See decompose_tensor()

  Returns:
    dti_params array (…, 12)

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

### `SignalIndex`

class dipy.reconst.force.SignalIndex(d)

  Bases: `object`

  Index for inner product similarity search.

  Uses optimized Cython BLAS for fast matrix multiplication and streaming heap for memory-efficient top-k selection.

  Parameters:
    d int

      Dimension of vectors.

  Methods

  `add`(x) | Add vectors to the index.
  `reset`() | Remove all vectors from the index.
  `search`(x, k) | Search for k nearest neighbors by inner product.

  add(x)

    Add vectors to the index.

    Parameters:
      x array-like (n, d)

        Vectors to add, will be converted to float32 C-contiguous.

    Notes

    Each call reallocates the internal array via `np.vstack`. This method is designed for a single bulk load; repeated small `add` calls will exhibit O(n²) memory allocation cost.

  reset()

    Remove all vectors from the index.

  search(x, k)

    Search for k nearest neighbors by inner product.

    Parameters:
      x array-like (n, d) or (d,)

        Query vectors.

      k int

        Number of neighbors.

    Returns:
      distances ndarray (n, k)

        Inner products (descending order).

      indices ndarray (n, k)

        Neighbor indices.

### `FORCEModel`

class dipy.reconst.force.FORCEModel(gtab, *, simulations=None, penalty=1e-05, n_neighbors=50, use_posterior=False, posterior_beta=2000.0, compute_odf=False, verbose=False)

  Bases: `ReconstModel`

  FORCE reconstruction model for signal matching based microstructure.

  Methods

  `fit`(data, *[, mask]) | Fit method for every voxel in data
  `generate`(*[, num_simulations, output_path, ...]) | Generate simulations for matching.
  `load`(input_path) | Load pre-computed simulations from file.

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

    Fit method for every voxel in data

  generate(*, num_simulations=500000, output_path=None, num_cpus=1, wm_threshold=0.5, tortuosity=False, odi_range=(0.01, 0.3), diffusivity_config=None, compute_dti=True, compute_dki=False, verbose=False, use_cache=True)

    Generate simulations for matching.

    When `output_path` is `None` and `use_cache` is `True`, simulations are cached in `~/.dipy/force_simulations/` (or `$DIPY_HOME`). A registry file (`cache_registry.json`) keeps track of the bvals, bvecs, diffusivity configuration and number of simulations for each cached file. If a cached simulation that matches the current gradient table (within tolerance) and diffusivity configuration already exists, it is loaded from disk and generation is skipped.

    Set `use_cache=False` to force regeneration even when a matching cached simulation exists.

    Parameters:
      num_simulations int, optional

        Number of simulated voxels.

      output_path str, optional

        Path to save simulations (.npz). When None, saves to `~/.dipy/force_simulations/` and uses caching.

      num_cpus int, optional

        Number of CPU cores for parallel processing.

      wm_threshold float, optional

        Minimum WM fraction to include fiber labels.

      tortuosity bool, optional

        Use tortuosity constraint for perpendicular diffusivity.

      odi_range tuple, optional

        (min, max) orientation dispersion index range.

      diffusivity_config dict, optional

        Custom diffusivity ranges.

      compute_dti bool, optional

        Compute DTI metrics (FA, MD, RD).

      compute_dki bool, optional

        Compute DKI metrics (AK, RK, MK, KFA).

      verbose bool, optional

        Enable progress output.

      use_cache bool, optional

        Whether to use cached simulations when `output_path` is None. Set to `False` to always regenerate.

    Returns:
      self FORCEModel

        Model with simulations loaded.

  load(input_path)

    Load pre-computed simulations from file.

    Parameters:
      input_path str

        Path to simulations file (.npz).

    Returns:
      self FORCEModel

        Model with simulations loaded.

### `FORCEFit`

class dipy.reconst.force.FORCEFit(model, params)

  Bases: `ReconstFit`

  FORCE model fit results for a single voxel.

  Attributes:
    `ak`

      Axial kurtosis (DKI).

    `ambiguity`

      Ambiguity (fraction above half-max).

    `ambiguity_ak`

      Per-microstructure ambiguity for AK (fraction of prior range).

    `ambiguity_csf_fraction`

      Per-microstructure ambiguity for CSF fraction (fraction of prior range).

    `ambiguity_dispersion`

      Per-microstructure ambiguity for dispersion (fraction of prior range).

    `ambiguity_fa`

      Per-microstructure ambiguity for FA (fraction of prior range).

    `ambiguity_gm_fraction`

      Per-microstructure ambiguity for GM fraction (fraction of prior range).

    `ambiguity_kfa`

      Per-microstructure ambiguity for KFA (fraction of prior range).

    `ambiguity_md`

      Per-microstructure ambiguity for MD (fraction of prior range).

    `ambiguity_mk`

      Per-microstructure ambiguity for MK (fraction of prior range).

    `ambiguity_nd`

      Per-microstructure ambiguity for ND (fraction of prior range).

    `ambiguity_num_fibers`

      Per-microstructure ambiguity for num_fibers (fraction of prior range).

    `ambiguity_rd`

      Per-microstructure ambiguity for RD (fraction of prior range).

    `ambiguity_rk`

      Per-microstructure ambiguity for RK (fraction of prior range).

    `ambiguity_ufa_voxel`

      Per-microstructure ambiguity for microFA voxel (fraction of prior range).

    `ambiguity_wm_fraction`

      Per-microstructure ambiguity for WM fraction (fraction of prior range).

    `csf_fraction`

      CSF fraction.

    `dispersion`

      Orientation dispersion.

    `entropy`

      Entropy (posterior mode only).

    `fa`

      Fractional anisotropy.

    `fracs`

      Fiber fractions.

    `gm_fraction`

      Gray matter fraction.

    `kfa`

      Kurtosis fractional anisotropy (DKI).

    `label`

      Fiber configuration label.

    `md`

      Mean diffusivity.

    `mk`

      Mean kurtosis (DKI).

    `nd`

      Neurite density.

    `num_fibers`

      Number of fibers.

    `odf`

      Orientation distribution function.

    `predicted_signal`

      Predicted signal from matched library entry (cleaned DWI).

    `rd`

      Radial diffusivity.

    `rk`

      Radial kurtosis (DKI).

    `ufa_voxel`

      Voxel-averaged microFA.

    `ufa_wm`

      microFA in white matter.

    `uncertainty`

      Uncertainty (IQR of penalized scores).

    `uncertainty_ak`

      Per-microstructure uncertainty for AK (fraction of prior range).

    `uncertainty_csf_fraction`

      Per-microstructure uncertainty for CSF fraction (fraction of prior range).

    `uncertainty_dispersion`

      Per-microstructure uncertainty for dispersion (fraction of prior range).

    `uncertainty_fa`

      Per-microstructure uncertainty for FA (fraction of prior range).

    `uncertainty_gm_fraction`

      Per-microstructure uncertainty for GM fraction (fraction of prior range).

    `uncertainty_kfa`

      Per-microstructure uncertainty for KFA (fraction of prior range).

    `uncertainty_md`

      Per-microstructure uncertainty for MD (fraction of prior range).

    `uncertainty_mk`

      Per-microstructure uncertainty for MK (fraction of prior range).

    `uncertainty_nd`

      Per-microstructure uncertainty for ND (fraction of prior range).

    `uncertainty_num_fibers`

      Per-microstructure uncertainty for num_fibers (fraction of prior range).

    `uncertainty_rd`

      Per-microstructure uncertainty for RD (fraction of prior range).

    `uncertainty_rk`

      Per-microstructure uncertainty for RK (fraction of prior range).

    `uncertainty_ufa_voxel`

      Uncertainty for microFA voxel (fraction of prior range).

    `uncertainty_wm_fraction`

      Per-microstructure uncertainty for WM fraction (fraction of prior range).

    `wm_fraction`

      White matter fraction.

  property ak

    Axial kurtosis (DKI).

  property ambiguity

    Ambiguity (fraction above half-max).

  property ambiguity_ak

    Per-microstructure ambiguity for AK (fraction of prior range).

  property ambiguity_csf_fraction

    Per-microstructure ambiguity for CSF fraction (fraction of prior range).

  property ambiguity_dispersion

    Per-microstructure ambiguity for dispersion (fraction of prior range).

  property ambiguity_fa

    Per-microstructure ambiguity for FA (fraction of prior range).

  property ambiguity_gm_fraction

    Per-microstructure ambiguity for GM fraction (fraction of prior range).

  property ambiguity_kfa

    Per-microstructure ambiguity for KFA (fraction of prior range).

  property ambiguity_md

    Per-microstructure ambiguity for MD (fraction of prior range).

  property ambiguity_mk

    Per-microstructure ambiguity for MK (fraction of prior range).

  property ambiguity_nd

    Per-microstructure ambiguity for ND (fraction of prior range).

  property ambiguity_num_fibers

    Per-microstructure ambiguity for num_fibers (fraction of prior range).

  property ambiguity_rd

    Per-microstructure ambiguity for RD (fraction of prior range).

  property ambiguity_rk

    Per-microstructure ambiguity for RK (fraction of prior range).

  property ambiguity_ufa_voxel

    Per-microstructure ambiguity for microFA voxel (fraction of prior range).

  property ambiguity_wm_fraction

    Per-microstructure ambiguity for WM fraction (fraction of prior range).

  property csf_fraction

    CSF fraction.

  property dispersion

    Orientation dispersion.

  property entropy

    Entropy (posterior mode only).

  property fa

    Fractional anisotropy.

  property fracs

    Fiber fractions.

  property gm_fraction

    Gray matter fraction.

  property kfa

    Kurtosis fractional anisotropy (DKI).

  property label

    Fiber configuration label.

  property md

    Mean diffusivity.

  property mk

    Mean kurtosis (DKI).

  property nd

    Neurite density.

  property num_fibers

    Number of fibers.

  property odf

    Orientation distribution function.

  property predicted_signal

    Predicted signal from matched library entry (cleaned DWI).

  property rd

    Radial diffusivity.

  property rk

    Radial kurtosis (DKI).

  property ufa_voxel

    Voxel-averaged microFA.

  property ufa_wm

    microFA in white matter.

  property uncertainty

    Uncertainty (IQR of penalized scores).

  property uncertainty_ak

    Per-microstructure uncertainty for AK (fraction of prior range).

  property uncertainty_csf_fraction

    Per-microstructure uncertainty for CSF fraction (fraction of prior range).

  property uncertainty_dispersion

    Per-microstructure uncertainty for dispersion (fraction of prior range).

  property uncertainty_fa

    Per-microstructure uncertainty for FA (fraction of prior range).

  property uncertainty_gm_fraction

    Per-microstructure uncertainty for GM fraction (fraction of prior range).

  property uncertainty_kfa

    Per-microstructure uncertainty for KFA (fraction of prior range).

  property uncertainty_md

    Per-microstructure uncertainty for MD (fraction of prior range).

  property uncertainty_mk

    Per-microstructure uncertainty for MK (fraction of prior range).

  property uncertainty_nd

    Per-microstructure uncertainty for ND (fraction of prior range).

  property uncertainty_num_fibers

    Per-microstructure uncertainty for num_fibers (fraction of prior range).

  property uncertainty_rd

    Per-microstructure uncertainty for RD (fraction of prior range).

  property uncertainty_rk

    Per-microstructure uncertainty for RK (fraction of prior range).

  property uncertainty_ufa_voxel

    Uncertainty for microFA voxel (fraction of prior range).

  property uncertainty_wm_fraction

    Per-microstructure uncertainty for WM fraction (fraction of prior range).

  property wm_fraction

    White matter fraction.

### normalize_signals

dipy.reconst.force.normalize_signals(signals)

  L2-normalize signal array for cosine similarity search.

  Parameters:
    signals ndarray (N, M)

      Signal array with N samples and M measurements.

  Returns:
    normalized ndarray (N, M)

      L2-normalized signals.

### create_signal_index

dipy.reconst.force.create_signal_index(signals_norm)

  Create index for cosine similarity search.

  Parameters:
    signals_norm ndarray (N, M)

      L2-normalized library signals.

  Returns:
    index SignalIndex

      Search index.

### softmax_stable

dipy.reconst.force.softmax_stable(x, *, axis=1)

  Numerically stable softmax.

  Parameters:
    x ndarray

      Input array.

    axis int, optional

      Axis along which to compute softmax.

  Returns:
    softmax ndarray

      Softmax probabilities.

### compute_uncertainty_ambiguity

dipy.reconst.force.compute_uncertainty_ambiguity(scores)

  Compute uncertainty and ambiguity metrics from match scores.

  Parameters:
    scores ndarray (N, K)

      Penalized scores for K neighbors.

  Returns:
    uncertainty ndarray (N,)

      IQR of scores.

    ambiguity ndarray (N,)

      Fraction above half-max.

### compute_microstructure_uncertainty_ambiguity

dipy.reconst.force.compute_microstructure_uncertainty_ambiguity(vals, weights, prior_range)

  Compute per-microstructure uncertainty and ambiguity.

  Uncertainty is the weighted interquartile range of the posterior density, normalized by the prior range. Ambiguity is the full width at half maximum (FWHM) of the weighted posterior density, similarly normalized. Both are in [0, 1] where 0 means no spread and 1 means the posterior spans the entire prior range.

  Parameters:
    vals ndarray (N, K)

      Parameter values for K neighbors per voxel.

    weights ndarray (N, K)

      Posterior weights (softmax).

    prior_range float

      Max minus min of this parameter across the simulation library.

  Returns:
    uncertainty ndarray (N,)

      Weighted IQR / prior_range (fraction in [0, 1]).

    ambiguity ndarray (N,)

      FWHM / prior_range (fraction in [0, 1]).

### postprocess_peaks

dipy.reconst.force.postprocess_peaks(preds, target_sphere, fracs)

### compute_entropy

dipy.reconst.force.compute_entropy(weights)

  Compute entropy of posterior weights.

  Parameters:
    weights ndarray (N, K)

      Posterior weights for K neighbors.

  Returns:
    entropy ndarray (N,)

      Shannon entropy for each sample.

### posterior_mean_signal

dipy.reconst.force.posterior_mean_signal(signals, weights, indices)

  Compute posterior mean signal from neighbors.

  Parameters:
    signals ndarray (N_lib, M)

      Library signals.

    weights ndarray (N_query, K)

      Posterior weights.

    indices ndarray (N_query, K)

      Neighbor indices.

  Returns:
    mean_signal ndarray (N_query, M)

      Posterior mean signals.

### posterior_odf

dipy.reconst.force.posterior_odf(odfs, weights, indices, n_dirs)

  Compute posterior ODF from neighbors.

  Parameters:
    odfs ndarray (N_lib, D)

      Library ODFs.

    weights ndarray (N_query, K)

      Posterior weights.

    indices ndarray (N_query, K)

      Neighbor indices.

    n_dirs int

      Number of sphere directions.

  Returns:
    odf ndarray (N_query, D)

      Posterior mean ODFs.

### force_peaks

dipy.reconst.force.force_peaks(fitted_object, *, mask=None, sh_order=8)

  Create a PeaksAndMetrics object from a FORCEFit or MultiVoxelFit.

  Parameters:
    fitted_object FORCEFit or MultiVoxelFit

      The result of model.fit().

    mask ndarray, optional

      Optional brain mask.

    sh_order int, optional

      Spherical harmonics order for the coefficients.

### `ForecastModel`

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

  Bases: `OdfModel`, `Cache`

  Fiber ORientation Estimated using Continuous Axially Symmetric Tensors (FORECAST).

  FORECAST [47], [48], [49] is a Spherical Deconvolution reconstruction model for multi-shell diffusion data which enables the calculation of a voxel adaptive response function using the Spherical Mean Technique (SMT) [48], [49].

  With FORECAST it is possible to calculate crossing invariant parallel diffusivity, perpendicular diffusivity, mean diffusivity, and fractional anisotropy [48].

  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

  Notes

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

  References

  [47]

  Adam W. Anderson. Measurement of fiber orientation distributions using high angular resolution diffusion imaging. Magnetic Resonance in Medicine, 54(5):1194–1206, 2005. URL: https://doi.org/10.1002/mrm.20667, doi:10.1002/mrm.20667.

  [48] (1,2,3)

  Enrico Kaden, Frithjof Kruggel, and Daniel C. Alexander. Quantitative mapping of the per-axon diffusion coefficients in brain white matter. Magnetic Resonance in Medicine, 75(4):1752–1763, April 2016. URL: https://doi.org/10.1002/mrm.25734, doi:10.1002/mrm.25734.

  [49] (1,2)

  Mauro Zucchelli, Maxime Descoteaux, and Gloria Menegaz. A generalized SMT-based framework for Diffusion MRI microstructural model estimation. In Enrico Kaden, Francesco Grussu, Lipeng Ning, Chantal M. W. Tax, and Jelle Veraart, editors, Computational Diffusion MRI, 51–63. Cham, 2018. Springer International Publishing.

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

    Fit method for every voxel in data

### `ForecastFit`

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

  Bases: `OdfFit`

  Attributes:
    `dpar`

      The parallel diffusivity

    `dperp`

      The perpendicular diffusivity

    `sh_coeff`

      The FORECAST SH coefficients

  Methods

  `fractional_anisotropy`() | Calculates the fractional anisotropy.
  `mean_diffusivity`() | Calculates the mean diffusivity.
  `odf`(sphere, *[, clip_negative]) | Calculates the fODF for a given discrete sphere.
  `predict`(*[, gtab, S0]) | Calculates the fODF for a given discrete sphere.

  property dpar

    The parallel diffusivity

  property dperp

    The perpendicular diffusivity

  fractional_anisotropy()

    Calculates the fractional anisotropy.

  mean_diffusivity()

    Calculates the mean diffusivity.

  odf(sphere, *, clip_negative=True)

    Calculates the fODF for a given discrete sphere.

    Parameters:
      sphere Sphere,

        the odf sphere

      clip_negative boolean, optional

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

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

    Calculates the fODF for a given discrete sphere.

    Parameters:
      gtab GradientTable, optional

        gradient directions and bvalues container class.

      S0 float, optional

        the signal at b-value=0

  property sh_coeff

    The FORECAST SH coefficients

### find_signal_means

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

  Calculate the mean signal for each shell.

  Parameters:
    b_unique 1d ndarray,

      unique b-values in a vector excluding zero

    data_norm 1d ndarray,

      normalized diffusion signal

    bvals 1d ndarray,

      the b-values

    rho 2d ndarray,

      SH basis matrix for fitting the signal on each shell

    lb_matrix 2d ndarray,

      Laplace-Beltrami regularization matrix

    w float,

      weight for the Laplace-Beltrami regularization

  Returns:
    means 1d ndarray

      the average of the signal for each b-values

### forecast_error_func

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

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

### psi_l

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

### forecast_matrix

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

  Compute the FORECAST radial matrix

### rho_matrix

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

  Compute the SH matrix \(\rho\)

### lb_forecast

dipy.reconst.forecast.lb_forecast(sh_order_max)

  Returns the Laplace-Beltrami regularization matrix for FORECAST

### `FreeWaterTensorModel`

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

  Bases: `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.

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

    Fit method for every voxel in data

  predict(fwdti_params, *, S0=1)

    Predict a signal for this TensorModel class instance given parameters.

    Parameters:
      fwdti_params(…, 13) ndarray

        The last dimension should have 13 parameters: the 12 tensor parameters (3 eigenvalues, followed by the 3 corresponding eigenvectors) and the free water volume fraction.

      S0 float or ndarray

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

    Returns:
      S(…, N) ndarray

        Simulated signal based on the free water DTI model

### `FreeWaterTensorFit`

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

  Bases: `TensorFit`

  Class for fitting the Free Water Tensor Model

  Attributes:
    S0_hat
    `directions`

      For tracking - return the primary direction in each voxel

    `evals`

      Returns the eigenvalues of the tensor as an array

    `evecs`

      Returns the eigenvectors of the tensor as an array, columnwise

    `f`

      Returns the free water diffusion volume fraction f

    `quadratic_form`

      Calculates the 3x3 diffusion tensor for each voxel

    shape

  Methods

  `ad`() | Axial diffusivity (AD) calculated from cached eigenvalues.
  `adc`(sphere) | Calculate the apparent diffusion coefficient (ADC) in each direction on 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.
  `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 |

  property f

    Returns the free water diffusion volume fraction f

  predict(gtab, *, S0=1)

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

    Parameters:
      gtab a GradientTable class instance

        The gradient table for this prediction

      S0 float array

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

    Returns:
      S(…, N) ndarray

        Simulated signal based on the free water DTI model

### fwdti_prediction

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

  Signal prediction given the free water DTI model parameters.

  Parameters:
    params(…, 13) ndarray

      Model parameters. The last dimension should have the 12 tensor parameters (3 eigenvalues, followed by the 3 corresponding eigenvectors) and the volume fraction of the free water compartment.

    gtab a GradientTable class instance

      The gradient table for this prediction

    S0 float or ndarray

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

    Diso float, optional

      Value of the free water isotropic diffusion. Default is set to 3e-3 \(mm^{2}.s^{-1}\). Please adjust this value if you are assuming different units of diffusion.

  Returns:
    S(…, N) ndarray

      Simulated signal based on the free water DTI model

  Notes

  The predicted signal is given by: \(S(\theta, b) = S_0 * [(1-f) * e^{-b ADC} + f * e^{-b D_{iso}]\), where \(ADC = \theta Q \theta^T\), \(\theta\) is a unit vector pointing at any direction on the sphere for which a signal is to be predicted, \(b\) is the b value provided in the GradientTable input for that direction, \(Q\) is the quadratic form of the tensor determined by the input parameters, \(f\) is the free water diffusion compartment, \(D_{iso}\) is the free water diffusivity which is equal to $3 * 10^{-3} mm^{2}s^{-1} [50].

  References

  [50] (1,2)

  Rafael Neto Henriques, Ariel Rokem, Eleftherios Garyfallidis, Samuel St-Jean, Eric Thomas Peterson, and Marta Morgado Correia. [Re] Optimization of a free water elimination two-compartment model for diffusion tensor imaging. bioRxiv, 2017. doi:https://doi.org/10.1101/108795.

### wls_iter

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

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

  Parameters:
    design_matrix array (g, 7)

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

    sig array (g, )

      Diffusion-weighted signal for a single voxel data.

    S0 float

      Non diffusion weighted signal (i.e. signal for b-value=0).

    Diso float, optional

      Value of the free water isotropic diffusion. Default is set to 3e-3 \(mm^{2}.s^{-1}\). Please adjust this value if you are assuming different units of diffusion.

    mdreg float, optimal

      DTI’s mean diffusivity regularization threshold. If standard DTI diffusion tensor’s mean diffusivity is almost near the free water diffusion value, the diffusion signal is assumed to be only free water diffusion (i.e. volume fraction will be set to 1 and tissue’s diffusion parameters are set to zero). Default md_reg is 2.7e-3 \(mm^{2}.s^{-1}\) (corresponding to 90% of the free water diffusion value).

    min_signal float

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

    piterations inter, optional

      Number of iterations used to refine the precision of f. Default is set to 3 corresponding to a precision of 0.01.

  Returns:
    fw_params ndarray

      All parameters estimated from the free water tensor model. Parameters are ordered as follows:

      > 1. Three diffusion tensor’s eigenvalues

      > 2. Three lines of the eigenvector matrix each containing the first, second and third coordinates of the eigenvector

      > 3. The volume fraction of the free water compartment

### wls_fit_tensor

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

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

  See [50] for further details about the method.

  Parameters:
    gtab a GradientTable class instance

      The gradient table containing diffusion acquisition parameters.

    data ndarray ([X, Y, Z, …], g)

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

    Diso float, optional

      Value of the free water isotropic diffusion. Default is set to 3e-3 \(mm^{2}.s^{-1}\). Please adjust this value if you are assuming different units of diffusion.

    mask array, optional

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

    min_signal float

      The minimum signal value. Needs to be a strictly positive number.

    piterations inter, optional

      Number of iterations used to refine the precision of f. Default is set to 3 corresponding to a precision of 0.01.

    mdreg float, optimal

      DTI’s mean diffusivity regularization threshold. If standard DTI diffusion tensor’s mean diffusivity is almost near the free water diffusion value, the diffusion signal is assumed to be only free water diffusion (i.e. volume fraction will be set to 1 and tissue’s diffusion parameters are set to zero). Default md_reg is 2.7e-3 \(mm^{2}.s^{-1}\) (corresponding to 90% of the free water diffusion value).

  Returns:
    fw_params ndarray (x, y, z, 13)

      Matrix containing in the last dimension the free water model parameters in the following order:

      > 1. Three diffusion tensor’s eigenvalues

      > 2. Three lines of the eigenvector matrix each containing the first, second and third coordinates of the eigenvector

      > 3. The volume fraction of the free water compartment.

  References

### nls_iter

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

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

  Parameters:
    design_matrix array (g, 7)

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

    sig array (g, )

      Diffusion-weighted signal for a single voxel data.

    S0 float

      Non diffusion weighted signal (i.e. signal for b-value=0).

    Diso float, optional

      Value of the free water isotropic diffusion. Default is set to 3e-3 \(mm^{2}.s^{-1}\). Please adjust this value if you are assuming different units of diffusion.

    mdreg float, optimal

      DTI’s mean diffusivity regularization threshold. If standard DTI diffusion tensor’s mean diffusivity is almost near the free water diffusion value, the diffusion signal is assumed to be only free water diffusion (i.e. volume fraction will be set to 1 and tissue’s diffusion parameters are set to zero). Default md_reg is 2.7e-3 \(mm^{2}.s^{-1}\) (corresponding to 90% of the free water diffusion value).

    min_signal float, optional

      The minimum signal value. Needs to be a strictly positive number.

    cholesky bool, optional

      If true it uses Cholesky decomposition to ensure that diffusion tensor is positive define.

    f_transform bool, optional

      If true, the water volume fractions is converted during the convergence procedure to ft = arcsin(2*f - 1) + pi/2, insuring f estimates between 0 and 1.

    jac bool, optional

      True to use the Jacobian.

    weighting: str, optional

      the weighting scheme to use in considering the squared-error. Default behavior is to use uniform weighting. Other options: ‘sigma’ ‘gmm’

    sigma: float, optional

      If the ‘sigma’ weighting scheme is used, a value of sigma needs to be provided here. According to Chang et al.[45], a good value to use is 1.5267 * std(background_noise), where background_noise is estimated from some part of the image known to contain no signal (only noise).

  Returns:
    All parameters estimated from the free water tensor model.
    Parameters are ordered as follows:

      1. Three diffusion tensor’s eigenvalues

      2. Three lines of the eigenvector matrix each containing the first, second and third coordinates of the eigenvector

      3. The volume fraction of the free water compartment.

### nls_fit_tensor

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

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

  Parameters:
    gtab a GradientTable class instance

      The gradient table containing diffusion acquisition parameters.

    data ndarray ([X, Y, Z, …], g)

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

    mask array, optional

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

    Diso float, optional

      Value of the free water isotropic diffusion. Default is set to 3e-3 \(mm^{2}.s^{-1}\). Please adjust this value if you are assuming different units of diffusion.

    mdreg float, optimal

      DTI’s mean diffusivity regularization threshold. If standard DTI diffusion tensor’s mean diffusivity is almost near the free water diffusion value, the diffusion signal is assumed to be only free water diffusion (i.e. volume fraction will be set to 1 and tissue’s diffusion parameters are set to zero). Default md_reg is 2.7e-3 \(mm^{2}.s^{-1}\) (corresponding to 90% of the free water diffusion value).

    min_signal float, optional

      The minimum signal value. Needs to be a strictly positive number.

    f_transform bool, optional

      If true, the water volume fractions is converted during the convergence procedure to ft = arcsin(2*f - 1) + pi/2, insuring f estimates between 0 and 1.

    cholesky bool, optional

      If true it uses Cholesky decomposition to ensure that diffusion tensor is positive define.

    jac bool, optional

      True to use the Jacobian.

    weighting: str, optional

      the weighting scheme to use in considering the squared-error. Default behavior is to use uniform weighting. Other options: ‘sigma’ ‘gmm’

    sigma: float, optional

      If the ‘sigma’ weighting scheme is used, a value of sigma needs to be provided here. According to Chang et al.[45], a good value to use is 1.5267 * std(background_noise), where background_noise is estimated from some part of the image known to contain no signal (only noise).

  Returns:
    fw_params ndarray (x, y, z, 13)

      Matrix containing in the dimension the free water model parameters in the following order:

      > 1. Three diffusion tensor’s eigenvalues

      > 2. Three lines of the eigenvector matrix each containing the first, second and third coordinates of the eigenvector

      > 3. The volume fraction of the free water compartment

  References

### lower_triangular_to_cholesky

dipy.reconst.fwdti.lower_triangular_to_cholesky(tensor_elements)

  Performs Cholesky decomposition of the diffusion tensor

  Parameters:
    tensor_elements array (6,)

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

  Returns:
    cholesky_elements array (6,)

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

  References

  [51] (1,2)

  Cheng Guan Koay, John D. Carew, Andrew L. Alexander, Peter J. Basser, and M. Elizabeth Meyerand. Investigation of anomalous estimates of tensor-derived quantities in diffusion tensor imaging. Magnetic Resonance in Medicine, 55(4):930–936, April 2006. URL: https://doi.org/10.1002/mrm.20832, doi:10.1002/mrm.20832.

### cholesky_to_lower_triangular

dipy.reconst.fwdti.cholesky_to_lower_triangular(R)

  Convert Cholesky decomposition elements to the diffusion tensor elements

  Parameters:
    R array (6,)

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

  Returns:
    tensor_elements array (6,)

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

  References

### `GeneralizedQSamplingModel`

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

  Bases: `OdfModel`, `Cache`

  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

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

    Fit method for every voxel in data

### `GeneralizedQSamplingFit`

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

  Bases: `OdfFit`

  Methods

  `odf`(sphere) | Calculates the discrete ODF for a given discrete sphere.

  odf(sphere)

    Calculates the discrete ODF for a given discrete sphere.

### normalize_qa

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

  Normalize quantitative anisotropy.

  Used mostly with GQI rather than GQI2.

  Parameters:
    qa array, shape (X, Y, Z, N)

      where N is the maximum number of peaks stored

    max_qa float,

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

  Returns:
    nqa array, shape (x, Y, Z, N)

      normalized quantitative anisotropy

  Notes

  Normalized quantitative anisotropy has the very useful property to be very small near gray matter and background areas. Therefore, it can be used to mask out white matter areas.

### squared_radial_component

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

  Part of the GQI2 integral

  Eq.8 in the referenced paper by Yeh et al.[52].

  References

  [52]

  Fang-Cheng Yeh, Van Jay Wedeen, and Wen-Yih Isaac Tseng. Generalized $q$-Sampling Imaging. IEEE Transactions on Medical Imaging, 29(9):1626–1635, 2010. URL: https://doi.org/10.1109/TMI.2010.2045126, doi:10.1109/TMI.2010.2045126.

### npa

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

  non-parametric anisotropy

  Nimmo-Smith et al. ISMRM 2011

### equatorial_zone_vertices

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

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

### polar_zone_vertices

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

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

### upper_hemi_map

dipy.reconst.gqi.upper_hemi_map(v)

  maps a 3-vector into the z-upper hemisphere

### equatorial_maximum

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

### patch_vertices

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

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

### patch_maximum

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

### odf_sum

dipy.reconst.gqi.odf_sum(odf)

### patch_sum

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

### triple_odf_maxima

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

### `IvimModelTRR`

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

  Bases: `ReconstModel`

  Ivim model

  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, *[, ...]) | 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.

  estimate_f_D_star(params_f_D_star, data, S0, D)

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

    Parameters:
      params_f_D_star: array

        An array containing the value of f and D_star.

      data array

        Array containing the actual signal values.

      S0 float

        The parameters S0 obtained from a linear fit.

      D float

        The parameters D obtained from a linear fit.

    Returns:
      f float

        Perfusion fraction estimated from the fit.

      D_star

        The value of D_star estimated from the fit.

  estimate_linear_fit(data, split_b, *, less_than=True)

    Estimate a linear fit by taking log of data.

    Parameters:
      data array

        An array containing the data to be fit

      split_b float

        The b value to split the data

      less_than bool

        If True, splitting occurs for bvalues less than split_b

    Returns:
      S0 float

        The estimated S0 value. (intercept)

      D float

        The estimated value of D.

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

    Fit method for every voxel in data

  predict(ivim_params, gtab, *, S0=1.0)

    Predict a signal for this IvimModel class instance given parameters.

    Parameters:
      ivim_params array

        The ivim parameters as an array [S0, f, D_star and D]

      gtab GradientTable class instance

        Gradient directions and bvalues.

      S0 float, optional

        This has been added just for consistency with the existing API. Unlike other models, IVIM predicts S0 and this is over written by the S0 value in params.

    Returns:
      ivim_signal array

        The predicted IVIM signal using given parameters.

### `IvimModelVP`

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

  Bases: `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 multiplying 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.

  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:
      phi array

        Returns an array calculated from :func: phi.

      signal array

        The signal values measured for this model.

    Returns:
      f1, f2 (volume fractions)

    Notes

    cost function for differential evolution algorithm:

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

    Fit method for every voxel in data

  ivim_mix_cost_one(phi, signal)

    Constructs the objective for the :func: stoc_search_cost.

    First calculates the Moore-Penrose inverse of the input phi and takes a dot product with the measured signal. The result obtained is again multiplied with phi to complete the projection of the variable into a transformed space. (see [53] and [54] for thorough discussion on Variable Projections and relevant cost functions).

    Parameters:
      phi array

        Returns an array calculated from :func: Phi.

      signal array

        The signal values measured for this model.

    Returns:
      (signal - S)^T(signal - S)

    Notes

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

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

    References

    [53]

    Shreyas Fadnavis, Marco Reisert, Hamza Farooq, Maryam Afzali, Cheng Hu, Bago Amirbekian, and Eleftherios Garyfallidis. MicroLearn: Framework for machine learning, reconstruction, optimization and microstructure modeling. In ISMRM 27th Annual Meeting & Exhibition SMRT 28th Annual Meeting. Montréal, Canada, 2019. International Society for Magnetic Resonance in Medicine (ISMRM).

    [54]

    Hamza Farooq, Junqian Xu, Jung Who Nam, Daniel F. Keefe, Essa Yacoub, Tryphon Georgiou, and Christophe Lenglet. Microstructure imaging of crossing (mix) white matter fibers from diffusion mri. Scientific Reports, 6(1):38927, December 2016. URL: https://doi.org/10.1038/srep38927, doi:10.1038/srep38927.

  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 number of iterations required by the differential evolution optimizer.

    Parameters:
      x_f array

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

      signal array

        The signal values measured for this model.

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

    Notes

    cost function for the least square problem.

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

    Creates a structure for the combining the diffusion and pseudo- diffusion by multiplying with the bvals and then exponentiating each of the two components for fitting as per the IVIM- two compartment model.

    Parameters:
      x array

        input from the Differential Evolution optimizer.

    Returns:
      exp_phi1 array

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

  stoc_search_cost(x, signal)

    Cost function for differential evolution algorithm. Performs a stochastic search for the non-linear parameters ‘x’. The objective function is calculated in the :func: ivim_mix_cost_one. The function constructs the parameters using :func: phi.

    Parameters:
      x array

        input from the Differential Evolution optimizer.

      signal array

        The signal values measured for this model.

    Returns:
      func:

        ivim_mix_cost_one ..

  x_and_f_to_x_f(x, f)

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

    Parameters:
      x, f array

        Split parameters into two separate arrays

    Returns:
      x_f array

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

  x_f_to_x_and_f(x_f)

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

    Parameters:
      x_f array

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

    Returns:
      x, f array

        Split parameters into two separate arrays

### `IvimFit`

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

  Bases: `object`

  Attributes:
    D
    D_star
    S0_predicted
    perfusion_fraction
    shape

  Methods

  `predict`(gtab, *[, S0]) | Given a model fit, predict the signal.

  predict(gtab, *, S0=1.0)

    Given a model fit, predict the signal.

    Parameters:
      gtab GradientTable class instance

        Gradient directions and bvalues

      S0 float

        S0 value here is not necessary and will not be used to predict the signal. It has been added to conform to the structure of the predict method in multi_voxel which requires a keyword argument S0.

    Returns:
      signal array

        The signal values predicted for this model using its parameters.

### ivim_prediction

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

  The Intravoxel incoherent motion (IVIM) model function.

  Parameters:
    params array

      An array of IVIM parameters - [S0, f, D_star, D].

    gtab GradientTable class instance

      Gradient directions and bvalues.

    S0 float, optional

      This has been added just for consistency with the existing API. Unlike other models, IVIM predicts S0 and this is over written by the S0 value in params.

  Returns:
    S array

      An array containing the IVIM signal estimated using given parameters.

### f_D_star_prediction

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

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

  Parameters:
    params array

      The value of f and D_star.

    gtab GradientTable class instance

      Gradient directions and bvalues.

    S0 float

      The parameters S0 obtained from a linear fit.

    D float

      The parameters D obtained from a linear fit.

  Returns:
    S array

      An array containing the IVIM signal estimated using given parameters.

### f_D_star_error

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

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

  Parameters:
    params array

      The value of f and D_star.

    gtab GradientTable class instance

      Gradient directions and bvalues.

    signal array

      Array containing the actual signal values.

    S0 float

      The parameters S0 obtained from a linear fit.

    D float

      The parameters D obtained from a linear fit.

  Returns:
    residual array

      An array containing the difference of actual and estimated signal.

### ivim_model_selector

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

  Selector function to switch between the 2-stage Trust-Region Reflective based NLLS fitting method (also containing the linear fit): trr and the Variable Projections based fitting method: varpro.

  Parameters:
    fit_method string, optional

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

### `MapmriModel`

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

  Bases: `ReconstModel`, `Cache`

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

  The main idea in MAPMRI footcite:p:Ozarslan2013 is to model the diffusion signal as a linear combination of the continuous functions presented in footcite:p:Ozarslan2008 but extending it in three dimensions.

  The main difference with the SHORE proposed in footcite:p:Merlet2013 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 footcite:p:Merlet2013 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.

  See [55] for additional tissue microstructure insights provided by MAPMRI.

  See also footcite:p:Fick2016b, footcite:p:Cheng2012, footcite:p:Hosseinbor2013, footcite:p:Craven1979, and footcite:p:DelaHaije2020 for additional insight into to the model.

  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

  References

  [55] (1,2,3,4)

  Alexandru V. Avram, Joelle E Sarlls, Alan S Barnett, Evren Özarslan, Cibu Thomas, M. Okan Irfanoglu, Elizabeth Hutchinson, Carlo Pierpaoli, and Peter J. Basser. Clinical feasibility of using mean apparent propagator (MAP) MRI to characterize brain tissue microstructure. NeuroImage, 111:159–169, 2015. URL: https://doi.org/10.1016/j.neuroimage.2015.01.007, doi:10.1016/j.neuroimage.2015.01.007.

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

    Fit method for every voxel in data

### `MapmriFit`

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

  Bases: `ReconstFit`

  Attributes:
    `mapmri_R`

      The MAPMRI rotation matrix

    `mapmri_coeff`

      The MAPMRI coefficients

    `mapmri_mu`

      The MAPMRI scale factors

  Methods

  `fitted_signal`(*[, gtab]) | Recovers the fitted signal for the given gradient table.
  `msd`() | Calculates the analytical Mean Squared Displacement (MSD).
  `ng`() | Calculates the analytical non-Gaussiannity (NG).
  `ng_parallel`() | Calculates the analytical parallel non-Gaussiannity (NG).
  `ng_perpendicular`() | Calculates the analytical perpendicular non-Gaussiannity (NG)
  `norm_of_laplacian_signal`() | Calculates the norm of the laplacian of the fitted signal.
  `odf`(sphere, *[, s]) | Calculates the analytical Orientation Distribution Function (ODF) from the signal.
  `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).
  `rtop`() | Calculates the analytical return to the origin probability (RTOP).
  `rtpp`() | Calculates the analytical return to the plane probability (RTPP).

  fitted_signal(*, gtab=None)

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

  property mapmri_R

    The MAPMRI rotation matrix

  property mapmri_coeff

    The MAPMRI coefficients

  property mapmri_mu

    The MAPMRI scale factors

  msd()

    Calculates the analytical Mean Squared Displacement (MSD).

    It is defined as the Laplacian of the origin of the estimated signal [56]. The analytical formula for the MAP-MRI basis was derived in [57] eq. (C13, D1).

    References

    [56] (1,2)

    Jian Cheng. Estimation and Processing of Ensemble Average Propagator and Its Features in Diffusion MRI. PhD thesis, Université Nice Sophia Antipolis, Valbonne, France, 2012. URL:, doi:.

    [57] (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)

    Rutger H. J. Fick, Demian Wassermann, Emmanuel Caruyer, and Rachid Deriche. MAPL: Tissue microstructure estimation using Laplacian-regularized MAP-MRI and its application to HCP data. NeuroImage, 134:365–385, July 2016. URL: https://doi.org/10.1016/j.neuroimage.2016.03.046, doi:10.1016/j.neuroimage.2016.03.046.

  ng()

    Calculates the analytical non-Gaussiannity (NG).

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

    See [58] for a definition of the metric.

    References

    [58] (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34)

    Evren Özarslan, Cheng Guan Koay, Timothy M. Shepherd, Michal E. Komlosh, M. Okan İrfanoǧlu, Carlo Pierpaoli, and Peter J. Basser. Mean apparent propagator (MAP) MRI: A novel diffusion imaging method for mapping tissue microstructure. NeuroImage, 78:16–32, 2013. URL: https://doi.org/10.1016/j.neuroimage.2013.04.016, doi:10.1016/j.neuroimage.2013.04.016.

  ng_parallel()

    Calculates the analytical parallel non-Gaussiannity (NG).

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

    See [58] for a definition of the metric.

    References

  ng_perpendicular()

    Calculates the analytical perpendicular non-Gaussiannity (NG)

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

    See [58] for a definition of the metric.

    References

  norm_of_laplacian_signal()

    Calculates the norm of the laplacian of the fitted signal.

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

    See [57] for a definition of the metric.

    References

  odf(sphere, *, s=2)

    Calculates the analytical Orientation Distribution Function (ODF) from the signal.

    See [58] Eq. (32).

    Parameters:
      sphere Sphere

        A Sphere instance with vertices, edges and faces attributes.

      s unsigned int

        radial moment of the ODF

    References

  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 [58] eq. (32). The radial moment s acts as a sharpening method. The analytical equation for the spherical ODF basis is given in [57] eq. (C8).

    References

  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 [59] eq. (22). The analytical formula for the MAP-MRI basis was derived in [57] eq. (C14, D2).

    References

    [59] (1,2)

    A. Pasha Hosseinbor, Moo K. Chung, Yu-Chien Wu, and Andrew L. Alexander. Bessel Fourier Orientation Reconstruction (BFOR): An analytical diffusion propagator reconstruction for hybrid diffusion imaging and computation of q-space indices. NeuroImage, 64:650–670, 2013. URL: https://doi.org/10.1016/j.neuroimage.2012.08.072, doi:10.1016/j.neuroimage.2012.08.072.

  rtap()

    Calculates the analytical return to the axis probability (RTAP).

    RTAP is defined in [58] eq. (40, 44a). The analytical formula for the isotropic MAP-MRI basis was derived in [57] eq. (C11).

    References

  rtop()

    Calculates the analytical return to the origin probability (RTOP).

    RTOP is defined in [58] eq. (36, 43). The analytical formula for the isotropic MAP-MRI basis was derived in [57] eq. (C11).

    References

  rtpp()

    Calculates the analytical return to the plane probability (RTPP).

    RTPP is defined in [58] eq. (42). The analytical formula for the isotropic MAP-MRI basis was derived in [57] eq. (C11).

    References

### isotropic_scale_factor

dipy.reconst.mapmri.isotropic_scale_factor(mu_squared)

  Estimated isotropic scaling factor.

  See [58] Eq. (49).

  Parameters:
    mu_squared array, shape (N,3)

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

  Returns:
    u0 float

      closest isotropic scale factor for the isotropic basis

  References

### mapmri_index_matrix

dipy.reconst.mapmri.mapmri_index_matrix(radial_order)

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

  See [58] for a definition of MAPMRI.

  Parameters:
    radial_order unsigned int

      radial order of MAPMRI basis

  Returns:
    index_matrix array, shape (N,3)

      ordering of the basis in x, y, z

  References

### b_mat

dipy.reconst.mapmri.b_mat(index_matrix)

  Calculates the B coefficients from

  See [58] Eq. (27).

  Parameters:
    index_matrix array, shape (N,3)

      ordering of the basis in x, y, z

  Returns:
    B array, shape (N,)

      B coefficients for the basis

  References

### b_mat_isotropic

dipy.reconst.mapmri.b_mat_isotropic(index_matrix)

  Calculates the isotropic B coefficients.

  See [58] Fig 8.

  Parameters:
    index_matrix array, shape (N,3)

      ordering of the isotropic basis in j, l, m

  Returns:
    B array, shape (N,)

      B coefficients for the isotropic basis

  References

### mapmri_phi_1d

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

  One dimensional MAPMRI basis function.

  See [58] Eq. (4).

  Parameters:
    n unsigned int

      order of the basis

    q array, shape (N,)

      points in the q-space in which evaluate the basis

    mu float

      scale factor of the basis

  References

### mapmri_phi_matrix

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

  Compute the MAPMRI phi matrix for the signal.

  See [58] eq. (23).

  Parameters:
    radial_order unsigned int,

      an even integer that represent the order of the basis

    mu array, shape (3,)

      scale factors of the basis for x, y, z

    q_gradients array, shape (N,3)

      points in the q-space in which evaluate the basis

  References

### mapmri_psi_1d

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

  One dimensional MAPMRI propagator basis function.

  See [58] Eq. (10).

  Parameters:
    n unsigned int

      order of the basis

    x array, shape (N,)

      points in the r-space in which evaluate the basis

    mu float

      scale factor of the basis

  References

### mapmri_psi_matrix

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

  Compute the MAPMRI psi matrix for the propagator.

  See [58] eq. (22).

  Parameters:
    radial_order unsigned int,

      an even integer that represent the order of the basis

    mu array, shape (3,)

      scale factors of the basis for x, y, z

    rgrad array, shape (N,3)

      points in the r-space in which evaluate the EAP

  References

### mapmri_odf_matrix

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

  Compute the MAPMRI ODF matrix.

  See [58] Eq. (33).

  Parameters:
    radial_order unsigned int,

      an even integer that represent the order of the basis

    mu array, shape (3,)

      scale factors of the basis for x, y, z

    s unsigned int

      radial moment of the ODF

    vertices array, shape (N,3)

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

  References

### mapmri_isotropic_phi_matrix

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

  Three dimensional isotropic MAPMRI signal basis function

  See [58] Eq. (61).

  Parameters:
    radial_order unsigned int,

      radial order of the mapmri basis.

    mu float,

      positive isotropic scale factor of the basis

    q array, shape (N,3)

      points in the q-space in which evaluate the basis

  References

### mapmri_isotropic_radial_signal_basis

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

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

  See [58] eq. (61).

  Parameters:
    j unsigned int,

      a positive integer related to the radial order

    l_value unsigned int,

      the spherical harmonic order (l)

    mu float,

      isotropic scale factor of the basis

    qval float,

      points in the q-space in which evaluate the basis

  References

### mapmri_isotropic_M_mu_independent

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

  Computed the mu independent part of the signal design matrix.

### mapmri_isotropic_M_mu_dependent

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

  Computed the mu dependent part of the signal design matrix.

### mapmri_isotropic_psi_matrix

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

  Three dimensional isotropic MAPMRI propagator basis function.

  See [58] Eq. (61).

  Parameters:
    radial_order unsigned int,

      radial order of the mapmri basis.

    mu float,

      positive isotropic scale factor of the basis

    rgrad array, shape (N,3)

      points in the r-space in which evaluate the basis

  References

### mapmri_isotropic_radial_pdf_basis

dipy.reconst.mapmri.mapmri_isotropic_radial_pdf_basis(j, l_value, mu, r)

  Radial part of the isotropic 1D-SHORE propagator basis.

  See [58] eq. (61).

  Parameters:
    j unsigned int,

      a positive integer related to the radial order

    l_value unsigned int,

      the spherical harmonic order (l)

    mu float,

      isotropic scale factor of the basis

    r float,

      points in the r-space in which evaluate the basis

  References

### mapmri_isotropic_K_mu_independent

dipy.reconst.mapmri.mapmri_isotropic_K_mu_independent(radial_order, rgrad)

  Computes mu independent part of K. Same trick as with M.

### mapmri_isotropic_K_mu_dependent

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

  Computes mu dependent part of M. Same trick as with M.

### binomialfloat

dipy.reconst.mapmri.binomialfloat(n, k)

  Custom Binomial function

### mapmri_isotropic_odf_matrix

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

  Compute the isotropic MAPMRI ODF matrix.

  The computation follows [58] Eq. 32, but it is done for the isotropic propagator in footcite:p:Ozarslan2013 eq. (60). Analytical derivation in [57] eq. (C8).

  Parameters:
    radial_order unsigned int,

      an even integer that represent the order of the basis

    mu float,

      isotropic scale factor of the isotropic MAP-MRI basis

    s unsigned int

      radial moment of the ODF

    vertices array, shape (N,3)

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

  Returns:
    odf_mat Matrix, shape (N_vertices, N_mapmri_coef)

      ODF design matrix to discrete sphere function

  References

### mapmri_isotropic_odf_sh_matrix

dipy.reconst.mapmri.mapmri_isotropic_odf_sh_matrix(radial_order, mu, s)

  Compute the isotropic MAPMRI ODF matrix.

  The computation follows [58] Eq. 32, but it is done for the isotropic propagator in [58] 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 [57] eq. (C8).

  Parameters:
    radial_order unsigned int,

      an even integer that represent the order of the basis

    mu float,

      isotropic scale factor of the isotropic MAP-MRI basis

    s unsigned int

      radial moment of the ODF

  Returns:
    odf_sh_mat Matrix, shape (N_sh_coef, N_mapmri_coef)

      ODF design matrix to spherical harmonics

  References

### mapmri_isotropic_laplacian_reg_matrix

dipy.reconst.mapmri.mapmri_isotropic_laplacian_reg_matrix(radial_order, mu)

  Computes the Laplacian regularization matrix for MAP-MRI’s isotropic implementation.

  See [57] eq. (C7).

  Parameters:
    radial_order unsigned int,

      an even integer that represent the order of the basis

    mu float,

      isotropic scale factor of the isotropic MAP-MRI basis

  Returns:
    LR Matrix, shape (N_coef, N_coef)

      Laplacian regularization matrix

  References

### mapmri_isotropic_laplacian_reg_matrix_from_index_matrix

dipy.reconst.mapmri.mapmri_isotropic_laplacian_reg_matrix_from_index_matrix(ind_mat, mu)

  Computes the Laplacian regularization matrix for MAP-MRI’s isotropic implementation.

  See [57] eq. (C7).

  Parameters:
    ind_mat matrix (N_coef, 3),

      Basis order matrix

    mu float,

      isotropic scale factor of the isotropic MAP-MRI basis

  Returns:
    LR Matrix, shape (N_coef, N_coef)

      Laplacian regularization matrix

  References

### mapmri_isotropic_index_matrix

dipy.reconst.mapmri.mapmri_isotropic_index_matrix(radial_order)

  Calculates the indices for the isotropic MAPMRI basis.

  See [58] Fig 8.

  Parameters:
    radial_order unsigned int

      radial order of isotropic MAPMRI basis

  Returns:
    index_matrix array, shape (N,3)

      ordering of the basis in x, y, z

  References

### create_rspace

dipy.reconst.mapmri.create_rspace(gridsize, radius_max)

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

  Parameters:
    gridsize unsigned int

      dimension of the propagator grid

    radius_max float

      maximal radius in which compute the propagator

  Returns:
    tab array, shape (N,3)

      real space points in which calculates the pdf

### delta

dipy.reconst.mapmri.delta(n, m)

### map_laplace_u

dipy.reconst.mapmri.map_laplace_u(n, m)

  S(n, m) static matrix for Laplacian regularization.

  See [57] eq. (13).

  Parameters:
    n, m unsigned int

      basis order of the MAP-MRI basis in different directions

  Returns:
    U float,

      Analytical integral of \(\phi_n(q) * \phi_m(q)\)

  References

### map_laplace_t

dipy.reconst.mapmri.map_laplace_t(n, m)

  L(m, n) static matrix for Laplacian regularization.

  See [57] eq. (12).

  Parameters:
    n, m unsigned int

      basis order of the MAP-MRI basis in different directions

  Returns:
    T float

      Analytical integral of \(\phi_n(q) * \phi_m''(q)\)

  References

### map_laplace_s

dipy.reconst.mapmri.map_laplace_s(n, m)

  R(m,n) static matrix for Laplacian regularization.

  See [57] eq. (11).

  Parameters:
    n, m unsigned int

      basis order of the MAP-MRI basis in different directions

  Returns:
    S float

      Analytical integral of \(\phi_n''(q) * \phi_m''(q)\)

  References

### mapmri_STU_reg_matrices

dipy.reconst.mapmri.mapmri_STU_reg_matrices(radial_order)

  Generate the static portions of the Laplacian regularization matrix.

  See [57] eq. (11, 12, 13).

  Parameters:
    radial_order unsigned int,

      an even integer that represent the order of the basis

  Returns:
    S, T, U Matrices, shape (N_coef,N_coef)

      Regularization submatrices

  References

### mapmri_laplacian_reg_matrix

dipy.reconst.mapmri.mapmri_laplacian_reg_matrix(ind_mat, mu, S_mat, T_mat, U_mat)

  Put the Laplacian regularization matrix together.

  See [57] eq. (10).

  The static parts in S, T and U are multiplied and divided by the voxel-specific scale factors.

  Parameters:
    ind_mat matrix (N_coef, 3),

      Basis order matrix

    mu array, shape (3,)

      scale factors of the basis for x, y, z

    S, T, U matrices, shape (N_coef,N_coef)

      Regularization submatrices

  Returns:
    LR matrix (N_coef, N_coef),

      Voxel-specific Laplacian regularization matrix

  References

### generalized_crossvalidation_array

dipy.reconst.mapmri.generalized_crossvalidation_array(data, M, LR, *, weights_array=None)

  Generalized Cross Validation Function.

  See [57] 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:
    data array (N),

      Basis order matrix

    M matrix, shape (N, Ncoef)

      mapmri observation matrix

    LR matrix, shape (N_coef, N_coef)

      regularization matrix

    weights_array array (N_of_weights)

      array of optional regularization weights

  References

### generalized_crossvalidation

dipy.reconst.mapmri.generalized_crossvalidation(data, M, LR, *, gcv_startpoint=0.05)

  Generalized Cross Validation Function.

  Finds optimal regularization weight based on generalized cross-validation.

  See [60] eq. (15).

  Parameters:
    data array (N),

      data array

    M matrix, shape (N, Ncoef)

      mapmri observation matrix

    LR matrix, shape (N_coef, N_coef)

      regularization matrix

    gcv_startpoint float

      startpoint for the gcv optimization

  Returns:
    optimal_lambda float,

      optimal regularization weight

  References

  [60] (1,2,3,4)

  Peter Craven and Grace Wahba. Smoothing Noisy Data with Spline Functions - Estimating the Correct Degree of Smoothing by the Method of Generalized Cross-Validation. Numerische Mathematik, 31(4):377–403, 1979. doi:.

### gcv_cost_function

dipy.reconst.mapmri.gcv_cost_function(weight, args)

  The GCV cost function that is iterated.

  See [57] for further details about the method.

  References

### `MultiShellResponse`

class dipy.reconst.mcsd.MultiShellResponse(response, sh_order_max, shells, *, S0=None)

  Bases: `object`

  Attributes:
    iso

### `MultiShellDeconvModel`

class dipy.reconst.mcsd.MultiShellDeconvModel(gtab, response, reg_sphere=<dipy.core.sphere.HemiSphere object>, *, sh_order_max=8, iso=2, tol=20)

  Bases: `SphHarmModel`

  Methods

  `cache_clear`() | Clear the cache.
  `cache_get`(tag, key, *[, default]) | Retrieve a value from the cache.
  `cache_set`(tag, key, value) | Store a value in the cache.
  `fit`(data, *[, mask]) | Fit method for every voxel in data
  `predict`(params, *[, gtab, S0]) | Compute a signal prediction given spherical harmonic coefficients for the provided GradientTable class instance.
  `sampling_matrix`(sphere) | The matrix needed to sample ODFs from coefficients of the model.

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

    Fit method for every voxel in data

  predict(params, *, gtab=None, S0=None)

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

    Parameters:
      params ndarray

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

      gtab GradientTable

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

      S0 ndarray or float

        The non diffusion-weighted signal value.

### `MSDeconvFit`

class dipy.reconst.mcsd.MSDeconvFit(model, coeff, mask)

  Bases: `SphHarmFit`

  Attributes:
    all_shm_coeff
    shape
    `shm_coeff`

      The spherical harmonic coefficients of the odf

    volume_fractions

  Methods

  `odf`(sphere) | Samples the odf function on the points of a sphere
  `predict`(*[, gtab, S0]) | Predict the diffusion signal from the model coefficients.

  gfa |

  property shm_coeff

    The spherical harmonic coefficients of the odf

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

### `QpFitter`

class dipy.reconst.mcsd.QpFitter(X, reg)

  Bases: `object`

  Methods

  `__call__`(signal) | Call self as a function.

### multi_tissue_basis

dipy.reconst.mcsd.multi_tissue_basis(gtab, sh_order_max, iso_comp)

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

  Parameters:
    gtab GradientTable

      Gradient table.

    sh_order_max int

      Maximal spherical harmonics order (l).

    iso_comp: int

      Number of tissue compartments for running the MSMT-CSD. Minimum number of compartments required is 2.

  Returns:
    B ndarray

      Matrix of the spherical harmonics model used to fit the data

    m_values int `|m_value| <= l_value`

      The phase factor (\(m\)) of the harmonic.

    l_values int `l_value >= 0`

      The order (\(l\)) of the harmonic.

### solve_qp

dipy.reconst.mcsd.solve_qp(P, Q, G, H)

  Helper function to set up and solve the Quadratic Program (QP) in CVXPY. A QP problem has the following form: minimize 1/2 x’ P x + Q’ x subject to G x <= H

  Here the QP solver is based on CVXPY and uses OSQP.

  Parameters:
    P ndarray

      n x n matrix for the primal QP objective function.

    Q ndarray

      n x 1 matrix for the primal QP objective function.

    G ndarray

      m x n matrix for the inequality constraint.

    H ndarray

      m x 1 matrix for the inequality constraint.

  Returns:
    x array

      Optimal solution to the QP problem.

### multi_shell_fiber_response

dipy.reconst.mcsd.multi_shell_fiber_response(sh_order_max, bvals, wm_rf, gm_rf, csf_rf, *, sphere=None, tol=20, btens=None)

  Fiber response function estimation for multi-shell data.

  Parameters:
    sh_order_max int

      Maximum spherical harmonics order (l).

    bvals ndarray

      Array containing the b-values. Must be unique b-values, like outputted by dipy.core.gradients.unique_bvals_tolerance.

    wm_rf(N-1, 4) ndarray

      Response function of the WM tissue, for each bvals, where N is the number of unique b-values including the b0.

    gm_rf(N-1, 4) ndarray

      Response function of the GM tissue, for each bvals.

    csf_rf(N-1, 4) ndarray

      Response function of the CSF tissue, for each bvals.

    sphere dipy.core.Sphere instance, optional

      Sphere where the signal will be evaluated.

    tol int, optional

      Tolerance gap for b-values clustering.

    btens can be any of two options, optional

      1. an array of strings of shape (N,) specifying encoding tensor shape associated with all unique b-values separately. N corresponds to the number of unique b-values, including the b0. Options for elements in array: ‘LTE’, ‘PTE’, ‘STE’, ‘CTE’ corresponding to linear, planar, spherical, and “cigar-shaped” tensor encoding.

      2. an array of shape (N,3,3) specifying the b-tensor of each unique b-values exactly. N corresponds to the number of unique b-values, including the b0.

  Returns:
    MultiShellResponse

      MultiShellResponse object.

### mask_for_response_msmt

dipy.reconst.mcsd.mask_for_response_msmt(gtab, data, *, roi_center=None, roi_radii=10, wm_fa_thr=0.7, gm_fa_thr=0.2, csf_fa_thr=0.1, gm_md_thr=0.0007, csf_md_thr=0.002)
  Computation of masks for multi-shell multi-tissue (msmt) response

    function using FA and MD.

  Parameters:
    gtab GradientTable

      Gradient table.

    data ndarray

      diffusion data (4D)

    roi_center array-like, (3,)

      Center of ROI in data. If center is None, it is assumed that it is the center of the volume with shape data.shape[:3].

    roi_radii int or array-like, (3,)

      radii of cuboid ROI

    wm_fa_thr float

      FA threshold for WM.

    gm_fa_thr float

      FA threshold for GM.

    csf_fa_thr float

      FA threshold for CSF.

    gm_md_thr float

      MD threshold for GM.

    csf_md_thr float

      MD threshold for CSF.

  Returns:
    mask_wm ndarray

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

    mask_gm ndarray

      Mask of voxels within the ROI and with FA below the FA threshold for GM and with MD below the MD threshold for GM.

    mask_csf ndarray

      Mask of voxels within the ROI and with FA below the FA threshold for CSF and with MD below the MD threshold for CSF.

  Notes

  In msmt-CSD there is an important pre-processing step: the estimation of every tissue’s response function. In order to do this, we look for voxels corresponding to WM, GM and CSF. This function aims to accomplish that by returning a mask of voxels within a ROI and who respect some threshold constraints, for each tissue. More precisely, the WM mask must have a FA value above a given threshold. The GM mask and CSF mask must have a FA below given thresholds and a MD below other thresholds. To get the FA and MD, we need to fit a Tensor model to the datasets.

### response_from_mask_msmt

dipy.reconst.mcsd.response_from_mask_msmt(gtab, data, mask_wm, mask_gm, mask_csf, *, tol=20)
  Computation of multi-shell multi-tissue (msmt) response

    functions from given tissues masks.

  Parameters:
    gtab GradientTable

      Gradient table.

    data ndarray

      diffusion data

    mask_wm ndarray

      mask from where to compute the WM response function.

    mask_gm ndarray

      mask from where to compute the GM response function.

    mask_csf ndarray

      mask from where to compute the CSF response function.

    tol int

      tolerance gap for b-values clustering. (Default = 20)

  Returns:
    response_wm ndarray, (len(unique_bvals_tolerance(gtab.bvals))-1, 4)

      (evals, S0) for WM for each unique bvalues (except b0).

    response_gm ndarray, (len(unique_bvals_tolerance(gtab.bvals))-1, 4)

      (evals, S0) for GM for each unique bvalues (except b0).

    response_csf ndarray, (len(unique_bvals_tolerance(gtab.bvals))-1, 4)

      (evals, S0) for CSF for each unique bvalues (except b0).

  Notes

  In msmt-CSD there is an important pre-processing step: the estimation of every tissue’s response function. In order to do this, we look for voxels corresponding to WM, GM and CSF. This information can be obtained by using mcsd.mask_for_response_msmt() through masks of selected voxels. The present function uses such masks to compute the msmt response functions.

  For the responses, we base our approach on the function csdeconv.response_from_mask_ssst(), with the added layers of multishell and multi-tissue (see the ssst function for more information about the computation of the ssst response function). This means that for each tissue we use the previously found masks and loop on them. For each mask, we loop on the b-values (clustered using the tolerance gap) to get many responses and then average them to get one response per tissue.

### auto_response_msmt

dipy.reconst.mcsd.auto_response_msmt(gtab, data, *, tol=20, roi_center=None, roi_radii=10, wm_fa_thr=0.7, gm_fa_thr=0.3, csf_fa_thr=0.15, gm_md_thr=0.001, csf_md_thr=0.0032)
  Automatic estimation of multi-shell multi-tissue (msmt) response

    functions using FA and MD.

  Parameters:
    gtab GradientTable

      Gradient table.

    data ndarray

      diffusion data

    tol int, optional

      Tolerance gap for b-values clustering.

    roi_center array-like, (3,)

      Center of ROI in data. If center is None, it is assumed that it is the center of the volume with shape data.shape[:3].

    roi_radii int or array-like, (3,)

      radii of cuboid ROI

    wm_fa_thr float

      FA threshold for WM.

    gm_fa_thr float

      FA threshold for GM.

    csf_fa_thr float

      FA threshold for CSF.

    gm_md_thr float

      MD threshold for GM.

    csf_md_thr float

      MD threshold for CSF.

  Returns:
    response_wm ndarray, (len(unique_bvals_tolerance(gtab.bvals))-1, 4)

      (evals, S0) for WM for each unique bvalues (except b0).

    response_gm ndarray, (len(unique_bvals_tolerance(gtab.bvals))-1, 4)

      (evals, S0) for GM for each unique bvalues (except b0).

    response_csf ndarray, (len(unique_bvals_tolerance(gtab.bvals))-1, 4)

      (evals, S0) for CSF for each unique bvalues (except b0).

  Notes

  In msmt-CSD there is an important pre-processing step: the estimation of every tissue’s response function. In order to do this, we look for voxels corresponding to WM, GM and CSF. We get this information from mcsd.mask_for_response_msmt(), which returns masks of selected voxels (more details are available in the description of the function).

  With the masks, we compute the response functions by using mcsd.response_from_mask_msmt(), which returns the response for each tissue (more details are available in the description of the function).

### `MeanDiffusionKurtosisModel`

class dipy.reconst.msdki.MeanDiffusionKurtosisModel(gtab, *args, bmag=None, return_S0_hat=False, **kwargs)

  Bases: `ReconstModel`

  Mean signal Diffusion Kurtosis Model

  Methods

  `fit`(data, *[, mask]) | Fit method of the MSDKI model class
  `predict`(msdki_params, *[, S0]) | Predict a signal for this MeanDiffusionKurtosisModel class instance given parameters.

  fit(data, *, mask=None)

    Fit method of the MSDKI model class

    Parameters:
      data ndarray ([X, Y, Z, …], g)

        ndarray containing the data signals in its last dimension.

      mask array

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

  predict(msdki_params, *, S0=1.0)

    Predict a signal for this MeanDiffusionKurtosisModel class instance given parameters.

    See [2] for further details about the method.

    Parameters:
      msdki_params ndarray

        The parameters of the mean signal diffusion kurtosis model

      S0 float or ndarray, optional

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

    Returns:
      S(…, N) ndarray

        Simulated mean signal based on the mean signal diffusion kurtosis model

    Notes

    The predicted signal is given by:

      \(MS(b) = S_0 * exp(-bD + 1/6 b^{2} D^{2} K)\), where \(D\) and \(K\) are the mean signal diffusivity and mean signal kurtosis.

    References

### `MeanDiffusionKurtosisFit`

class dipy.reconst.msdki.MeanDiffusionKurtosisFit(model, model_params, *, model_S0=None)

  Bases: `object`

  Attributes:
    S0_hat

  Methods

  `msd`() | Mean signal diffusivity (MSD) calculated from the mean signal Diffusion Kurtosis Model.
  `msk`() | Mean signal kurtosis (MSK) calculated from the mean signal Diffusion Kurtosis Model.
  `predict`(gtab, *[, S0]) | Given a mean signal diffusion kurtosis model fit, predict the signal on the vertices of a sphere
  `smt2di`() | Computes the intrinsic diffusivity from the mean signal diffusional kurtosis parameters assuming the 2-compartmental spherical mean technique model.
  `smt2f`() | Computes the axonal water fraction from the mean signal kurtosis assuming the 2-compartmental spherical mean technique model.
  `smt2uFA`() | Computes the microscopic fractional anisotropy from the mean signal diffusional kurtosis parameters assuming the 2-compartmental spherical mean technique model.

  msd()

    Mean signal diffusivity (MSD) calculated from the mean signal Diffusion Kurtosis Model.

    See [2] for further details about the method.

    Returns:
      msd ndarray

        Calculated signal mean diffusivity.

    References

  msk()

    Mean signal kurtosis (MSK) calculated from the mean signal Diffusion Kurtosis Model.

    See [2] for further details about the method.

    Returns:
      msk ndarray

        Calculated signal mean kurtosis.

    References

  predict(gtab, *, S0=1.0)

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

    See [2] for further details about the method.

    Parameters:
      gtab a GradientTable class instance

        This encodes the directions for which a prediction is made

      S0 float array

        The mean non-diffusion weighted signal in each voxel. Default: The fitted S0 value in all voxels if it was fitted. Otherwise 1 in all voxels.

    Returns:
      S(…, N) ndarray

        Simulated mean signal based on the mean signal kurtosis model

    Notes

    The predicted signal is given by: \(MS(b) = S_0 * exp(-bD + 1/6 b^{2} D^{2} K)\), where \(D\) and \(k\) are the mean signal diffusivity and mean signal kurtosis.

    References

  smt2di()

    Computes the intrinsic diffusivity from the mean signal diffusional kurtosis parameters assuming the 2-compartmental spherical mean technique model.

    See [61] and [62] for further details about the method.

    Returns:
      smt2di ndarray

        Intrinsic diffusivity computed by converting MSDKI to SMT2.

    Notes

    Computes the intrinsic diffusivity using equation 16 of [62].

    References

    [61] (1,2,3,4)

    Enrico Kaden, Nathaniel D. Kelm, Robert P. Carson, Mark D. Does, and Daniel C. Alexander. Multi-compartment microscopic diffusion imaging. NeuroImage, 139:346–359, October 2016. URL: https://doi.org/10.1016/j.neuroimage.2016.06.002, doi:10.1016/j.neuroimage.2016.06.002.

    [62] (1,2,3,4,5,6,7,8,9)

    Rafael Neto Henriques, Sune N. Jespersen, and Noam Shemesh. Microscopic anisotropy misestimation in spherical-mean single diffusion encoding MRI. Magnetic Resonance in Medicine, 81(5):3245–3261, 2019. URL: https://doi.org/10.1002/mrm.27606, doi:10.1002/mrm.27606.

  smt2f()

    Computes the axonal water fraction from the mean signal kurtosis assuming the 2-compartmental spherical mean technique model.

    See [61] and [62] for further details about the method.

    Returns:
      ndarray

        Axonal volume fraction calculated from MSK.

    Notes

    Computes the axonal water fraction from the mean signal kurtosis MSK using equation 17 of [62].

    References

  smt2uFA()

    Computes the microscopic fractional anisotropy from the mean signal diffusional kurtosis parameters assuming the 2-compartmental spherical mean technique model.

    See [61] and [62] for further details about the method.

    Returns:
      smt2uFA ndarray

        Microscopic fractional anisotropy computed by converting MSDKI to SMT2.

    Notes

    Computes the intrinsic diffusivity using equation 10 of [62].

    References

### mean_signal_bvalue

dipy.reconst.msdki.mean_signal_bvalue(data, gtab, *, bmag=None)

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

  Parameters:
    data ndarray ([X, Y, Z, …], g)

      ndarray containing the data signals in its last dimension.

    gtab a GradientTable class instance

      The gradient table containing diffusion acquisition parameters.

    bmag The order of magnitude that the bvalues have to differ to be

      considered an unique b-value. Default: derive this value from the maximal b-value provided: \(bmag=log_{10}(max(bvals)) - 1\).

  Returns:
    msignal ndarray ([X, Y, Z, …, nub])

      Mean signal along all gradient directions for each unique b-value Note that the last dimension contains the signal means and nub is the number of unique b-values.

    ng ndarray(nub)

      Number of gradient directions used to compute the mean signal for all unique b-values

  Notes

  This function assumes that directions are evenly sampled on the sphere or on the hemisphere

### msk_from_awf

dipy.reconst.msdki.msk_from_awf(f)

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

  Parameters:
    f ndarray ([X, Y, Z, …])

      ndarray containing the axonal volume fraction estimate.

  Returns:
    msk ndarray(nub)

      Mean signal kurtosis (msk)

  Notes

  Computes mean signal kurtosis using equations 17 of [62].

  References

### awf_from_msk

dipy.reconst.msdki.awf_from_msk(msk, *, mask=None)

  Computes the axonal water fraction from the mean signal kurtosis assuming the 2-compartmental spherical mean technique model.

  See [61] and [62] for further details about the method.

  Parameters:
    msk ndarray ([X, Y, Z, …])

      Mean signal kurtosis (msk)

    mask ndarray, optional

      A boolean array used to mark the coordinates in the data that should be analyzed that has the same shape of the msdki parameters

  Returns:
    awf ndarray ([X, Y, Z, …])

      ndarray containing the axonal volume fraction estimate.

  Notes

  Computes the axonal water fraction from the mean signal kurtosis MSK using equation 17 of [62].

  References

### msdki_prediction

dipy.reconst.msdki.msdki_prediction(msdki_params, gtab, *, S0=1.0)

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

  See [2] for further details about the method.

  Parameters:
    msdki_params ndarray ([X, Y, Z, …], 2)

      Array containing the mean signal diffusivity and mean signal kurtosis in its last axis

    gtab a GradientTable class instance

      The gradient table for this prediction

    S0 float or ndarray, optional

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

  Notes

  The predicted signal is given by:

    \(MS(b) = S_0 * exp(-bD + 1/6 b^{2} D^{2} K)\), where \(D\) and \(K\) are the mean signal diffusivity and mean signal kurtosis.

  References

### wls_fit_msdki

dipy.reconst.msdki.wls_fit_msdki(design_matrix, msignal, ng, *, mask=None, min_signal=0.0001, return_S0_hat=False)

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

  See [2] for further details about the method.

  Parameters:
    design_matrix array (nub, 3)

      Design matrix holding the covariants used to solve for the regression coefficients of the mean signal diffusion kurtosis model. Note that nub is the number of unique b-values

    msignal ndarray ([X, Y, Z, …, nub])

      Mean signal along all gradient directions for each unique b-value Note that the last dimension should contain the signal means and nub is the number of unique b-values.

    ng ndarray(nub)

      Number of gradient directions used to compute the mean signal for all unique b-values

    mask array

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

    min_signal float, optional

      Voxel with mean signal intensities lower than the min positive signal are not processed. Default: 0.0001

    return_S0_hat bool

      If True, also return S0 values for the fit.

  Returns:
    params array (…, 2)

      Containing the mean signal diffusivity and mean signal kurtosis

  References

### design_matrix

dipy.reconst.msdki.design_matrix(ubvals)

  Constructs design matrix for the mean signal diffusion kurtosis model

  Parameters:
    ubvals array

      Containing the unique b-values of the data.

  Returns:
    design_matrix array (nb, 3)

      Design matrix or B matrix for the mean signal diffusion kurtosis model assuming that parameters are in the following order: design_matrix[j, :] = (msd, msk, S0)

### `MultiVoxelFit`

class dipy.reconst.multi_voxel.MultiVoxelFit(model, fit_array, mask)

  Bases: `ReconstFit`

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

  Attributes:
    shape

  Methods

  `predict`(*args, **kwargs) | Predict for the multi-voxel object using each single-object's prediction API, with S0 provided from an array.

  predict(*args, **kwargs)

    Predict for the multi-voxel object using each single-object’s prediction API, with S0 provided from an array.

### `CallableArray`

class dipy.reconst.multi_voxel.CallableArray(shape, dtype=None, buffer=None, offset=0, strides=None, order=None)

  Bases: `ndarray`

  An array which can be called like a function

  Attributes:
    `T`

      View of the transposed array.

    `base`

      Base object if memory is from some other object.

    `ctypes`

      An object to simplify the interaction of the array with the ctypes module.

    `data`

      Python buffer object pointing to the start of the array’s data.

    device
    `dtype`

      Data-type of the array’s elements.

    `flags`

      Information about the memory layout of the array.

    `flat`

      A 1-D iterator over the array.

    `imag`

      The imaginary part of the array.

    `itemsize`

      Length of one array element in bytes.

    `mT`

      View of the matrix transposed array.

    `nbytes`

      Total bytes consumed by the elements of the array.

    `ndim`

      Number of array dimensions.

    `real`

      The real part of the array.

    `shape`

      Tuple of array dimensions.

    `size`

      Number of elements in the array.

    `strides`

      Tuple of bytes to step in each dimension when traversing an array.

  Methods

  `__call__`(*args, **kwargs) | Call self as a function.
  `all`([axis, out, keepdims, where]) | Returns True if all elements evaluate to True.
  `any`([axis, out, keepdims, where]) | Returns True if any of the elements of a evaluate to True.
  `argmax`([axis, out, keepdims]) | Return indices of the maximum values along the given axis.
  `argmin`([axis, out, keepdims]) | Return indices of the minimum values along the given axis.
  `argpartition`(kth[, axis, kind, order]) | Returns the indices that would partition this array.
  `argsort`([axis, kind, order, stable]) | 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`(other, /[, out]) | Refer to `numpy.dot()` for full documentation.
  `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.
  `max`([axis, out, keepdims, initial, where]) | Return the maximum along a given axis.
  `mean`([axis, dtype, out, keepdims, where]) | Returns the average of the array elements along given axis.
  `min`([axis, out, keepdims, initial, where]) | Return the minimum along a given axis.
  `nonzero`() | Return the indices of the elements that are non-zero.
  `partition`(kth[, axis, kind, order]) | Partially sorts the elements in the array in such a way that the value of the element in k-th position is in the position it would be in a sorted array.
  `prod`([axis, dtype, out, keepdims, initial, ...]) | Return the product of the array elements over the given axis
  `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`(a.reshape) | Returns an array containing the same data with a new shape.
  `resize`(a.resize) | 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, respectively.
  `sort`([axis, kind, order, stable]) | Sort an array in-place.
  `squeeze`([axis]) | Remove axes of length one from a.
  `std`([axis, dtype, out, ddof, keepdims, ...]) | Returns the standard deviation of the array elements along given axis.
  `sum`([axis, dtype, out, keepdims, initial, where]) | Return the sum of the array elements over the given axis.
  `swapaxes`(axis1, axis2, /) | Return a view of the array with axis1 and axis2 interchanged.
  `take`(indices[, axis, out, mode]) | Return an array formed from the elements of a at the given indices.
  `to_device`(device, /, *[, stream]) | For Array API compatibility.
  `tobytes`([order]) | Construct Python bytes containing the raw data bytes in the array.
  `tofile`(fid, /[, sep, format]) | Write array to a file as text or binary (default).
  `tolist`() | Return the array as an `a.ndim`-levels deep nested list of Python scalars.
  `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.

### multi_voxel_fit

dipy.reconst.multi_voxel.multi_voxel_fit(_func=None, *, batched=False, shared_obj=None, chunk_size=None)

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

  Supports two calling styles:

      @multi_voxel_fit                   # existing models — unchanged
      @multi_voxel_fit(batched=True)     # batched models (e.g. FORCE)

  When `batched=True` the decorated `fit` method must accept both 1-D (single voxel) and 2-D (batch) input and return a single fit object or a 1-D object array of fit objects respectively.

  Raw-dict protocol — if the model declares a `_fit_class` attribute, the decorator automatically injects `_raw=True` into worker kwargs so that `fit` returns a plain `dict` of numpy arrays instead of Python fit objects. After all chunks are collected, the generic `_assemble_results()` helper is called once in the caller process to build the final fit array via `_fit_class(None, params)`. This avoids serialising Python objects through the Ray object store and is available to any batched model that sets `_fit_class`.

  Parameters:
    _func callable, optional

      When the decorator is used without parentheses (`@multi_voxel_fit`) Python passes the decorated function here directly.

    batched bool, optional

      When True the fit method handles batched 2-D input itself.

    shared_obj tuple of str, optional

      Names of model attributes to place into the Ray object store once and reuse across workers (avoids per-task serialization of large arrays). Example: `("_penalty_array", "_index", "simulations")`. Only active when `engine="ray"`.

    chunk_size int or dict, optional

      Number of voxels per chunk. Accepts either a single `int` (applied to all engines) or a `dict` mapping engine names to chunk sizes, e.g. `{"serial": 10_000, "ray": 100_000}`. Overridden at call time by the `vox_per_chunk` keyword argument. Defaults to 10 000 for the serial-batched path and `n_vox // n_jobs` for parallel engines.

### `OdfModel`

class dipy.reconst.odf.OdfModel(gtab)

  Bases: `ReconstModel`

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

  All odf models should provide a fit method which may take data as it’s first and only argument.

  Methods

  `fit`(data) | To be implemented by specific odf models

  fit(data)

    To be implemented by specific odf models

### `OdfFit`

class dipy.reconst.odf.OdfFit(model, data)

  Bases: `ReconstFit`

  Methods

  `odf`(sphere) | To be implemented but specific odf models

  odf(sphere)

    To be implemented but specific odf models

### gfa

dipy.reconst.odf.gfa(samples)

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

  Parameters:
    samples ndarray

      Values of data on the unit sphere.

  Returns:
    gfa ndarray

      GFA evaluated in each entry of the array, along the last dimension. An np.nan is returned for coordinates that contain all-zeros in samples.

  Notes

  The GFA is defined as [63]:

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

  References

  [63]

  Julien Cohen-Adad, Maxime Descoteaux, and Lawrence L. Wald. Quality assessment of high angular resolution diffusion imaging data using bootstrap on Q-ball reconstruction. Journal of Magnetic Resonance Imaging, 33(5):1194–1208, 2011. URL: https://doi.org/10.1002/jmri.22535, doi:10.1002/jmri.22535.

### minmax_normalize

dipy.reconst.odf.minmax_normalize(samples, *, out=None)

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

  Normalizes samples to `(samples - min(samples)) / (max(samples) - min(samples))` for each unit sphere.

  Parameters:
    samples ndarray (…, N)

      N samples on a unit sphere for each point, stored along the last axis of the array.

    out ndrray (…, N), optional

      An array to store the normalized samples.

  Returns:
    out ndarray, (…, N)

      Normalized samples.

### `QtdmriModel`

class dipy.reconst.qtdmri.QtdmriModel(gtab, *, radial_order=6, time_order=2, laplacian_regularization=False, laplacian_weighting=0.2, l1_regularization=False, l1_weighting=0.1, cartesian=True, anisotropic_scaling=True, normalization=False, constrain_q0=True, bval_threshold=10000000000.0, eigenvalue_threshold=0.0001, cvxpy_solver='CLARABEL')

  Bases: `Cache`

  The q:math:tau-dMRI model to analytically and continuously represent the q:math:tau diffusion signal attenuation over diffusion sensitization q and diffusion time \(\tau\).

  The model [64] can be seen as an extension of the MAP-MRI basis [58] towards different diffusion times.

  The main idea is to model the diffusion signal over time and space as a linear combination of continuous functions,

  \hat{E}(\textbf{q},\tau;\textbf{c}) = \sum_i^{N_{\textbf{q}}}\sum_k^{N_\tau} \textbf{c}_{ik} \,\Phi_i(\textbf{q})\,T_k(\tau)

  where \(\Phi\) and \(T\) are the spatial and temporal basis functions, \(N_{\textbf{q}}\) and \(N_\tau\) are the maximum spatial and temporal order, and \(i,k\) are basis order iterators.

  The estimation of the coefficients \(c_i\) can be regularized using either analytic Laplacian regularization, sparsity regularization using the l1-norm, or both to do a type of elastic net regularization.

  From the coefficients, there exists an analytical formula to estimate the ODF, RTOP, RTAP, RTPP, QIV and MSD, for any diffusion time.

  Parameters:
    gtab GradientTable,

      gradient directions and bvalues container class. The bvalues should be in the normal s/mm^2. big_delta and small_delta need to be given in seconds.

    radial_order unsigned int,

      an even integer representing the spatial/radial order of the basis.

    time_order unsigned int,

      an integer larger or equal than zero representing the time order of the basis.

    laplacian_regularization bool,

      Regularize using the Laplacian of the qt-dMRI basis.

    laplacian_weighting: string or scalar,

      The string ‘GCV’ makes it use generalized cross-validation to find the regularization weight [60]. A scalar sets the regularization weight to that value.

    l1_regularization bool,

      Regularize by imposing sparsity in the coefficients using the l1-norm.

    l1_weighting‘CV’ or scalar,

      The string ‘CV’ makes it use five-fold cross-validation to find the regularization weight. A scalar sets the regularization weight to that value.

    cartesian bool

      Whether to use the Cartesian or spherical implementation of the qt-dMRI basis, which we first explored in [65].

    anisotropic_scaling bool

      Whether to use anisotropic scaling or isotropic scaling. This option can be used to test if the Cartesian implementation is equivalent with the spherical one when using the same scaling.

    normalization bool

      Whether to normalize the basis functions such that their inner product is equal to one. Normalization is only necessary when imposing sparsity in the spherical basis if cartesian=False.

    constrain_q0 bool

      whether to constrain the q0 point to unity along the tau-space. This is necessary to ensure that \(E(0,\tau)=1\).

    bval_threshold float

      the threshold b-value to be used, such that only data points below that threshold are used when estimating the scale factors.

    eigenvalue_threshold float,

      Sets the minimum of the tensor eigenvalues in order to avoid stability problem.

    cvxpy_solver str, optional

      cvxpy solver name. Optionally optimize the positivity constraint with a particular cvxpy solver. See https://www.cvxpy.org/ for details. Default: None (cvxpy chooses its own solver)

  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

  References

  [64] (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22)

  Rutger H. J. Fick, Alexandra Petiet, Mathieu Santin, Anne-Charlotte Philippe, Stephane Lehericy, Rachid Deriche, and Demian Wassermann. Non-parametric graphnet-regularized representation of dMRI in space and time. Medical Image Analysis, 43:37–53, 2018. URL: https://doi.org/10.1016/j.media.2017.09.002, doi:10.1016/j.media.2017.09.002.

  [65]

  Rutger Fick, Demian Wassermann, Marco Pizzolato, and Rachid Deriche. A Unifying Framework for Spatial and Temporal Diffusion in Diffusion MRI. In Sebastien Ourselin, Daniel C. Alexander, Carl-Fredrik Westin, and M. Jorge Cardoso, editors, Information Processing in Medical Imaging, 167–178. Cham, 2015. Springer International Publishing.

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

    Fit method for every voxel in data

### `QtdmriFit`

class dipy.reconst.qtdmri.QtdmriFit(model, qtdmri_coef, us, ut, tau_scaling, R, lopt, alpha, cvxpy_solution_optimal)

  Bases: `object`

  Methods

  `fitted_signal`(*[, gtab]) | Recovers the fitted signal for the given gradient table.
  `msd`(tau) | Calculates the analytical Mean Squared Displacement (MSD) for a given diffusion time tau.
  `norm_of_laplacian_signal`() | Calculates the norm of the laplacian of the fitted signal.
  `odf`(sphere, tau, *[, s]) | Calculates the analytical Orientation Distribution Function (ODF) for a given diffusion time tau from the signal.
  `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.
  `rtap`(tau) | Calculates the analytical return to the axis probability (RTAP) for a given diffusion time tau.
  `rtop`(tau) | Calculates the analytical return to the origin probability (RTOP) for a given diffusion time tau.
  `rtpp`(tau) | Calculates the analytical return to the plane probability (RTPP) for a given diffusion time tau.
  `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

  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 Cheng[56]. The analytical formula for the MAP-MRI basis was derived in [57] eq. (C13, D1). The qtdmri coefficients are first converted to mapmri coefficients following [64].

    Parameters:
      tau float

        diffusion time (big_delta - small_delta / 3.) in seconds

    References

  norm_of_laplacian_signal()

    Calculates the norm of the laplacian of the fitted signal.

    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 Fick et al.[57], the Laplacian now describes oscillations in the 4-dimensional qt-signal [64].

    See [57] for a definition of the metric.

    References

  odf(sphere, tau, *, s=2)

    Calculates the analytical Orientation Distribution Function (ODF) for a given diffusion time tau from the signal.

    See [58] Eq. (32). The qtdmri coefficients are first converted to mapmri coefficients following [64].

    Parameters:
      sphere dipy sphere object

        sphere object with vertice orientations to compute the ODF on.

      tau float

        diffusion time (big_delta - small_delta / 3.) in seconds

      s unsigned int

        radial moment of the ODF

    References

  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 [58] eq. (32). The radial moment s acts as a sharpening method. The analytical equation for the spherical ODF basis is given in [57] eq. (C8). The qtdmri coefficients are first converted to mapmri coefficients following [64].

    Parameters:
      tau float

        diffusion time (big_delta - small_delta / 3.) in seconds

      s unsigned int

        radial moment of the ODF

    References

  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 [59] eq. (22). The analytical formula for the MAP-MRI basis was derived in [57] eq. (C14, D2). The qtdmri coefficients are first converted to mapmri coefficients following Fick et al.[64].

    Parameters:
      tau float

        diffusion time (big_delta - small_delta / 3.) in seconds

    References

  qtdmri_to_mapmri_coef(tau)

    This function converts the qtdmri coefficients to mapmri coefficients for a given tau.

    Defined in [64], 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:
      tau float

        diffusion time (big_delta - small_delta / 3.) in seconds

    References

  rtap(tau)

    Calculates the analytical return to the axis probability (RTAP) for a given diffusion time tau.

    See [58] eq. (40, 44a). The analytical formula for the isotropic MAP-MRI basis was derived in [57] eq. (C11). The qtdmri coefficients are first converted to mapmri coefficients following [64].

    Parameters:
      tau float

        diffusion time (big_delta - small_delta / 3.) in seconds

    References

  rtop(tau)

    Calculates the analytical return to the origin probability (RTOP) for a given diffusion time tau.

    See [58] eq. (36, 43). The analytical formula for the isotropic MAP-MRI basis was derived in [57] eq. (C11). The qtdmri coefficients are first converted to mapmri coefficients following [64].

    Parameters:
      tau float

        diffusion time (big_delta - small_delta / 3.) in seconds

    References

  rtpp(tau)

    Calculates the analytical return to the plane probability (RTPP) for a given diffusion time tau.

    See [58] eq. (42). The analytical formula for the isotropic MAP-MRI basis was derived in [57] eq. (C11). The qtdmri coefficients are first converted to mapmri coefficients following [64].

    Parameters:
      tau float

        diffusion time (big_delta - small_delta / 3.) in seconds

    References

  sparsity_abs(*, threshold=0.99)

    As a measure of sparsity, calculates the number of largest coefficients needed to absolute sum up to 99% of the total absolute sum of all coefficients

  sparsity_density(*, threshold=0.99)

    As a measure of sparsity, calculates the number of largest coefficients needed to squared sum up to 99% of the total squared sum of all coefficients

### qtdmri_to_mapmri_matrix

dipy.reconst.qtdmri.qtdmri_to_mapmri_matrix(radial_order, time_order, ut, tau)

  Generate the matrix that maps the qtdmri coefficients to MAP-MRI coefficients for the anisotropic case.

  The conversion is done by only evaluating the time basis for a diffusion time tau and summing up coefficients with the same spatial basis orders [64].

  Parameters:
    radial_order unsigned int,

      an even integer representing the spatial/radial order of the basis.

    time_order unsigned int,

      an integer larger or equal than zero representing the time order of the basis.

    ut float

      temporal scaling factor

    tau float

      diffusion time (big_delta - small_delta / 3.) in seconds

  References

### qtdmri_isotropic_to_mapmri_matrix

dipy.reconst.qtdmri.qtdmri_isotropic_to_mapmri_matrix(radial_order, time_order, ut, tau)

  Generate the matrix that maps the spherical qtdmri coefficients to MAP-MRI coefficients for the isotropic case.

  The conversion is done by only evaluating the time basis for a diffusion time tau and summing up coefficients with the same spatial basis orders [64].

  Parameters:
    radial_order unsigned int,

      an even integer representing the spatial/radial order of the basis.

    time_order unsigned int,

      an integer larger or equal than zero representing the time order of the basis.

    ut float

      temporal scaling factor

    tau float

      diffusion time (big_delta - small_delta / 3.) in seconds

  References

### qtdmri_temporal_normalization

dipy.reconst.qtdmri.qtdmri_temporal_normalization(ut)

  Normalization factor for the temporal basis

### qtdmri_mapmri_normalization

dipy.reconst.qtdmri.qtdmri_mapmri_normalization(mu)

  Normalization factor for Cartesian MAP-MRI basis. The scaling is the same for every basis function depending only on the spatial scaling mu.

### qtdmri_mapmri_isotropic_normalization

dipy.reconst.qtdmri.qtdmri_mapmri_isotropic_normalization(j, ell, u0)

  Normalization factor for Spherical MAP-MRI basis. The normalization for a basis function with orders [j,l,m] depends only on orders j,l and the isotropic scale factor.

### qtdmri_signal_matrix

dipy.reconst.qtdmri.qtdmri_signal_matrix(radial_order, time_order, us, ut, q, tau)

  Constructs the design matrix as a product of 3 separated radial, angular and temporal design matrices. It precomputes the relevant basis orders for each one and finally puts them together according to the index matrix

### qtdmri_eap_matrix

dipy.reconst.qtdmri.qtdmri_eap_matrix(radial_order, time_order, us, ut, grid)

  Constructs the design matrix as a product of 3 separated radial, angular and temporal design matrices. It precomputes the relevant basis orders for each one and finally puts them together according to the index matrix

### qtdmri_isotropic_signal_matrix

dipy.reconst.qtdmri.qtdmri_isotropic_signal_matrix(radial_order, time_order, us, ut, q, tau)

### qtdmri_isotropic_eap_matrix

dipy.reconst.qtdmri.qtdmri_isotropic_eap_matrix(radial_order, time_order, us, ut, grid)

  Constructs the design matrix as a product of 3 separated radial, angular and temporal design matrices. It precomputes the relevant basis orders for each one and finally puts them together according to the index matrix

### radial_basis_opt

dipy.reconst.qtdmri.radial_basis_opt(j, ell, us, q)

  Spatial basis dependent on spatial scaling factor us

### angular_basis_opt

dipy.reconst.qtdmri.angular_basis_opt(ell, m, q, theta, phi)

  Angular basis independent of spatial scaling factor us. Though it includes q, it is independent of the data and can be precomputed.

### radial_basis_EAP_opt

dipy.reconst.qtdmri.radial_basis_EAP_opt(j, ell, us, r)

### angular_basis_EAP_opt

dipy.reconst.qtdmri.angular_basis_EAP_opt(j, ell, m, r, theta, phi)

### temporal_basis

dipy.reconst.qtdmri.temporal_basis(o, ut, tau)

  Temporal basis dependent on temporal scaling factor ut

### qtdmri_index_matrix

dipy.reconst.qtdmri.qtdmri_index_matrix(radial_order, time_order)

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

### qtdmri_isotropic_index_matrix

dipy.reconst.qtdmri.qtdmri_isotropic_index_matrix(radial_order, time_order)

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

### qtdmri_laplacian_reg_matrix

dipy.reconst.qtdmri.qtdmri_laplacian_reg_matrix(ind_mat, us, ut, *, S_mat=None, T_mat=None, U_mat=None, part1_ut_precomp=None, part23_ut_precomp=None, part4_ut_precomp=None, normalization=False)

  Computes the cartesian qt-dMRI Laplacian regularization matrix.

  If given, uses precomputed matrices for temporal and spatial regularization matrices to speed up computation. Follows the formulation of Appendix B in [64].

  References

### qtdmri_isotropic_laplacian_reg_matrix

dipy.reconst.qtdmri.qtdmri_isotropic_laplacian_reg_matrix(ind_mat, us, ut, *, part1_uq_iso_precomp=None, part1_ut_precomp=None, part23_ut_precomp=None, part4_ut_precomp=None, normalization=False)

  Computes the spherical qt-dMRI Laplacian regularization matrix.

  If given, uses precomputed matrices for temporal and spatial regularization matrices to speed up computation. Follows the formulation of Appendix C in [64].

  References

### part23_reg_matrix_q

dipy.reconst.qtdmri.part23_reg_matrix_q(ind_mat, U_mat, T_mat, us)

  Partial cartesian spatial Laplacian regularization matrix.

  The implementation follows the second line of Eq. (B2) in [64].

  References

### part23_iso_reg_matrix_q

dipy.reconst.qtdmri.part23_iso_reg_matrix_q(ind_mat, us)

  Partial spherical spatial Laplacian regularization matrix.

  The implementation follows the equation below Eq. (C4) in [64].

  References

### part4_reg_matrix_q

dipy.reconst.qtdmri.part4_reg_matrix_q(ind_mat, U_mat, us)

  Partial cartesian spatial Laplacian regularization matrix.

  The implementation follows equation Eq. (B2) in [64].

  References

### part4_iso_reg_matrix_q

dipy.reconst.qtdmri.part4_iso_reg_matrix_q(ind_mat, us)

  Partial spherical spatial Laplacian regularization matrix.

  The implementation follows the equation below Eq. (C4) in [64].

  References

### part1_reg_matrix_tau

dipy.reconst.qtdmri.part1_reg_matrix_tau(ind_mat, ut)

  Partial temporal Laplacian regularization matrix.

  The implementation follows Appendix B in [64].

  References

### part23_reg_matrix_tau

dipy.reconst.qtdmri.part23_reg_matrix_tau(ind_mat, ut)

  Partial temporal Laplacian regularization matrix.

  The implementation follows Appendix B in [64].

  References

### part4_reg_matrix_tau

dipy.reconst.qtdmri.part4_reg_matrix_tau(ind_mat, ut)

  Partial temporal Laplacian regularization matrix.

  The implementation follows Appendix B in [64].

  References

### H

dipy.reconst.qtdmri.H(value)

  Step function of H(x)=1 if x>=0 and zero otherwise. Used for the temporal laplacian matrix.

### generalized_crossvalidation

dipy.reconst.qtdmri.generalized_crossvalidation(data, M, LR, *, startpoint=0.0005)

  Generalized Cross Validation Function.

  See [60] for further details about the method.

  References

### GCV_cost_function

dipy.reconst.qtdmri.GCV_cost_function(weight, arguments)

  Generalized Cross Validation Function that is iterated.

  See [60] for further details about the method.

  References

### qtdmri_isotropic_scaling

dipy.reconst.qtdmri.qtdmri_isotropic_scaling(data, q, tau)

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

### qtdmri_anisotropic_scaling

dipy.reconst.qtdmri.qtdmri_anisotropic_scaling(data, q, bvecs, tau)

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

### design_matrix_spatial

dipy.reconst.qtdmri.design_matrix_spatial(bvecs, qvals)

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

  Parameters:
    bvecs array (N x 3)

      unit b-vectors of the acquisition.

    qvals array (N,)

      corresponding q-values in 1/mm

  Returns:
    design_matrix array (g,7)

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

### create_rt_space_grid

dipy.reconst.qtdmri.create_rt_space_grid(grid_size_r, max_radius_r, grid_size_tau, min_radius_tau, max_radius_tau)

  Generates EAP grid (for potential positivity constraint).

### qtdmri_number_of_coefficients

dipy.reconst.qtdmri.qtdmri_number_of_coefficients(radial_order, time_order)

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

  See equation given below Eq (9) in Fick et al.[64].

  References

### l1_crossvalidation

dipy.reconst.qtdmri.l1_crossvalidation(b0s_mask, E, M, *, weight_array=None)

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

### elastic_crossvalidation

dipy.reconst.qtdmri.elastic_crossvalidation(b0s_mask, E, M, L, lopt, *, weight_array=None)

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

### visualise_gradient_table_G_Delta_rainbow

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:
    gtab GradientTable object

      constructed gradient table with big_delta and small_delta given as inputs.

    big_delta_start float,

      optional minimum big_delta that is plotted in seconds

    big_delta_end float,

      optional maximum big_delta that is plotted in seconds

    G_start float,

      optional minimum gradient strength that is plotted in T/m

    G_end float,

      optional maximum gradient strength that is plotted in T/m

    bval_isolines array,

      optional array of bvalue isolines that are plotted in the background

    alpha_shading float between [0-1]

      optional shading of the bvalue colors in the background

### `QtiModel`

class dipy.reconst.qti.QtiModel(gtab, *, fit_method='WLS', cvxpy_solver='SCS', **kwargs)

  Bases: `ReconstModel`

  Methods

  `fit`(data, *[, mask]) | Fit QTI to data.
  `iterative_fit`(X, data_masked, *[, num_iter, ...]) | Iteratively Reweighted fitting for the QTI model.
  `predict`(params) | Generate signals from this model class instance and given parameters.

  fit(data, *, mask=None)

    Fit QTI to data.

    Parameters:
      data numpy.ndarray

        Array of shape (…, number of acquisitions).

      mask numpy.ndarray, optional

        Array with the same shape as the data array of a single acquisition.

    Returns:
      qtifit dipy.reconst.qti.QtiFit

        The fitted model.

  iterative_fit(X, data_masked, *, num_iter=4, weights_method=<function weights_method_wls_m_est>)

    Iteratively Reweighted fitting for the QTI model.

    Parameters:
      X array (g, 28)

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

      data_masked array (N, g)

        The measured signal, already masked.

      num_iter int, optional

        Number of times to iterate.

      weights_method callable, optional

        A function with args and returns as follows:

        (weights, robust) =
          weights_method(data, pred_sig,

            design_matrix, leverages, idx, num_iter, robust)

    Notes

    On the first iteration, (C)WLS fit is performed. Subsequent iterations will be weighted according to weights_method. Outlier rejection should be handled within weights_method by setting the corresponding weights to zero (if weights_method implements outlier rejection).

  predict(params)

    Generate signals from this model class instance and given parameters.

    Parameters:
      params numpy.ndarray

        Array of shape (…, 28) containing the model parameters. Element 0 is the natural logarithm of the signal without diffusion-weighting, elements 1-6 are the diffusion tensor elements in Voigt notation, and elements 7-27 are the covariance tensor elements in Voigt notation.

    Returns:
      S numpy.ndarray

        Signals.

### `QtiFit`

class dipy.reconst.qti.QtiFit(params)

  Bases: `object`

  Methods

  `S0_hat`() | Estimated signal without diffusion-weighting.
  `c_c`() | Microscopic orientation coherence.
  `c_m`() | Normalized macroscopic anisotropy.
  `c_md`() | Normalized variance of mean diffusivities.
  `c_mu`() | Normalized microscopic anisotropy.
  `d_sq`() | Diffusion tensor's outer product with itself.
  `fa`() | Fractional anisotropy.
  `k_bulk`() | Bulk kurtosis.
  `k_mu`() | Microscopic kurtosis.
  `k_shear`() | Shear kurtosis.
  `md`() | Mean diffusivity.
  `mean_d_sq`() | Average of microscopic diffusion tensors' outer products with themselves.
  `mk`() | Mean kurtosis.
  `predict`(gtab) | Generate signals from this model fit and a given gradient table.
  `ufa`() | Microscopic fractional anisotropy.
  `v_iso`() | Total isotropic variance.
  `v_md`() | Variance of microscopic mean diffusivities.
  `v_shear`() | Shear variance.

  S0_hat()

    Estimated signal without diffusion-weighting.

    Returns:
      S0 numpy.ndarray
  c_c()

    Microscopic orientation coherence.

    Returns:
      c_c numpy.ndarray

    Notes

    Microscopic orientation coherence is calculated as

    > \[C_c = \frac{C_\text{M}}{C_\mu}\]

  c_m()

    Normalized macroscopic anisotropy.

    Returns:
      c_m numpy.ndarray

    Notes

    Normalized macroscopic anisotropy is calculated as

    > \[C_\text{M} = \frac{3}{2} \frac{\langle \mathbf{D} \rangle \otimes \langle \mathbf{D} \rangle : \mathbb{E}_\text{shear}} {\langle \mathbf{D} \rangle \otimes \langle \mathbf{D} \rangle : \mathbb{E}_\text{iso}}\]

  c_md()

    Normalized variance of mean diffusivities.

    Returns:
      c_md numpy.ndarray

    Notes

    Normalized variance of microscopic mean diffusivities is calculated as

    > \[C_\text{MD} = \frac{\mathbb{C} : \mathbb{E}_\text{bulk}} {\langle \mathbf{D} \otimes \mathbf{D} \rangle : \mathbb{E}_\text{bulk}}\]

  c_mu()

    Normalized microscopic anisotropy.

    Returns:
      c_mu numpy.ndarray

    Notes

    Normalized microscopic anisotropy is calculated as

    > \[C_\mu = \frac{3}{2} \frac{\langle \mathbf{D} \otimes \mathbf{D} \rangle : \mathbb{E}_\text{shear}}{\langle \mathbf{D} \otimes \mathbf{D} \rangle : \mathbb{E}_\text{iso}}\]

  d_sq()

    Diffusion tensor’s outer product with itself.

    Returns:
      d_sq numpy.ndarray
  fa()

    Fractional anisotropy.

    Returns:
      fa numpy.ndarray

    Notes

    Fractional anisotropy is calculated as

    > \[\text{FA} = \sqrt{C_\text{M}}\]

  k_bulk()

    Bulk kurtosis.

    Returns:
      k_bulk numpy.ndarray

    Notes

    Bulk kurtosis is calculated as

    > \[K_\text{bulk} = 3 \frac{\mathbb{C} : \mathbb{E}_\text{bulk}} {\langle \mathbf{D} \rangle \otimes \langle \mathbf{D} \rangle : \mathbb{E}_\text{bulk}}\]

  k_mu()

    Microscopic kurtosis.

    Returns:
      k_mu numpy.ndarray

    Notes

    Microscopic kurtosis is calculated as

    > \[K_\mu = \frac{6}{5} \frac{\langle \mathbf{D} \otimes \mathbf{D} \rangle : \mathbb{E}_\text{shear}}{\langle \mathbf{D} \rangle \otimes \langle \mathbf{D} \rangle : \mathbb{E}_\text{bulk}}\]

  k_shear()

    Shear kurtosis.

    Returns:
      k_shear numpy.ndarray

    Notes

    Shear kurtosis is calculated as

    > \[K_\text{shear} = \frac{6}{5} \frac{\mathbb{C} : \mathbb{E}_\text{shear}}{\langle \mathbf{D} \rangle \otimes \langle \mathbf{D} \rangle : \mathbb{E}_\text{bulk}}\]

  md()

    Mean diffusivity.

    Returns:
      md numpy.ndarray

    Notes

    Mean diffusivity is calculated as

    > \[\text{MD} = \langle \mathbf{D} \rangle : \mathbf{E}_\text{iso}\]

  mean_d_sq()

    Average of microscopic diffusion tensors’ outer products with themselves.

    Returns:
      mean_d_sq numpy.ndarray

    Notes

    Average of microscopic diffusion tensors’ outer products with themselves is calculated as

    > \[\langle \mathbf{D} \otimes \mathbf{D} \rangle = \mathbb{C} + \langle \mathbf{D} \rangle \otimes \langle \mathbf{D} \rangle\]

  mk()

    Mean kurtosis.

    Returns:
      mk numpy.ndarray

    Notes

    Mean kurtosis is calculated as

    > \[\text{MK} = K_\text{bulk} + K_\text{shear}\]

  predict(gtab)

    Generate signals from this model fit and a given gradient table.

    Parameters:
      gtab dipy.core.gradients.GradientTable

        Gradient table with b-tensors.

    Returns:
      S numpy.ndarray

        Signals.

  ufa()

    Microscopic fractional anisotropy.

    Returns:
      ufa numpy.ndarray

    Notes

    Microscopic fractional anisotropy is calculated as

    > \[\mu\text{FA} = \sqrt{C_\mu}\]

  v_iso()

    Total isotropic variance.

    Returns:
      v_iso numpy.ndarray

    Notes

    Total isotropic variance is calculated as

    > \[V_\text{iso} = \mathbb{C} : \mathbb{E}_\text{iso}\]

  v_md()

    Variance of microscopic mean diffusivities.

    Returns:
      v_md numpy.ndarray

    Notes

    Variance of microscopic mean diffusivities is calculated as

    > \[V_\text{MD} = \mathbb{C} : \mathbb{E}_\text{bulk}\]

  v_shear()

    Shear variance.

    Returns:
      v_shear numpy.ndarray

    Notes

    Shear variance is calculated as

    > \[V_\text{shear} = \mathbb{C} : \mathbb{E}_\text{shear}\]

### from_3x3_to_6x1

dipy.reconst.qti.from_3x3_to_6x1(T)

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

  Parameters:
    T numpy.ndarray

      An array of size (…, 3, 3).

  Returns:
    V numpy.ndarray

      Converted vectors of size (…, 6, 1).

  Notes

  The conversion of a matrix into a vector is defined as

  > \[\mathbf{V} = \begin{bmatrix} T_{11} & T_{22} & T_{33} & \sqrt{2} T_{23} & \sqrt{2} T_{13} & \sqrt{2} T_{12} \end{bmatrix}^T\]

### from_6x1_to_3x3

dipy.reconst.qti.from_6x1_to_3x3(V)

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

  Parameters:
    V numpy.ndarray

      An array of size (…, 6, 1).

  Returns:
    T numpy.ndarray

      Converted matrices of size (…, 3, 3).

  Notes

  The conversion of a matrix into a vector is defined as

  > \[\mathbf{V} = \begin{bmatrix} T_{11} & T_{22} & T_{33} & \sqrt{2} T_{23} & \sqrt{2} T_{13} & \sqrt{2} T_{12} \end{bmatrix}^T\]

### from_6x6_to_21x1

dipy.reconst.qti.from_6x6_to_21x1(T)

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

  Parameters:
    T numpy.ndarray

      An array of size (…, 6, 6).

  Returns:
    V numpy.ndarray

      Converted vectors of size (…, 21, 1).

  Notes

  The conversion of a matrix into a vector is defined as

  > \[\begin{matrix} \mathbf{V} = & \big[ T_{11} & T_{22} & T_{33} \ & \sqrt{2} T_{23} & \sqrt{2} T_{13} & \sqrt{2} T_{12} \ & \sqrt{2} T_{14} & \sqrt{2} T_{15} & \sqrt{2} T_{16} \ & \sqrt{2} T_{24} & \sqrt{2} T_{25} & \sqrt{2} T_{26} \ & \sqrt{2} T_{34} & \sqrt{2} T_{35} & \sqrt{2} T_{36} \ & T_{44} & T_{55} & T_{66} \ & \sqrt{2} T_{45} & \sqrt{2} T_{56} & \sqrt{2} T_{46} \big]^T \end{matrix}\]

### from_21x1_to_6x6

dipy.reconst.qti.from_21x1_to_6x6(V)

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

  Parameters:
    V numpy.ndarray

      An array of size (…, 21, 1).

  Returns:
    T numpy.ndarray

      Converted matrices of size (…, 6, 6).

  Notes

  The conversion of a matrix into a vector is defined as

  > \[\begin{matrix} \mathbf{V} = & \big[ T_{11} & T_{22} & T_{33} \ & \sqrt{2} T_{23} & \sqrt{2} T_{13} & \sqrt{2} T_{12} \ & \sqrt{2} T_{14} & \sqrt{2} T_{15} & \sqrt{2} T_{16} \ & \sqrt{2} T_{24} & \sqrt{2} T_{25} & \sqrt{2} T_{26} \ & \sqrt{2} T_{34} & \sqrt{2} T_{35} & \sqrt{2} T_{36} \ & T_{44} & T_{55} & T_{66} \ & \sqrt{2} T_{45} & \sqrt{2} T_{56} & \sqrt{2} T_{46} \big]^T \end{matrix}\]

### cvxpy_1x6_to_3x3

dipy.reconst.qti.cvxpy_1x6_to_3x3(V)

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

  Parameters:
    V numpy.ndarray

      An array of size (1, 6).

  Returns:
    T cvxpy.bmat

      Converted matrix of size (3, 3).

  Notes

  The conversion of a matrix into a vector is defined as

  > \[\mathbf{V} = \begin{bmatrix} T_{11} & T_{22} & T_{33} & \sqrt{2} T_{23} & \sqrt{2} T_{13} & \sqrt{2} T_{12} \end{bmatrix}^T\]

### cvxpy_1x21_to_6x6

dipy.reconst.qti.cvxpy_1x21_to_6x6(V)

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

  Parameters:
    V numpy.ndarray

      An array of size (1, 21).

  Returns:
    T cvxpy.bmat

      Converted matrices of size (6, 6).

  Notes

  The conversion of a matrix into a vector is defined as

  > \[\begin{matrix} \mathbf{V} = & \big[ T_{11} & T_{22} & T_{33} \ & \sqrt{2} T_{23} & \sqrt{2} T_{13} & \sqrt{2} T_{12} \ & \sqrt{2} T_{14} & \sqrt{2} T_{15} & \sqrt{2} T_{16} \ & \sqrt{2} T_{24} & \sqrt{2} T_{25} & \sqrt{2} T_{26} \ & \sqrt{2} T_{34} & \sqrt{2} T_{35} & \sqrt{2} T_{36} \ & T_{44} & T_{55} & T_{66} \ & \sqrt{2} T_{45} & \sqrt{2} T_{56} & \sqrt{2} T_{46} \big]^T \end{matrix}\]

### dtd_covariance

dipy.reconst.qti.dtd_covariance(DTD)

  Calculate covariance of a diffusion tensor distribution (DTD).

  Parameters:
    DTD numpy.ndarray

      Diffusion tensor distribution of shape (number of tensors, 3, 3) or (number of tensors, 6, 1).

  Returns:
    C numpy.ndarray

      Covariance tensor of shape (6, 6).

  Notes

  The covariance tensor is calculated according to the following equation and converted into a rank-2 tensor [3]:

  > \[\mathbb{C} = \langle \mathbf{D} \otimes \mathbf{D} \rangle - \langle \mathbf{D} \rangle \otimes \langle \mathbf{D} \rangle\]

  References

### qti_signal

dipy.reconst.qti.qti_signal(gtab, D, C, *, S0=1)

  Generate signals using the covariance tensor signal representation.

  Parameters:
    gtab dipy.core.gradients.GradientTable

      Gradient table with b-tensors.

    D numpy.ndarray

      Diffusion tensors of shape (…, 3, 3), (…, 6, 1), or (…, 6).

    C numpy.ndarray

      Covariance tensors of shape (…, 6, 6), (…, 21, 1), or (…, 21).

    S0 numpy.ndarray, optional

      Signal magnitudes without diffusion-weighting. Must be a single number or an array of same shape as D and C without the last two dimensions.

  Returns:
    S numpy.ndarray

      Simulated signals.

  Notes

  The signal is generated according to

  > \[S = S_0 \exp \left(- \mathbf{b} : \langle \mathbf{D} \rangle + \frac{1}{2}(\mathbf{b} \otimes \mathbf{b}) : \mathbb{C} \right)\]

### design_matrix

dipy.reconst.qti.design_matrix(btens)

  Calculate the design matrix from the b-tensors.

  Parameters:
    btens numpy.ndarray

      An array of b-tensors of shape (number of acquisitions, 3, 3).

  Returns:
    X numpy.ndarray

      Design matrix.

  Notes

  The design matrix is generated according to

  > \[X = \begin{pmatrix} 1 & -\mathbf{b}_1^T & \frac{1}{2}( \mathbf{b}_1 \otimes\mathbf{b}_1)^T \ \vdots & \vdots & \vdots \ 1 & -\mathbf{b}_n^T & \frac{1}{2}(\mathbf{b}_n\otimes \mathbf{b}_n)^T \end{pmatrix}\]

### `RumbaSDModel`

class dipy.reconst.rumba.RumbaSDModel(gtab, *, wm_response=(0.0017, 0.0002, 0.0002), gm_response=0.0008, csf_response=0.003, n_iter=600, recon_type='smf', n_coils=1, R=1, voxelwise=True, use_tv=False, sphere=None, verbose=False)

  Bases: `OdfModel`

  Methods

  `fit`(data, *[, mask]) | Fit fODF and GM/CSF volume fractions.

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

    Fit fODF and GM/CSF volume fractions.

    Parameters:
      data ndarray (x, y, z, N) or ([x, y, z], N)

        Signal values for each voxel. Must be 4D for global fit and 2D for voxelwise fit.

      mask ndarray (x, y, z), optional

        Binary mask specifying voxels of interest with 1; results will only be fit at these voxels (0 elsewhere). If None, fits all voxels. Default: None.

    Returns:
      model_fit RumbaFit

        Fit object storing model parameters.

### `RumbaFit`

class dipy.reconst.rumba.RumbaFit(model, model_params)

  Bases: `OdfFit`

  Methods

  `combined_odf_iso`() | Constructs fODF combined with isotropic volume fraction at discrete vertices on model sphere.
  `f_csf`() | Constructs CSF volume fraction for each voxel.
  `f_gm`() | Constructs GM volume fraction for each voxel.
  `f_iso`() | Constructs isotropic volume fraction for each voxel.
  `f_wm`() | Constructs white matter volume fraction for each voxel.
  `odf`(*[, sphere]) | Constructs fODF at discrete vertices on model sphere for each voxel.
  `predict`(*[, gtab, S0]) | Compute signal prediction on model gradient table given given fODF and GM/CSF volume fractions for each voxel.

  combined_odf_iso()

    Constructs fODF combined with isotropic volume fraction at discrete vertices on model sphere.

    Distributes isotropic compartments evenly along each fODF direction. Sums to 1.

    Returns:
      combined ndarray ([x, y, z], M-2)

        fODF combined with isotropic volume fraction.

  f_csf()

    Constructs CSF volume fraction for each voxel.

    Returns:
      f_csf ndarray ([x, y, z])

        CSF volume fraction.

  f_gm()

    Constructs GM volume fraction for each voxel.

    Returns:
      f_gm ndarray ([x, y, z])

        GM volume fraction.

  f_iso()

    Constructs isotropic volume fraction for each voxel.

    Equivalent to sum of GM and CSF volume fractions.

    Returns:
      f_iso ndarray ([x, y, z])

        Isotropic volume fraction.

  f_wm()

    Constructs white matter volume fraction for each voxel.

    Equivalent to sum of fODF.

    Returns:
      f_wm ndarray ([x, y, z])

        White matter volume fraction.

  odf(*, sphere=None)

    Constructs fODF at discrete vertices on model sphere for each voxel.

    Parameters:
      sphere Sphere, optional

        Sphere on which to construct fODF. If specified, must be the same sphere used by the RumbaSDModel model. Default: None.

    Returns:
      odf ndarray ([x, y, z], M-2)

        fODF computed at each vertex on model sphere.

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

    Compute signal prediction on model gradient table given given fODF and GM/CSF volume fractions for each voxel.

    Parameters:
      gtab GradientTable, optional

        The gradients for which the signal will be predicted. Use the model’s gradient table if None. Default: None

      S0 ndarray ([x, y, z]) or float, optional

        The non diffusion-weighted signal value for each voxel. If a float, the same value is used for each voxel. If None, 1 is used for each voxel. Default: None

    Returns:
      pred_sig ndarray ([x, y, z], N)

        The predicted signal.

### rumba_deconv

dipy.reconst.rumba.rumba_deconv(data, kernel, *, n_iter=600, recon_type='smf', n_coils=1)

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

  Deconvolves the kernel from the diffusion-weighted signal by computing a maximum likelihood estimation of the fODF [66]. Minimizes the negative log-likelihood of the data under Rician or Noncentral Chi noise distributions by adapting the iterative technique developed in Richardson-Lucy deconvolution.

  Parameters:
    data 1d ndarray (N,)

      Signal values for a single voxel.

    kernel 2d ndarray (N, M)

      Deconvolution kernel mapping volume fractions of the M compartments to N-length signal. Last two columns should be for GM and CSF.

    n_iter int, optional

      Number of iterations for fODF estimation. Must be a positive int. Default: 600

    recon_type{‘smf’, ‘sos’}, optional

      MRI reconstruction method: spatial matched filter (SMF) or sum-of-squares (SoS). SMF reconstruction generates Rician noise while SoS reconstruction generates Noncentral Chi noise. Default: ‘smf’

    n_coils int, optional

      Number of coils in MRI scanner – only relevant in SoS reconstruction. Must be a positive int. Default: 1

  Returns:
    fit_vec 1d ndarray (M,)

      Vector containing fODF and GM/CSF volume fractions. First M-2 components are fODF while last two are GM and CSF respectively.

  Notes

  The diffusion MRI signal measured at a given voxel is a sum of contributions from each intra-voxel compartment, including parallel white matter (WM) fiber populations in a given orientation as well as effects from GM and CSF. The equation governing these contributions is:

  \(S_i = S_0\left(\sum_{j=1}^{M}f_j\exp(-b_i\textbf{v}_i^T\textbf{D}_j \textbf{v}_i) + f_{GM}\exp(-b_iD_{GM})+f_{CSF}\exp(-b_iD_{CSF})\right)\)

  Where \(S_i\) is the resultant signal along the diffusion-sensitizing gradient unit vector \(\textbf{v_i}; i = 1, ..., N\) with a b-value of \(b_i\). \(f_j; j = 1, ..., M\) is the volume fraction of the \(j^{th}\) fiber population with an anisotropic diffusion tensor \(\textbf{D_j}\).

  \(f_{GM}\) and \(f_{CSF}\) are the volume fractions and \(D_{GM}\) and \(D_{CSF}\) are the mean diffusivities of GM and CSF respectively.

  This equation is linear in \(f_j, f_{GM}, f_{CSF}\) and can be simplified to a single matrix multiplication:

  \(\textbf{S} = \textbf{Hf}\)

  Where \(\textbf{S}\) is the signal vector at a certain voxel, \(\textbf{H}\) is the deconvolution kernel, and \(\textbf{f}\) is the vector of volume fractions for each compartment.

  Modern MRI scanners produce noise following a Rician or Noncentral Chi distribution, depending on their signal reconstruction technique footcite:p:`Constantinides1997. Using this linear model, it can be shown that the likelihood of a signal under a Noncentral Chi noise model is:

  \(P(\textbf{S}|\textbf{H}, \textbf{f}, \sigma^2, n) = \prod_{i=1}^{N}\left( \frac{S_i}{\bar{S_i}}\right)^n\exp\left\{-\frac{1}{2\sigma^2}\left[ S_i^2 + \bar{S}_i^2\right]\right\}I_{n-1}\left(\frac{S_i\bar{S}_i} {\sigma^2}\right)u(S_i)\)

  Where \(S_i\) and \(\bar{S}_i = \textbf{Hf}\) are the measured and expected signals respectively, and \(n\) is the number of coils in the scanner, and \(I_{n-1}\) is the modified Bessel function of first kind of order \(n-1\). This gives the likelihood under a Rician distribution when \(n\) is set to 1.

  By taking the negative log of this with respect to \(\textbf{f}\) and setting the derivative to 0, the \(\textbf{f}\) maximizing likelihood is found to be:

  \(\textbf{f} = \textbf{f} \circ \frac{\textbf{H}^T\left[\textbf{S}\circ \frac{I_n(\textbf{S}\circ \textbf{Hf}/\sigma^2)} {I_{n-1}(\textbf{S} \circ\textbf{Hf}\sigma^2)} \right ]} {\textbf{H}^T\textbf{Hf}}\)

  The solution can be found using an iterative scheme, just as in the Richardson-Lucy algorithm:

  \(\textbf{f}^{k+1} = \textbf{f}^k \circ \frac{\textbf{H}^T\left[\textbf{S} \circ\frac{I_n(\textbf{S}\circ\textbf{Hf}^k/\sigma^2)} {I_{n-1}(\textbf{S} \circ\textbf{Hf}^k/\sigma^2)} \right ]} {\textbf{H}^T\textbf{Hf}^k}\)

  In order to apply this, a reasonable estimate of \(\sigma^2\) is required. To find this, a separate iterative scheme is found using the derivative of the negative log with respect to \(\sigma^2\), and is run in parallel. This is shown here:

  \(\alpha^{k+1} = \frac{1}{nN}\left\{ \frac{\textbf{S}^T\textbf{S} + \textbf{f}^T\textbf{H}^T\textbf{Hf}}{2} - \textbf{1}^T_N\left[(\textbf{S} \circ\textbf{Hf})\circ\frac{I_n(\textbf{S}\circ\textbf{Hf}/\alpha^k)} {I_{n-1}(\textbf{S}\circ\textbf{Hf}/\alpha^k)} \right ]\right \}\)

  For more details, see [66].

  References

  [66] (1,2,3)

  Erick J. Canales-Rodríguez, Alessandro Daducci, Stamatios N. Sotiropoulos, Emmanuel Caruyer, Santiago Aja-Fernández, Joaquim Radua, Jesús M. Yurramendi Mendizabal, Yasser Iturria-Medina, Lester Melie-García, Yasser Alemán-Gómez, Jean-Philippe Thiran, Salvador Sarró, Edith Pomarol-Clotet, and Raymond Salvador. Spherical Deconvolution of Multichannel Diffusion MRI Data with Non-Gaussian Noise Models and Spatial Regularization. PLOS ONE, 10(10):e0138910, 2015. URL: https://doi.org/10.1371/journal.pone.0138910, doi:10.1371/journal.pone.0138910.

### mbessel_ratio

dipy.reconst.rumba.mbessel_ratio(n, x)

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

  Computes:

  \(I_{n}(x) / I_{n-1}(x)\)

  using Perron’s continued fraction equation where \(I_n\) is the modified Bessel function of first kind, order \(n\) [67].

  Parameters:
    n int

      Order of Bessel function in numerator (denominator is of order n-1). Must be a positive int.

    x float or ndarray

      Value or array of values with which to compute ratio.

  Returns:
    y float or ndarray

      Result of ratio computation.

  References

  [67]

  Walter Gautschi and Josef Slavik. On the computation of modified Bessel function ratios. Mathematics of Computation, 32(143):865–875, 1978. doi:10.1090/S0025-5718-1978-0470267-9.

### generate_kernel

dipy.reconst.rumba.generate_kernel(gtab, sphere, wm_response, gm_response, csf_response)

  Generate deconvolution kernel

  Compute kernel mapping orientation densities of white matter fiber populations (along each vertex of the sphere) and isotropic volume fractions to a diffusion weighted signal.

  Parameters:
    gtab GradientTable

      Gradient table.

    sphere Sphere

      Sphere with which to sample discrete fiber orientations in order to construct kernel

    wm_response 1d ndarray or 2d ndarray or AxSymShResponse, optional

      Tensor eigenvalues as a (3,) ndarray, multishell eigenvalues as a (len(unique_bvals_tolerance(gtab.bvals))-1, 3) ndarray in order of smallest to largest b-value, or an AxSymShResponse.

    gm_response float, optional

      Mean diffusivity for GM compartment. If None, then grey matter compartment set to all zeros.

    csf_response float, optional

      Mean diffusivity for CSF compartment. If None, then CSF compartment set to all zeros.

  Returns:
    kernel 2d ndarray (N, M)

      Computed kernel; can be multiplied with a vector consisting of volume fractions for each of M-2 fiber populations as well as GM and CSF fractions to produce a diffusion weighted signal.

### rumba_deconv_global

dipy.reconst.rumba.rumba_deconv_global(data, kernel, mask, *, n_iter=600, recon_type='smf', n_coils=1, R=1, use_tv=True, verbose=False)

  Fit fODF for all voxels simultaneously using RUMBA-SD.

  Deconvolves the kernel from the diffusion-weighted signal at each voxel by computing a maximum likelihood estimation of the fODF [66]. Global fitting also permits the use of total variation regularization (RUMBA-SD + TV). The spatial dependence introduced by TV promotes smoother solutions (i.e. prevents oscillations), while still allowing for sharp discontinuities [68]. This promotes smoothness and continuity along individual tracts while preventing smoothing of adjacent tracts.

  Generally, global_fit will proceed more quickly than the voxelwise fit provided that the computer has adequate RAM (>= 16 GB should be more than sufficient).

  Parameters:
    data 4d ndarray (x, y, z, N)

      Signal values for entire brain. None of the volume dimensions x, y, z can be 1 if TV regularization is required.

    kernel 2d ndarray (N, M)

      Deconvolution kernel mapping volume fractions of the M compartments to N-length signal. Last two columns should be for GM and CSF.

    mask 3d ndarray(x, y, z)

      Binary mask specifying voxels of interest with 1; fODF will only be fit at these voxels (0 elsewhere).

    n_iter int, optional

      Number of iterations for fODF estimation. Must be a positive int.

    recon_type{‘smf’, ‘sos’}, optional

      MRI reconstruction method: spatial matched filter (SMF) or sum-of-squares (SoS). SMF reconstruction generates Rician noise while SoS reconstruction generates Noncentral Chi noise.

    n_coils int, optional

      Number of coils in MRI scanner – only relevant in SoS reconstruction. Must be a positive int.

    use_tv bool, optional

      If true, applies total variation regularization. This requires a brain volume with no singleton dimensions.

    verbose bool, optional

      If true, logs updates on estimated signal-to-noise ratio after each iteration.

  Returns:
    fit_array 4d ndarray (x, y, z, M)

      fODF and GM/CSF volume fractions computed for each voxel. First M-2 components are fODF, while last two are GM and CSf respectively.

  Notes

  TV modifies our cost function as follows:

  \[\]

  J(textbf{f}) = -log{P(textbf{S}|textbf{H}, textbf{f}, sigma^2, n)})+ alpha_{TV}TV(textbf{f})

  where the first term is the negative log likelihood described in the notes of rumba_deconv, and the second term is the TV energy, or the sum of gradient absolute values for the fODF across the entire brain. This results in a new multiplicative factor in the iterative scheme, now becoming:

  \[\]

  textbf{f}^{k+1} = textbf{f}^k circ frac{textbf{H}^Tleft[textbf{S} circfrac{I_n(textbf{S}circtextbf{Hf}^k/sigma^2)} {I_{n-1}(textbf{S} circtextbf{Hf}^k/sigma^2)} right ]} {textbf{H}^Ttextbf{Hf}^k}circ textbf{R}^k

  where \(\textbf{R}^k\) is computed voxelwise by:

  \[\]

  (textbf{R}^k)_j = frac{1}{1 - alpha_{TV}divleft(frac{triangledown[ textbf{f}^k_{3D}]_j}{lverttriangledown[textbf{f}^k_{3D}]_j rvert} right)biggrrvert_{x, y, z}}

  Here, \(\triangledown\) is the symbol for the 3D gradient at any voxel.

  The regularization strength, \(\alpha_{TV}\) is updated after each iteration by the discrepancy principle – specifically, it is selected to match the estimated variance after each iteration [69].

  References

  [68]

  Leonid I. Rudin, Stanley Osher, and Emad Fatemi. Nonlinear total variation based noise removal algorithms. Physica D: Nonlinear Phenomena, 60(1):259–268, 1992. URL: https://doi.org/10.1016/0167-2789(92)90242-F, doi:10.1016/0167-2789(92)90242-F.

  [69]

  Antonin Chambolle. An Algorithm for Total Variation Minimization and Applications. Journal of Mathematical Imaging and Vision, 20(1):89–97, 2004. URL: https://doi.org/10.1023/B:JMIV.0000011325.36760.1e, doi:10.1023/B:JMIV.0000011325.36760.1e.

### `IsotropicModel`

class dipy.reconst.sfm.IsotropicModel(gtab)

  Bases: `ReconstModel`

  A base-class for the representation of isotropic signals.

  The default behavior, suitable for single b-value data is to calculate the mean in each voxel as an estimate of the signal that does not depend on direction.

  Methods

  `fit`(data, *[, mask]) | Fit an IsotropicModel.

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

    Fit an IsotropicModel.

    This boils down to finding the mean diffusion-weighted signal in each voxel

    Parameters:
      data ndarray
    Returns:
      IsotropicFit class instance.

### `IsotropicFit`

class dipy.reconst.sfm.IsotropicFit(model, params)

  Bases: `ReconstFit`

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

  Methods

  `predict`(*[, gtab]) | Predict the isotropic signal.

  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:
      gtab a GradientTable class instance, optional

        Defaults to use the gtab from the IsotropicModel from which this fit was derived.

### `ExponentialIsotropicModel`

class dipy.reconst.sfm.ExponentialIsotropicModel(gtab)

  Bases: `IsotropicModel`

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

  Methods

  `fit`(data, *[, mask]) |

  fit(data, *, mask=None, **kwargs)
    Parameters:
      data ndarray
      mask array, optional

        A boolean array used to mark the coordinates in the data that should be analyzed. Has the shape data.shape[:-1]. Default: None, which implies that all points should be analyzed.

    Returns:
      ExponentialIsotropicFit class instance.

### `ExponentialIsotropicFit`

class dipy.reconst.sfm.ExponentialIsotropicFit(model, params)

  Bases: `IsotropicFit`

  A fit to the ExponentialIsotropicModel object, based on data.

  Methods

  `predict`(*[, gtab]) | Predict the isotropic signal, based on a gradient table.

  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:
      gtab a GradientTable class instance, optional

        Defaults to use the gtab from the IsotropicModel from which this fit was derived.

### `SparseFascicleModel`

class dipy.reconst.sfm.SparseFascicleModel(gtab, *, sphere=None, response=(0.0015, 0.0005, 0.0005), solver='ElasticNet', l1_ratio=0.5, alpha=0.001, isotropic=None, seed=42)

  Bases: `ReconstModel`, `Cache`

  Methods

  `cache_clear`() | Clear the cache.
  `cache_get`(tag, key, *[, default]) | Retrieve a value from the cache.
  `cache_set`(tag, key, value) | Store a value in the cache.
  `design_matrix`() | The design matrix for a SFM.
  `fit`(data, *[, mask, num_processes, ...]) | Fit the SparseFascicleModel object to data.

  design_matrix()

    The design matrix for a SFM.

    Returns:
      ndarray

        The design matrix, where each column is a rotated version of the response function.

  fit(data, *, mask=None, num_processes=1, parallel_backend='multiprocessing')

    Fit the SparseFascicleModel object to data.

    Parameters:
      data array

        The measured signal.

      mask array, optional

        A boolean array used to mark the coordinates in the data that should be analyzed. Has the shape data.shape[:-1]. Default: None, which implies that all points should be analyzed.

      num_processes int, optional

        Split the fit calculation to a pool of children processes using joblib. This only applies to 4D data arrays. Default is 1, which does not require joblib and will run fit serially. If < 0 the maximal number of cores minus `num_processes + 1` is used (enter -1 to use as many cores as possible). 0 raises an error.

      parallel_backend: str, ParallelBackendBase instance or None

        Specify the parallelization backend implementation. Supported backends are:

        - “loky” used by default, can induce some communication and memory overhead when exchanging input and output data with the worker Python processes.

        - “multiprocessing” previous process-based backend based on multiprocessing.Pool. Less robust than loky.

        - “threading” is a very low-overhead backend but it suffers from the Python Global Interpreter Lock if the called function relies a lot on Python objects. “threading” is mostly useful when the execution bottleneck is a compiled extension that explicitly releases the GIL (for instance a Cython loop wrapped in a “with nogil” block or an expensive call to a library such as NumPy).

    Returns:
      SparseFascicleFit object

### `SparseFascicleFit`

class dipy.reconst.sfm.SparseFascicleFit(model, beta, S0, iso)

  Bases: `ReconstFit`

  Methods

  `odf`(sphere) | The orientation distribution function of the SFM
  `predict`(*[, gtab, response, S0]) | Predict the signal based on the SFM parameters

  odf(sphere)

    The orientation distribution function of the SFM

    Parameters:
      sphere Sphere

        The points in which the ODF is evaluated

    Returns:
      odf ndarray of shape (x, y, z, sphere.vertices.shape[0])
  predict(*, gtab=None, response=None, S0=None)

    Predict the signal based on the SFM parameters

    Parameters:
      gtab GradientTable, optional

        The bvecs/bvals to predict the signal on. Default: the gtab from the model object.

      response list of 3 elements, optional

        The eigenvalues of a tensor which will serve as a kernel function. Default: the response of the model object. Default to use model.response.

      S0 float or array, optional

        The non-diffusion-weighted signal. Default: use the S0 of the data

    Returns:
      pred_sig ndarray

        The signal predicted in each voxel/direction

### sfm_design_matrix

dipy.reconst.sfm.sfm_design_matrix(gtab, sphere, response, *, mode='signal')

  Construct the SFM design matrix

  Parameters:
    gtab GradientTable or Sphere

      Sets the rows of the matrix, if the mode is ‘signal’, this should be a GradientTable. If mode is ‘odf’ this should be a Sphere.

    sphere Sphere

      Sets the columns of the matrix

    response list of 3 elements

      The eigenvalues of a tensor which will serve as a kernel function.

    mode str {‘signal’ | ‘odf’}, optional

      Choose the (default) ‘signal’ for a design matrix containing predicted signal in the measurements defined by the gradient table for putative fascicles oriented along the vertices of the sphere. Otherwise, choose ‘odf’ for an odf convolution matrix, with values of the odf calculated from a tensor with the provided response eigenvalues, evaluated at the b-vectors in the gradient table, for the tensors with principal diffusion directions along the vertices of the sphere.

  Returns:
    mat ndarray

      A design matrix that can be used for one of the following operations: when the ‘signal’ mode is used, each column contains the putative signal in each of the bvectors of the gtab if a fascicle is oriented in the direction encoded by the sphere vertex corresponding to this column. This is used for deconvolution with a measured DWI signal. If the ‘odf’ mode is chosen, each column instead contains the values of the tensor ODF for a tensor with a principal diffusion direction corresponding to this vertex. This is used to generate odfs from the fits of the SFM for the purpose of tracking.

  References

  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 :footcite:p`Rokem2014`:

      >>> tensor_matrix = sfm_design_matrix(gtab, sphere,
      ...                                   [0.0015, 0.0005, 0.0005])

  A ‘stick’ function :footcite:p`Behrens2007`:

      >>> stick_matrix = sfm_design_matrix(gtab, sphere, [0.001, 0, 0])

### `SphHarmModel`

class dipy.reconst.shm.SphHarmModel(gtab)

  Bases: `OdfModel`, `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.

  sampling_matrix(sphere)

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

    Parameters:
      sphere Sphere

        Points used to sample ODF.

    Returns:
      sampling_matrix array

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

### `QballBaseModel`

class dipy.reconst.shm.QballBaseModel(gtab, sh_order_max, *, smooth=0.006, min_signal=1e-05, assume_normed=False)

  Bases: `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.

  fit(data, *, mask=None)

    Fits the model to diffusion data and returns the model fit

### `SphHarmFit`

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

  Bases: `OdfFit`

  Diffusion data fit to a spherical harmonic model

  Attributes:
    shape
    `shm_coeff`

      The spherical harmonic coefficients of the odf

  Methods

  `odf`(sphere) | Samples the odf function on the points of a sphere
  `predict`(*[, gtab, S0]) | Predict the diffusion signal from the model coefficients.

  gfa |

  odf(sphere)

    Samples the odf function on the points of a sphere

    Parameters:
      sphere Sphere

        The points on which to sample the odf.

    Returns:
      values ndarray

        The value of the odf on each point of sphere.

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

    Predict the diffusion signal from the model coefficients.

    Parameters:
      gtab a GradientTable class instance

        The directions and bvalues on which prediction is desired

      S0 float array

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

  property shm_coeff

    The spherical harmonic coefficients of the odf

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

### `CsaOdfModel`

class dipy.reconst.shm.CsaOdfModel(gtab, sh_order_max, *, smooth=0.006, min_signal=1e-05, assume_normed=False)

  Bases: `QballBaseModel`

  Implementation of Constant Solid Angle reconstruction method.

  See [6] for further details about the method.

  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.

  References

### `OpdtModel`

class dipy.reconst.shm.OpdtModel(gtab, sh_order_max, *, smooth=0.006, min_signal=1e-05, assume_normed=False)

  Bases: `QballBaseModel`

  Implementation of Orientation Probability Density Transform reconstruction method.

  See [8] and [9] for further details about the method.

  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.

  References

### `QballModel`

class dipy.reconst.shm.QballModel(gtab, sh_order_max, *, smooth=0.006, min_signal=1e-05, assume_normed=False)

  Bases: `QballBaseModel`

  Implementation of regularized Qball reconstruction method.

  See [7] for further details about the method.

  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.

  References

### `ResidualBootstrapWrapper`

class dipy.reconst.shm.ResidualBootstrapWrapper(signal_object, B, where_dwi, *, min_signal=1e-05)

  Bases: `object`

  Returns a residual bootstrap sample of the signal_object when indexed

  Wraps a signal_object, this signal object can be an interpolator. When indexed, the wrapper indexes the signal_object to get the signal. There wrapper than samples the residual bootstrap distribution of signal and returns that sample.

### forward_sdeconv_mat

dipy.reconst.shm.forward_sdeconv_mat(r_rh, l_values)

  Build forward spherical deconvolution matrix

  Parameters:
    r_rh ndarray

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

    l_values ndarray

      The orders (\(l\)) of spherical harmonic function associated with each row of the deconvolution matrix. Only even orders are allowed

  Returns:
    R ndarray (N, N)

      Deconvolution matrix with shape (N, N)

### sh_to_rh

dipy.reconst.shm.sh_to_rh(r_sh, m_values, l_values)

  Spherical harmonics (SH) to rotational harmonics (RH)

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

  See [13] for further details about the method.

  Parameters:
    r_sh ndarray (N,)

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

    m_values ndarray (N,)

      The phase factors (\(m\)) of the spherical harmonic function associated with each coefficient.

    l_values ndarray (N,)

      The orders (\(l\)) of the spherical harmonic function associated with each coefficient.

  Returns:
    r_rh ndarray (`(sh_order + 1)*(sh_order + 2)/2`,)

      Rotational harmonics coefficients representing the input r_sh

  See also

  `shm.real_sh_descoteaux_from_index`, `shm.real_sh_descoteaux`

  References

### gen_dirac

dipy.reconst.shm.gen_dirac(m_values, l_values, theta, phi, *, legacy=True)

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

  The spherical harmonics (SH) representation of this Dirac is returned as coefficients to spherical harmonic functions produced from `descoteaux07` basis.

  Parameters:
    m_values ndarray (N,)

      The phase factors of the spherical harmonic function associated with each coefficient.

    l_values ndarray (N,)

      The order (\(l\)) of the spherical harmonic function associated with each coefficient.

    theta float [0, pi]

      The polar (colatitudinal) coordinate.

    phi float [0, 2*pi]

      The azimuthal (longitudinal) coordinate.

    legacy: bool, optional

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

  Returns:
    dirac ndarray

      SH coefficients representing the Dirac function. The shape of this is (m + 2) * (m + 1) / 2.

  See also

  `shm.real_sh_descoteaux_from_index`, `shm.real_sh_descoteaux`

### spherical_harmonics

dipy.reconst.shm.spherical_harmonics(m_values, l_values, theta, phi, *, use_scipy=True)

  Compute spherical harmonics.

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

  Parameters:
    m_values array of int `|m| <= l`

      The phase factors (\(m\)) of the harmonics.

    l_values array of int `l >= 0`

      The orders (\(l\)) of the harmonics.

    theta float [0, 2*pi]

      The azimuthal (longitudinal) coordinate.

    phi float [0, pi]

      The polar (colatitudinal) coordinate.

    use_scipy bool, optional

      If True, use scipy implementation.

  Returns:
    y_mn complex float

      The harmonic \(Y_l^m\) sampled at `theta` and `phi`.

  Notes

  This is a faster implementation of scipy.special.sph_harm for scipy version < 0.15.0. For scipy 0.15 and onwards, we use the scipy implementation of the function.

  The usual definitions for `theta` and `phi` used in DIPY are interchanged in the method definition to agree with the definitions in scipy.special.sph_harm, where theta represents the azimuthal coordinate and phi represents the polar coordinate.

  Although scipy uses a naming convention where `m` is the order and `n` is the degree of the SH, the opposite of DIPY’s, their definition for both parameters is the same as ours, with `l >= 0` and `|m| <= l`.

### real_sph_harm

dipy.reconst.shm.real_sph_harm(m_values, l_values, theta, phi)

  Compute real spherical harmonics.

  dipy.reconst.shm.real_sph_harm is deprecated, Please use dipy.reconst.shm.real_sh_descoteaux_from_index instead

  - deprecated from version: 1.3

  - Will raise <class ‘dipy.utils.deprecator.ExpiredDeprecationError’> as of version: 2.0

  Where the real harmonic \(Y_l^m\) is defined to be:

  Y_l^m = \begin{cases} \sqrt{2} * \Im(Y_l^m) \; if m > 0 \\ Y^0_l \; if m = 0 \\ \sqrt{2} * \Re(Y_l^{|m|}) \; if m < 0 \\ \end{cases}

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

  Parameters:
    m_values array of int `|m| <= l`

      The phase factors (\(m\)) of the harmonics.

    l_values array of int `l >= 0`

      The orders (\(l\)) of the harmonics.

    theta float [0, pi]

      The polar (colatitudinal) coordinate.

    phi float [0, 2*pi]

      The azimuthal (longitudinal) coordinate.

  Returns:
    y_mn real float

      The real harmonic \(Y_l^m\) sampled at theta and phi.

  See also

  `scipy.special.sph_harm`

### real_sh_tournier_from_index

dipy.reconst.shm.real_sh_tournier_from_index(m_values, l_values, theta, phi, *, legacy=True)

  Compute real spherical harmonics.

  The SH are computed as initially defined in [13] then updated in MRtrix3 [70], where the real harmonic \(Y_l^m\) is defined to be:

  Y_l^m = \begin{cases} \sqrt{2} * \Re(Y_l^m) \; if m > 0 \\ Y^0_l \; if m = 0 \\ \sqrt{2} * \Im(Y_l^{|m|}) \; if m < 0 \\ \end{cases}

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

  Parameters:
    m_values array of int `|m| <= l`

      The phase factors (\(m\)) of the harmonics.

    l_values array of int `l >= 0`

      The orders (\(l\)) of the harmonics.

    theta float [0, pi]

      The polar (colatitudinal) coordinate.

    phi float [0, 2*pi]

      The azimuthal (longitudinal) coordinate.

    legacy: bool, optional

      If true, uses MRtrix 0.2 SH basis definition, where the `sqrt(2)` factor is omitted. Else, uses the MRtrix 3 definition presented above.

  Returns:
    real_sh real float

      The real harmonics \(Y_l^m\) sampled at `theta` and `phi`.

  References

  [70] (1,2,3,4,5,6,7,8,9,10)

  Jacques-Donald Tournier, Robert Smith, David Raffelt, Rami Tabbara, Thijs Dhollander, Maximilian Pietsch, Daan Christiaens, Ben Jeurissen, Chun-Hung Yeh, and Alan Connelly. MRtrix3: A fast, flexible and open software framework for medical image processing and visualisation. NeuroImage, 202:116137, November 2019. URL: https://doi.org/10.1016/j.neuroimage.2019.116137, doi:10.1016/j.neuroimage.2019.116137.

### real_sh_descoteaux_from_index

dipy.reconst.shm.real_sh_descoteaux_from_index(m_values, l_values, theta, phi, *, legacy=True)

  Compute real spherical harmonics.

  The definition adopted here follows [7], where the real harmonic \(Y_l^m\) is defined to be:

  Y_l^m = \begin{cases} \sqrt{2} * \Im(Y_l^m) \; if m > 0 \\ Y^0_l \; if m = 0 \\ \sqrt{2} * \Re(Y_l^m) \; if m < 0 \\ \end{cases}

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

  Parameters:
    m_values array of int `|m| <= l`

      The phase factors (\(m\)) of the harmonics.

    l_values array of int `l >= 0`

      The orders (\(l\)) of the harmonics.

    theta float [0, pi]

      The polar (colatitudinal) coordinate.

    phi float [0, 2*pi]

      The azimuthal (longitudinal) coordinate.

    legacy: bool, optional

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

  Returns:
    real_sh real float

      The real harmonic \(Y_l^m\) sampled at `theta` and `phi`.

  References

### real_sh_tournier

dipy.reconst.shm.real_sh_tournier(sh_order_max, theta, phi, *, full_basis=False, legacy=True)

  Compute real spherical harmonics.

  The SH are computed as initially defined in [13] then updated in MRtrix3 [70], where the real harmonic \(Y_l^m\) is defined to be:

  Y_l^m = \begin{cases} \sqrt{2} * \Re(Y_l^m) \; if m > 0 \\ Y^0_l \; if m = 0 \\ \sqrt{2} * \Im(Y_l^{|m|}) \; if m < 0 \\ \end{cases}

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

  Parameters:
    sh_order_max int

      The maximum order (\(l\)) of the spherical harmonic basis.

    theta float [0, pi]

      The polar (colatitudinal) coordinate.

    phi float [0, 2*pi]

      The azimuthal (longitudinal) coordinate.

    full_basis: bool, optional

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

    legacy: bool, optional

      If true, uses MRtrix 0.2 SH basis definition, where the `sqrt(2)` factor is omitted. Else, uses MRtrix 3 definition presented above.

  Returns:
    real_sh real float

      The real harmonic \(Y_l^m\) sampled at `theta` and `phi`.

    m_values array of int

      The phase factor (\(m\)) of the harmonics.

    l_values array of int

      The order (\(l\)) of the harmonics.

  References

### real_sh_descoteaux

dipy.reconst.shm.real_sh_descoteaux(sh_order_max, theta, phi, *, full_basis=False, legacy=True)

  Compute real spherical harmonics.

  The definition adopted here follows [7], where the real harmonic \(Y_l^m\) is defined to be:

  Y_l^m = \begin{cases} \sqrt{2} * \Im(Y_l^m) \; if m > 0 \\ Y^0_l \; if m = 0 \\ \sqrt{2} * \Re(Y_l^m) \; if m < 0 \\ \end{cases}

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

  Parameters:
    sh_order_max int

      The maximum order (\(l\)) of the spherical harmonic basis.

    theta float [0, pi]

      The polar (colatitudinal) coordinate.

    phi float [0, 2*pi]

      The azimuthal (longitudinal) coordinate.

    full_basis: bool, optional

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

    legacy: bool, optional

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

  Returns:
    real_sh real float

      The real harmonic \(Y_l^m\) sampled at `theta` and `phi`.

    m_values array of int

      The phase factor (\(m\)) of the harmonics.

    l_values array of int

      The order (\(l\)) of the harmonics.

  References

### real_sym_sh_mrtrix

dipy.reconst.shm.real_sym_sh_mrtrix(sh_order_max, theta, phi)

  dipy.reconst.shm.real_sym_sh_mrtrix is deprecated, Please use dipy.reconst.shm.real_sh_tournier instead

  - deprecated from version: 1.3

  - Will raise <class ‘dipy.utils.deprecator.ExpiredDeprecationError’> as of version: 2.0

  Compute real symmetric spherical harmonics.

  The SH are computed as initially defined in Tournier et al.[13], where the real harmonic \(Y_l^m\) is defined to be:

  Y_l^m = \begin{cases} \Re(Y_l^m) \; if m > 0 \\ Y^0_l \; if m = 0 \\ \Im(Y_l^{|m|}) \; if m < 0 \\ \end{cases}

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

  Parameters:
    sh_order_max int

      The maximum order (\(l\)) of the spherical harmonic basis.

    theta float [0, pi]

      The polar (colatitudinal) coordinate.

    phi float [0, 2*pi]

      The azimuthal (longitudinal) coordinate.

  Returns:
    y_mn real float

      The real harmonic \(Y_l^m\) sampled at `theta` and `phi` as implemented in mrtrix. Warning: the basis is Tournier et al.[13]; [16] is slightly different.

    m_values array

      The phase factor (\(m\)) of the harmonics.

    l_values array

      The order (\(l\)) of the harmonics.

  References

### real_sym_sh_basis

dipy.reconst.shm.real_sym_sh_basis(sh_order_max, theta, phi)

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

  dipy.reconst.shm.real_sym_sh_basis is deprecated, Please use dipy.reconst.shm.real_sh_descoteaux instead

  - deprecated from version: 1.3

  - Will raise <class ‘dipy.utils.deprecator.ExpiredDeprecationError’> as of version: 2.0

  Samples the basis functions up to order sh_order_max at points on the sphere given by theta and phi. The basis functions are defined here the same way as in [7] where the real harmonic \(Y_l^m\) is defined to be:

  Y_l^m = \begin{cases} \sqrt{2} * \Im(Y_l^m) \; if m > 0 \\ Y^0_l \; if m = 0 \\ \sqrt{2} * \Im(Y_l^{|m|}) \; if m < 0 \\ \end{cases}

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

  Parameters:
    sh_order_max int

      The maximum order (\(l\)) of the spherical harmonic basis. Even int > 0, max spherical harmonic order

    theta float [0, 2*pi]

      The azimuthal (longitudinal) coordinate.

    phi float [0, pi]

      The polar (colatitudinal) coordinate.

  Returns:
    y_mn real float

      The real harmonic \(Y_l^m\) sampled at `theta` and `phi`

    m_values array of int

      The phase factor (\(m\)) of the harmonics.

    l_values array of int

      The order (\(l\)) of the harmonics.

  References

### sph_harm_ind_list

dipy.reconst.shm.sph_harm_ind_list(sh_order_max, *, full_basis=False)

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

  Parameters:
    sh_order_max int

      The maximum order (\(l\)) of the spherical harmonic basis. Even int > 0, max order to return

    full_basis: bool, optional

      True for SH basis with even and odd order terms

  Returns:
    m_list array of int

      phase factors (\(m\)) of even spherical harmonics

    l_list array of int

      orders (\(l\)) of even spherical harmonics

  See also

  `shm.real_sh_descoteaux_from_index`, `shm.real_sh_tournier_from_index`

### order_from_ncoef

dipy.reconst.shm.order_from_ncoef(ncoef, *, full_basis=False)

  Given a number `n` of coefficients, calculate back the `sh_order_max`

  Parameters:
    ncoef: int

      number of coefficients

    full_basis: bool, optional

      True when coefficients are for a full SH basis.

  Returns:
    sh_order_max: int

      maximum order (\(l\)) of SH basis

### smooth_pinv

dipy.reconst.shm.smooth_pinv(B, L)

  Regularized pseudo-inverse

  Computes a regularized least square inverse of B

  Parameters:
    B array_like (n, m)

      Matrix to be inverted

    L array_like (m,)
  Returns:
    inv ndarray (m, n)

      regularized least square inverse of B

  Notes

  In the literature this inverse is often written \((B^{T}B+L^{2})^{-1}B^{T}\). However here this inverse is implemented using the pseudo-inverse because it is more numerically stable than the direct implementation of the matrix product.

### lazy_index

dipy.reconst.shm.lazy_index(index)

  Produces a lazy index

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

### normalize_data

dipy.reconst.shm.normalize_data(data, where_b0, *, min_signal=1e-05, out=None)

  Normalizes the data with respect to the mean b0

### hat

dipy.reconst.shm.hat(B)

  Returns the hat matrix for the design matrix B

### lcr_matrix

dipy.reconst.shm.lcr_matrix(H)

  Returns a matrix for computing leveraged, centered residuals from data

  if r = (d-Hd), the leveraged centered residuals are lcr = (r/l)-mean(r/l) returns the matrix R, such that lcr = Rd

### bootstrap_data_array

dipy.reconst.shm.bootstrap_data_array(data, H, R, *, permute=None)

  Applies the Residual Bootstraps to the data given H and R

  data must be normalized, ie 0 < data <= 1

  This function, and the bootstrap_data_voxel function, calculate residual-bootstrap samples given a Hat matrix and a Residual matrix. These samples can be used for non-parametric statistics or for bootstrap probabilistic tractography,

  See [71], [72], and [73].

  References

  [71]

  Jeffrey I. Berman, SungWon Chung, Pratik Mukherjee, Christopher P. Hess, Eric T. Han, and Roland G. Henry. Probabilistic streamline q-ball tractography using the residual bootstrap. NeuroImage, 39(1):215–222, 2008. URL: https://doi.org/10.1016/j.neuroimage.2007.08.021, doi:10.1016/j.neuroimage.2007.08.021.

  [72]

  Hamied A. Haroon, David M. Morris, Karl V. Embleton, Daniel C. Alexander, and Geoffrey J. M. Parker. Using the Model-Based Residual Bootstrap to Quantify Uncertainty in Fiber Orientations From $Q$-Ball Analysis. IEEE Transactions on Medical Imaging, 28(4):535–550, 2009. doi:10.1109/TMI.2008.2006528.

  [73]

  Ben Jeurissen, Alexander Leemans, Derek K. Jones, Jacques-Donald Tournier, and Jan Sijbers. Probabilistic fiber tracking using the residual bootstrap with constrained spherical deconvolution. Human Brain Mapping, 32(3):461–479, 2011. URL: https://doi.org/10.1002/hbm.21032, doi:10.1002/hbm.21032.

### bootstrap_data_voxel

dipy.reconst.shm.bootstrap_data_voxel(data, H, R, *, permute=None)

  Like bootstrap_data_array but faster when for a single voxel

  data must be 1d and normalized

### sf_to_sh

dipy.reconst.shm.sf_to_sh(sf, sphere, *, sh_order_max=4, basis_type=None, full_basis=False, legacy=True, smooth=0.0)

  Spherical function to spherical harmonics (SH).

  Parameters:
    sf ndarray

      Values of a function on the given `sphere`.

    sphere Sphere

      The points on which the sf is defined.

    sh_order_max int, optional

      Maximum SH order (l) in the SH fit. For `sh_order_max`, there will be `(sh_order_max + 1) * (sh_order_max + 2) / 2` SH coefficients for a symmetric basis and `(sh_order_max + 1) * (sh_order_max + 1)` coefficients for a full SH basis.

    basis_type{None, ‘tournier07’, ‘descoteaux07’}, optional

      `None` for the default DIPY basis, `tournier07` for the Tournier 2007 [13], [70] basis, `descoteaux07` for the Descoteaux 2007 [7] basis, (`None` defaults to `descoteaux07`).

    full_basis: bool, optional

      True for using a SH basis containing even and odd order SH functions. False for using a SH basis consisting only of even order SH functions.

    legacy: bool, optional

      True to use a legacy basis definition for backward compatibility with previous `tournier07` and `descoteaux07` implementations.

    smooth float, optional

      Lambda-regularization in the SH fit.

  Returns:
    sh ndarray

      SH coefficients representing the input function.

  References

### sh_to_sf

dipy.reconst.shm.sh_to_sf(sh, sphere, *, sh_order_max=4, basis_type=None, full_basis=False, legacy=True)

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

  Parameters:
    sh ndarray

      SH coefficients representing a spherical function.

    sphere Sphere

      The points on which to sample the spherical function.

    sh_order_max int, optional

      Maximum SH order (l) in the SH fit. For `sh_order_max`, there will be `(sh_order_max + 1) * (sh_order_max + 2) / 2` SH coefficients for a symmetric basis and `(sh_order_max + 1) * (sh_order_max + 1)` coefficients for a full SH basis.

    basis_type{None, ‘tournier07’, ‘descoteaux07’}, optional

      `None` for the default DIPY basis, `tournier07` for the Tournier 2007 [13], [70] basis, `descoteaux07` for the Descoteaux 2007 [7] basis, (`None` defaults to `descoteaux07`).

    full_basis: bool, optional

      True to use a SH basis containing even and odd order SH functions. Else, use a SH basis consisting only of even order SH functions.

    legacy: bool, optional

      True to use a legacy basis definition for backward compatibility with previous `tournier07` and `descoteaux07` implementations.

  Returns:
    sf ndarray

      Spherical function values on the `sphere`.

  References

### sh_to_sf_matrix

dipy.reconst.shm.sh_to_sf_matrix(sphere, *, sh_order_max=4, basis_type=None, full_basis=False, legacy=True, return_inv=True, smooth=0)

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

  Parameters:
    sphere Sphere

      The points on which to sample the spherical function.

    sh_order_max int, optional

      Maximum SH order in the SH fit. For `sh_order_max`, there will be `(sh_order_max + 1) * (sh_order_max + 2) / 2` SH coefficients for a symmetric basis and `(sh_order_max + 1) * (sh_order_max + 1)` coefficients for a full SH basis.

    basis_type{None, ‘tournier07’, ‘descoteaux07’}, optional

      `None` for the default DIPY basis, `tournier07` for the Tournier 2007 [13], [70] basis, `descoteaux07` for the Descoteaux 2007 [7] basis, (`None` defaults to `descoteaux07`).

    full_basis: bool, optional

      If True, uses a SH basis containing even and odd order SH functions. Else, uses a SH basis consisting only of even order SH functions.

    legacy: bool, optional

      True to use a legacy basis definition for backward compatibility with previous `tournier07` and `descoteaux07` implementations.

    return_inv bool, optional

      If True then the inverse of the matrix is also returned.

    smooth float, optional

      Lambda-regularization in the SH fit.

  Returns:
    B ndarray

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

    invB ndarray

      Inverse of B.

  References

### calculate_max_order

dipy.reconst.shm.calculate_max_order(n_coeffs, *, full_basis=False)

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

  Parameters:
    n_coeffs int

      The number of SH coefficients

    full_basis: bool, optional

      True if the used SH basis contains even and odd order SH functions. False if the SH basis consists only of even order SH functions.

  Returns:
    L int

      The maximal SH order (l), given the number of coefficients

  Notes

  The calculation in this function for the symmetric SH basis proceeds according to the following logic:

  \[n = \frac{1}{2} (L+1) (L+2) \rarrow 2n = L^2 + 3L + 2 \rarrow L^2 + 3L + 2 - 2n = 0 \rarrow L^2 + 3L + 2(1-n) = 0 \rarrow L_{1,2} = \frac{-3 \pm \sqrt{9 - 8 (1-n)}}{2} \rarrow L{1,2} = \frac{-3 \pm \sqrt{1 + 8n}}{2}\]

  Finally, the positive value is chosen between the two options.

  For a full SH basis, the calculation consists in solving the equation \(n = (L + 1)^2\) for \(L\), which gives \(L = sqrt(n) - 1\).

### anisotropic_power

dipy.reconst.shm.anisotropic_power(sh_coeffs, *, norm_factor=1e-05, power=2, non_negative=True)

  Calculate anisotropic power map with a given SH coefficient matrix.

  See [74] for further details about the method.

  Parameters:
    sh_coeffs ndarray

      A ndarray where the last dimension is the SH coefficients estimates for that voxel.

    norm_factor: float, optional

      The value to normalize the ap values.

    power int, optional

      The degree to which power maps are calculated.

    non_negative: bool, optional

      Whether to rectify the resulting map to be non-negative.

  Returns:
    log_ap ndarray

      The log of the resulting power image.

  Notes

  Calculate AP image based on a IxJxKxC SH coefficient matrix based on the equation:

  \[AP = \sum_{l=2,4,6,...}{\frac{1}{2l+1} \sum_{m=-l}^l{|a_{l,m}|^n}}\]

  Where the last dimension, C, is made of a flattened array of \(l`x:math:`m\) coefficients, where \(l\) are the SH orders, and \(m = 2l+1\), So l=1 has 1 coefficient, l=2 has 5, … l=8 has 17 and so on. A l=2 SH coefficient matrix will then be composed of a IxJxKx6 volume. The power, \(n\) is usually set to \(n=2\).

  The final AP image is then shifted by -log(norm_factor), to be strictly non-negative. Remaining values < 0 are discarded (set to 0), per default, and this option is controlled through the non_negative keyword argument.

  References

  [74]

  Flavio Dell’Acqua, Luis Lacerda, Marco Catani, and Andrew Simmons. Anisotropic Power Maps: A diffusion contrast to reveal low anisotropy tissues from HARDI data. In Joint Annual Meeting ISMRM-ESMRMB 2014 SMRT 23rd Annual Meeting, volume. Milan, Italy, 2014. International Society for Magnetic Resonance in Medicine (ISMRM).

### convert_sh_to_full_basis

dipy.reconst.shm.convert_sh_to_full_basis(sh_coeffs)

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

  Parameters:
    sh_coeffs: ndarray

      A ndarray where the last dimension is the SH coefficients estimates for that voxel.

  Returns:
    full_sh_coeffs: ndarray

      A ndarray where the last dimension is the SH coefficients estimates for that voxel in a full SH basis.

### convert_sh_from_legacy

dipy.reconst.shm.convert_sh_from_legacy(sh_coeffs, sh_basis, *, full_basis=False)

  Convert SH coefficients in legacy SH basis to SH coefficients of the new SH basis for `descoteaux07` or `tournier07` bases.

  See [7] and [13], [70] for the `descoteaux07` and `tournier07` bases, respectively.

  Parameters:
    sh_coeffs: ndarray

      A ndarray where the last dimension is the SH coefficients estimates for that voxel.

    sh_basis: {‘descoteaux07’, ‘tournier07’}

      `tournier07` for the Tournier 2007 [13], [70] basis, `descoteaux07` for the Descoteaux 2007 [7] basis.

    full_basis: bool, optional

      True if the input SH basis includes both even and odd order SH functions, else False.

  Returns:
    out_sh_coeffs: ndarray

      The array of coefficients expressed in the new SH basis.

  References

### convert_sh_to_legacy

dipy.reconst.shm.convert_sh_to_legacy(sh_coeffs, sh_basis, *, full_basis=False)

  Convert SH coefficients in new SH basis to SH coefficients for the legacy SH basis for `descoteaux07` or `tournier07` bases.

  See [7] and [13], [70] for the `descoteaux07` and `tournier07` bases, respectively.

  Parameters:
    sh_coeffs: ndarray

      A ndarray where the last dimension is the SH coefficients estimates for that voxel.

    sh_basis: {‘descoteaux07’, ‘tournier07’}

      `tournier07` for the Tournier 2007 [13], [70] basis, `descoteaux07` for the Descoteaux 2007 [7] basis.

    full_basis: bool, optional

      True if the input SH basis includes both even and odd order SH functions.

  Returns:
    out_sh_coeffs: ndarray

      The array of coefficients expressed in the legacy SH basis.

  References

### convert_sh_descoteaux_tournier

dipy.reconst.shm.convert_sh_descoteaux_tournier(sh_coeffs)

  Convert SH coefficients between legacy-descoteaux07 and tournier07.

  Convert SH coefficients between the legacy `descoteaux07` SH basis and the non-legacy `tournier07` SH basis. Because this conversion is equal to its own inverse, it can be used to convert in either direction: legacy-descoteaux to non-legacy-tournier or non-legacy-tournier to legacy-descoteaux.

  This can be used to convert SH representations between DIPY and MRtrix3.

  See [7] and [70] for the origin of these SH bases.

  See [mrtrixbasis] for a description of the basis used in MRtrix3. See [mrtrixdipybases] for more details on the conversion.

  Parameters:
    sh_coeffs: ndarray

      A ndarray where the last dimension is the SH coefficients estimates for that voxel.

  Returns:
    out_sh_coeffs: ndarray

      The array of coefficients expressed in the “other” SH basis. If the input was in the legacy-descoteaux basis then the output will be in the non-legacy-tournier basis, and vice versa.

  References

  [mrtrixbasis]

  https://mrtrix.readthedocs.io/en/latest/concepts/spherical_harmonics.html

  [mrtrixdipybases]

  https://github.com/dipy/dipy/discussions/2959#discussioncomment-7481675

### `ShoreModel`

class dipy.reconst.shore.ShoreModel(gtab, *, radial_order=6, zeta=700, lambdaN=1e-08, lambdaL=1e-08, tau=0.025330295910584444, constrain_e0=False, positive_constraint=False, pos_grid=11, pos_radius=0.02, cvxpy_solver=None)

  Bases: `Cache`

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

  The main idea of SHORE [75] is to model the diffusion signal as a linear combination of continuous functions \(\phi_i\),

  \[S(\mathbf{q})= \sum_{i=0}^I c_{i} \phi_{i}(\mathbf{q})\]

  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 [76], [77], and [78].

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

  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

  Notes

  The implementation of SHORE depends on CVXPY (https://www.cvxpy.org/).

  References

  [75]

  Evren Özarslan, Cheng Guan Koay, and Peter J. Basser. Simple harmonic oscillator based reconstruction and estimation for one-dimensional q-space magnetic resonance (1D-SHORE). In ISMRM 16th Scientific Meeting & Exhibition SMRT 17th Annual Meeting, volume 16, 35. Toronto, Canada, 2008. International Society for Magnetic Resonance in Medicine (ISMRM).

  [76] (1,2,3,4)

  Sylvain L. Merlet and Rachid Deriche. Continuous diffusion signal, EAP and ODF estimation via Compressive Sensing in diffusion MRI. Medical Image Analysis, 17(5):556–572, July 2013. URL: https://doi.org/10.1016/j.media.2013.02.010, doi:10.1016/j.media.2013.02.010.

  [77]

  Yogesh Rathi, Oleg Michailovich, Kawin Setsompop, Sylvain Bouix, Martha E. Shenton, and Carl-Fredrik Westin. Sparse Multi-Shell Diffusion Imaging. In Gabor Fichtinger, Anne Martel, and Terry Peters, editors, Medical Image Computing and Computer-Assisted Intervention – MICCAI 2011, 58–65. Berlin, Heidelberg, 2011. Springer Berlin Heidelberg.

  [78]

  Jian Cheng, Tianzi Jiang, and Rachid Deriche. Theoretical Analysis and Practical Insights on EAP Estimation via a Unified HARDI Framework. In MICCAI Workshop on Computational Diffusion MRI (CDMRI). Toronto, Canada, September 2011.

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

    Fit method for every voxel in data

### `ShoreFit`

class dipy.reconst.shore.ShoreFit(model, shore_coef)

  Bases: `object`

  Attributes:
    `shore_coeff`

      The SHORE coefficients

  Methods

  `fitted_signal`() | The fitted signal.
  `msd`() | Calculates the analytical mean squared displacement (MSD).
  `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.
  `rtop_signal`() | Calculates the analytical return to origin probability (RTOP) from the signal.

  fitted_signal()

    The fitted signal.

  msd()

    Calculates the analytical mean squared displacement (MSD).

    See [32] for a definition of the method.

    MSD:{DSI}=\int_{-\infty}^{\infty}\int_{-\infty}^{\infty} \int_{-\infty}^{\infty} P(\hat{\mathbf{r}}) \cdot \hat{\mathbf{r}}^{2} \ dr_x \ dr_y \ dr_z

    where \(\hat{\mathbf{r}}\) is a point in the 3D propagator space (see Wu and Alexander[32]).

    References

  odf(sphere)

    Calculates the ODF for a given discrete sphere.

  odf_sh()

    Calculates the real analytical ODF in terms of Spherical Harmonics.

  pdf(r_points)

    Diffusion propagator on a given set of real points. if the array r_points is non writeable, then intermediate results are cached for faster recalculation

  pdf_grid(gridsize, radius_max)

    Applies the analytical FFT on \(S\) to generate the diffusion propagator. This is calculated on a discrete 3D grid in order to obtain an EAP similar to that which is obtained with DSI.

    Parameters:
      gridsize unsigned int

        dimension of the propagator grid

      radius_max float

        maximal radius in which to compute the propagator

    Returns:
      eap ndarray

        the ensemble average propagator in the 3D grid

  rtop_pdf()

    Calculates the analytical return to origin probability (RTOP) from the pdf.

    See [58] for further details about the method.

    References

  rtop_signal()

    Calculates the analytical return to origin probability (RTOP) from the signal.

    See [58] for further details about the method.

    References

  property shore_coeff

    The SHORE coefficients

### shore_matrix

dipy.reconst.shore.shore_matrix(radial_order, zeta, gtab, *, tau=0.025330295910584444)

  Compute the SHORE matrix for modified Merlet’s 3D-SHORE.

  See [76] for the definition.

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

  where \(\phi_{nlm}\) is

  \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})
  Parameters:
    radial_order unsigned int,

      an even integer that represent the order of the basis

    zeta unsigned int,

      scale factor

    gtab GradientTable,

      gradient directions and bvalues container class

    tau float, optional

      diffusion time. By default the value that makes q=sqrt(b).

  References

### shore_matrix_pdf

dipy.reconst.shore.shore_matrix_pdf(radial_order, zeta, rtab)

  Compute the SHORE propagator matrix.

  See [76] for the definition.

  Parameters:
    radial_order unsigned int,

      an even integer that represent the order of the basis

    zeta unsigned int,

      scale factor

    rtab array, shape (N,3)

      real space points in which calculates the pdf

  References

### shore_matrix_odf

dipy.reconst.shore.shore_matrix_odf(radial_order, zeta, sphere_vertices)

  Compute the SHORE ODF matrix.

  See [76] for the definition.

  Parameters:
    radial_order unsigned int,

      an even integer that represent the order of the basis

    zeta unsigned int,

      scale factor

    sphere_vertices array, shape (N,3)

      vertices of the odf sphere

  References

### l_shore

dipy.reconst.shore.l_shore(radial_order)

  Returns the angular regularisation matrix for SHORE basis

### n_shore

dipy.reconst.shore.n_shore(radial_order)

  Returns the angular regularisation matrix for SHORE basis

### create_rspace

dipy.reconst.shore.create_rspace(gridsize, radius_max)
  Create the real space table, that contains the points in which

    to compute the pdf.

  Parameters:
    gridsize unsigned int

      dimension of the propagator grid

    radius_max float

      maximal radius in which compute the propagator

  Returns:
    vecs array, shape (N,3)

      positions of the pdf points in a 3D matrix

    tab array, shape (N,3)

      real space points in which calculates the pdf

### shore_indices

dipy.reconst.shore.shore_indices(radial_order, index)

  Given the basis order and the index, return the shore indices n, l, m for modified Merlet’s 3D-SHORE

  \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

  \begin{equation} \phi_{nlm}^{SHORE}(q\textbf{u})=\Biggl[\dfrac{2(n-l)!} {\zeta^{3/2} \Gamma(n+3/2)} \Biggr]^{1/2} \Biggl(\dfrac{q^2}{\zeta}\Biggr)^{l/2} exp\Biggl(\dfrac{-q^2}{2\zeta}\Biggr) L^{l+1/2}_{n-l} \Biggl(\dfrac{q^2}{\zeta}\Biggr) Y_l^m(\textbf{u}). \end{equation}
  Parameters:
    radial_order unsigned int

      an even integer that represent the maximal order of the basis

    index unsigned int

      index of the coefficients, start from 0

  Returns:
    n unsigned int

      the index n of the modified shore basis

    l unsigned int

      the index l of the modified shore basis

    m unsigned int

      the index m of the modified shore basis

### shore_order

dipy.reconst.shore.shore_order(n, ell, 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:
    n unsigned int

      the index n of the modified shore basis

    ell unsigned int

      the index l of the modified shore basis

    m unsigned int

      the index m of the modified shore basis

  Returns:
    radial_order unsigned int

      an even integer that represent the maximal order of the basis

    index unsigned int

      index of the coefficient corresponding to (n,l,m), start from 0

### dki_design_matrix

dipy.reconst.utils.dki_design_matrix(gtab)

  Construct B design matrix for DKI.

  Parameters:
    gtab GradientTable

      Measurement directions.

  Returns:
    B array (N, 22)

      Design matrix or B matrix for the DKI model

      \[B[j, :] = (Bxx, Bxy, Byy, Bxz, Byz, Bzz, Bxxxx, Byyyy, Bzzzz, Bxxxy, Bxxxz, Bxyyy, Byyyz, Bxzzz, Byzzz, Bxxyy, Bxxzz, Byyzz, Bxxyz, Bxyyz, Bxyzz, BlogS0)\]

### cti_design_matrix

dipy.reconst.utils.cti_design_matrix(gtab1, gtab2)

  Construct B design matrix for CTI.

  Parameters:
    gtab1: dipy.core.gradients.GradientTable

      A GradientTable class instance for first DDE diffusion epoch

    gtab2: dipy.core.gradients.GradientTable

      A GradientTable class instance for second DDE diffusion epoch

  Returns:
    B: array(N, 43)
    Design matrix or B matrix for the CTI model assuming multiple
    Gaussian Components

### convert_tensors

dipy.reconst.utils.convert_tensors(tensor, from_format, to_format)

  Convert tensors from one format to another.

  Parameters:
    tensor ndarray

      Input tensor.

    from_format str

      Format of the input tensor. Options: ‘dipy’, ‘mrtrix’, ‘ants’, ‘fsl’.

    to_format str

      Format of the output tensor. Options: ‘dipy’, ‘mrtrix’, ‘ants’, ‘fsl’.

  Notes

  - DIPY order: [Dxx, Dxy, Dyy, Dxz, Dyz, Dzz]. Shape: [i, j , k, 6]. See: https://github.com/dipy/dipy/blob/master/dipy/reconst/dti.py#L1639

  - MRTRIX order: [Dxx, Dyy, Dzz, Dxy, Dxz, Dyz]

      Shape: [i, j , k, 6]. See: https://mrtrix.readthedocs.io/en/dev/reference/commands/dwi2tensor.html # noqa

  - ANTS: [Dxx, Dxy, Dyy, Dxz, Dyz, Dzz].

      Shape: [i, j , k, 1, 6] - Note the extra dimension (5D) See: https://github.com/ANTsX/ANTs/wiki/Importing-diffusion-tensor-data-from-other-software # noqa

  - FSL: [Dxx, Dxy, Dxz, Dyy, Dyz, Dzz] Shape: [i, j , k, 6]. (Also used for the Fibernavigator) Ref: https://fsl.fmrib.ox.ac.uk/fsl/fslwiki/FDT/UserGuide

### simple_cutoff

dipy.reconst.weights_method.simple_cutoff(residuals, log_residuals, pred_sig, design_matrix, leverages, C, cutoff)

  Define outliers based on the signal (rather than the log-signal).

  Parameters:
    residuals ndarray

      Residuals of the signal (observed signal - fitted signal).

    log_residuals ndarray

      Residuals of the log signal (log observed signal - fitted log signal).

    pred_sig ndarray

      The predicted signal, given a previous fit.

    design_matrix ndarray (g, …)

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

    leverages ndarray

      The leverages (diagonal of the ‘hat matrix’) of the fit.

    C float

      Estimate of the standard deviation of the error.

    cutoff float, optional

      Cut-off value for defining outliers based on fitting residuals. Here the condition is:

          |residuals| > cut_off x C x HAT_factor

      where HAT_factor = sqrt(1 - leverages) adjusts for leverage effects.

### two_eyes_cutoff

dipy.reconst.weights_method.two_eyes_cutoff(residuals, log_residuals, pred_sig, design_matrix, leverages, C, cutoff)

  Define outliers with two-eyes approach.

  see [79] for more details.

  Parameters:
    residuals ndarray

      Residuals of the signal (observed signal - fitted signal).

    log_residuals ndarray

      Residuals of the log signal (log observed signal - fitted log signal).

    pred_sig ndarray

      The predicted signal, given a previous fit.

    design_matrix ndarray (g, …)

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

    leverages ndarray

      The leverages (diagonal of the ‘hat matrix’) of the fit.

    C float

      Estimate of the standard deviation of the error.

    cutoff float, optional

      Cut-off value for defining outliers based on fitting residuals, see [79] for the two-eyes approached used here.

  References

  [79] (1,2,3)

  Quinten Collier, Jelle Veraart, Ben Jeurissen, Arno den Dekker, and Jan Sijbers. Iterative reweighted linear least squares for accurate, fast, and robust estimation of diffusion magnetic resonance parameters: IRLLS for Estimation of Diffusion MR Parameters. Magnetic Resonance in Medicine, 73(6):2174–2184, 2015. URL: https://doi.org/10.1002/mrm.25351, doi:10.1002/mrm.25351.

### weights_method_wls_m_est

dipy.reconst.weights_method.weights_method_wls_m_est(data, pred_sig, design_matrix, leverages, idx, total_idx, last_robust, *, m_est='gm', cutoff=3, outlier_condition_func=<function simple_cutoff>)

  Calculate M-estimator weights for WLS model.

  Parameters:
    data ndarray

      The measured signal.

    pred_sig ndarray

      The predicted signal, given a previous fit. Has the same shape as data.

    design_matrix ndarray (g, …)

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

    leverages ndarray

      The leverages (diagonal of the ‘hat matrix’) of the fit.

    idx int

      The current iteration number.

    total_idx int

      The total number of iterations.

    last_robust ndarray

      True for inlier indices and False for outlier indices. Must have the same shape as data.

    m_est str, optional.

      M-estimator weighting scheme to use. Currently, ‘gm’ (Geman-McClure) and ‘cauchy’ are provided.

    cutoff float, optional

      Cut-off value for defining outliers based on fitting residuals. Will be passed to the outlier_condition_func. Typical example: `|residuals| > cut_off x standard_deviation`

    outlier_condition_func callable, optional

      A function with args and returns as follows:

          is_an_outlier = outlier_condition_func(residuals, log_residuals,
              pred_sig, design_matrix, leverages, C, cutoff)

  Notes

  Robust weights are calculated specifically for the WLS problem, i.e. the usual form of the WLS problem is accounted for when defining these new weights, see [79]. On the second-to-last iteration, OLS is performed without outliers. On the last iteration, WLS is performed without outliers.

  References

### weights_method_nlls_m_est

dipy.reconst.weights_method.weights_method_nlls_m_est(data, pred_sig, design_matrix, leverages, idx, total_idx, last_robust, *, m_est='gm', cutoff=3, outlier_condition_func=<function simple_cutoff>)

  Calculate M-estimator weights for NLLS model.

  Parameters:
    data ndarray

      The measured signal.

    pred_sig ndarray

      The predicted signal, given a previous fit. Has the same shape as data.

    design_matrix ndarray (g, …)

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

    leverages ndarray

      The leverages (diagonal of the ‘hat matrix’) of the fit.

    idx int

      The current iteration number.

    total_idx int

      The total number of iterations.

    last_robust ndarray

      True for inlier indices and False for outlier indices. Must have the same shape as data.

    m_est str, optional.

      M-estimator weighting scheme to use. Currently, ‘gm’ (Geman-McClure) and ‘cauchy’ are provided.

    cutoff float, optional

      Cut-off value for defining outliers based on fitting residuals. Will be passed to the outlier_condition_func. Typical example: `|residuals| > cut_off x standard_deviation`

    outlier_condition_func callable, optional

      A function with args and returns as follows:

          is_an_outlier = outlier_condition_func(residuals, log_residuals,
              pred_sig, design_matrix, leverages, C, cutoff)

  Notes

  Robust weights are calculated specifically for the NLLS problem. On the last iteration, NLLS is performed without outliers.