Welcome to dmipy’s documentation!¶
The dmipy software package facilitates stateoftheart diffusion MRI Microstructure Imaging using a “Building Block” philosophy. In this philosophy, any combination of biophysical models, typically representing intra and/or extraaxonal tissue compartments, can be easy combined into a multicompartment Microstructure Model in just a few lines of code.
To see how to use it, please refer to the README file in the Github repository.
Contents:
API Reference¶
core
¶
Module: core.acquisition_scheme
¶

dmipy.core.acquisition_scheme.
get_sh_order_from_bval
(bval)¶ Estimates minimum sh_order to represent data of given bvalue.

class
dmipy.core.acquisition_scheme.
DmipyAcquisitionScheme
(bvalues, gradient_directions, qvalues, gradient_strengths, delta, Delta, TE, min_b_shell_distance, b0_threshold)¶ Class that calculates and contains all information needed to simulate and fit data using microstructure models.
Attributes
Methods

print_acquisition_info
¶ prints a small summary of the acquisition scheme. Is useful to check if the function correctly separated the shells and if the input parameters were given in the right scale.

to_schemefile
(filename)¶ Exports acquisition scheme information in schemefile format, which can be used by the Camino MonteCarlo simulator.
Parameters: filename : string,
location at which to save the schemefile.

visualise_acquisition_G_Delta_rainbow
(Delta_start=None, 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 qtau 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 bvector, with a background of bvalue isolines for reference. It assumes there is only one unique pulse length (small_delta) in the acquisition scheme.
Parameters: Delta_start : float,
optional minimum big_delta that is plotted in seconds
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 taht is plotted in T/m
bval_isolines : array,
optional array of bvalue isolines that are plotted in background given in s/mm^2
alpha_shading : float between [01]
optional shading of the bvalue colors in the background


class
dmipy.core.acquisition_scheme.
RotationalHarmonicsAcquisitionScheme
(dmipy_acquisition_scheme, N_angular_samples=10)¶ AcquisitionScheme instance that contains the information necessary to calculate the rotational harmonics for a model for every acquisition shell. It is instantiated using a regular DmipyAcquisitionScheme and N_angular_samples determines how many samples are taken between mu=[0., 0.] and mu=[np.pi/2, 0.].
Parameters: dmipy_acquisition_scheme: DmipyAcquisitionScheme instance :
An acquisition scheme that has been instantiated using dMipy.
N_angular_samples: int :
Integer representing the number of angular samples per shell.

class
dmipy.core.acquisition_scheme.
SphericalMeanAcquisitionScheme
(bvalues, qvalues, gradient_strengths, Deltas, deltas)¶ Acquisition scheme for isotropic spherical mean models.

dmipy.core.acquisition_scheme.
acquisition_scheme_from_bvalues
(bvalues, gradient_directions, delta, Delta, TE=None, min_b_shell_distance=50000000.0, b0_threshold=10000000.0)¶ Creates an acquisition scheme object from bvalues, gradient directions, pulse duration \(\delta\) and pulse separation time \(\Delta\).
Parameters: bvalues: 1D numpy array of shape (Ndata) :
bvalues of the acquisition in s/m^2. e.g., a bvalue of 1000 s/mm^2 must be entered as 1000 * 1e6 s/m^2
gradient_directions: 2D numpy array of shape (Ndata, 3) :
gradient directions array of cartesian unit vectors.
delta: float or 1D numpy array of shape (Ndata) :
if float, pulse duration of every measurements in seconds. if array, potentially varying pulse duration per measurement.
Delta: float or 1D numpy array of shape (Ndata) :
if float, pulse separation time of every measurements in seconds. if array, potentially varying pulse separation time per measurement.
min_b_shell_distance : float
minimum bvalue distance between different shells. This parameter is used to separate measurements into different shells, which is necessary for any model using spherical convolution or spherical mean.
b0_threshold : float
bvalue threshold for a measurement to be considered a b0 measurement.
Returns: DmipyAcquisitionScheme: acquisition scheme object :
contains all information of the acquisition scheme to be used in any microstructure model.

dmipy.core.acquisition_scheme.
acquisition_scheme_from_qvalues
(qvalues, gradient_directions, delta, Delta, TE=None, min_b_shell_distance=50000000.0, b0_threshold=10000000.0)¶ Creates an acquisition scheme object from qvalues, gradient directions, pulse duration \(\delta\) and pulse separation time \(\Delta\).
Parameters: qvalues: 1D numpy array of shape (Ndata) :
diffusion sensitization of the acquisition in 1/m. e.g. a qvalue of 10 1/mm must be entered as 10 * 1e3 1/m
gradient_directions: 2D numpy array of shape (Ndata, 3) :
gradient directions array of cartesian unit vectors.
delta: float or 1D numpy array of shape (Ndata) :
if float, pulse duration of every measurements in seconds. if array, potentially varying pulse duration per measurement.
Delta: float or 1D numpy array of shape (Ndata) :
if float, pulse separation time of every measurements in seconds. if array, potentially varying pulse separation time per measurement.
min_b_shell_distance : float
minimum bvalue distance between different shells. This parameter is used to separate measurements into different shells, which is necessary for any model using spherical convolution or spherical mean.
b0_threshold : float
bvalue threshold for a measurement to be considered a b0 measurement.
Returns: DmipyAcquisitionScheme: acquisition scheme object :
contains all information of the acquisition scheme to be used in any microstructure model.

dmipy.core.acquisition_scheme.
acquisition_scheme_from_gradient_strengths
(gradient_strengths, gradient_directions, delta, Delta, TE=None, min_b_shell_distance=50000000.0, b0_threshold=10000000.0)¶ Creates an acquisition scheme object from gradient strengths, gradient directions pulse duration \(\delta\) and pulse separation time \(\Delta\).
Parameters: gradient_strengths: 1D numpy array of shape (Ndata) :
gradient strength of the acquisition in T/m. e.g., a gradient strength of 300 mT/m must be entered as 300 / 1e3 T/m
gradient_directions: 2D numpy array of shape (Ndata, 3) :
gradient directions array of cartesian unit vectors.
delta: float or 1D numpy array of shape (Ndata) :
if float, pulse duration of every measurements in seconds. if array, potentially varying pulse duration per measurement.
Delta: float or 1D numpy array of shape (Ndata) :
if float, pulse separation time of every measurements in seconds. if array, potentially varying pulse separation time per measurement.
min_b_shell_distance : float
minimum bvalue distance between different shells. This parameter is used to separate measurements into different shells, which is necessary for any model using spherical convolution or spherical mean.
b0_threshold : float
bvalue threshold for a measurement to be considered a b0 measurement.
Returns: DmipyAcquisitionScheme: acquisition scheme object :
contains all information of the acquisition scheme to be used in any microstructure model.

dmipy.core.acquisition_scheme.
acquisition_scheme_from_schemefile
(file_path, min_b_shell_distance=50000000.0, b0_threshold=10000000.0)¶ Created an acquisition scheme object from a Camino scheme file, containing gradient directions, strengths, pulse duration \(\delta\) and pulse separation time \(\Delta\) and TE.
Parameters: file_path: string :
absolute file path to schemefile location
Returns: DmipyAcquisitionScheme: acquisition scheme object :
contains all information of the acquisition scheme to be used in any microstructure model.

dmipy.core.acquisition_scheme.
unify_length_reference_delta_Delta
(reference_array, delta, Delta, TE)¶ If either delta or Delta are given as float, makes them an array the same size as the reference array.
Parameters: reference_array : array of size (Nsamples)
typically bvalues, qvalues or gradient strengths.
delta : float or array of size (Nsamples)
pulse duration in seconds.
Delta : float or array of size (Nsamples)
pulse separation in seconds.
TE : None, float or array of size (Nsamples)
Echo time of the acquisition in seconds.
Returns: delta_ : array of size (Nsamples)
pulse duration copied to be same size as reference_array
Delta_ : array of size (Nsamples)
pulse separation copied to be same size as reference_array
TE_ : None or array of size (Nsamples)
Echo time copied to be same size as reference_array

dmipy.core.acquisition_scheme.
calculate_shell_bvalues_and_indices
(bvalues, max_distance=20000000.0)¶ Calculates which measurements belong to different acquisition shells. It uses scipy’s linkage clustering algorithm, which uses the max_distance input as a limit of including measurements in the same cluster.
For example, if bvalues were [1, 2, 3, 4, 5] and max_distance was 1, then all bvalues would belong to the same cluster. However, if bvalues were [1, 2, 4, 5] max max_distance was 1, then this would result in 2 clusters.
Parameters: bvalues: 1D numpy array of shape (Ndata) :
bvalues of the acquisition in s/m^2.
max_distance: float :
maximum bvalue distance for a measurement to be included in the same shell.
Returns: shell_indices: 1D numpy array of shape (Ndata) :
array of integers, starting from 0, representing to which shell a measurement belongs. The number itself has no meaning other than just being different for different shells.
shell_bvalues: 1D numpy array of shape (Nshells) :
array of the mean bvalues for every acquisition shell.

dmipy.core.acquisition_scheme.
check_acquisition_scheme
(bqg_values, gradient_directions, delta, Delta, TE)¶ function to check the validity of the input parameters.

dmipy.core.acquisition_scheme.
gtab_dipy2mipy
(dipy_gradient_table)¶ Converts a dipy gradient_table to a dmipy acquisition_scheme.

dmipy.core.acquisition_scheme.
gtab_mipy2dipy
(dmipy_gradient_table)¶ Converts a dmipy acquisition scheme to a dipy gradient_table.
Module: core.constants
¶
Module: core.fitted_modeling_framework
¶

class
dmipy.core.fitted_modeling_framework.
FittedMultiCompartmentModel
(model, S0, mask, fitted_parameters_vector)¶ The FittedMultiCompartmentModel instance contains information about the original MultiCompartmentModel, the estimated S0 values, the fitting mask and the fitted model parameters.
Parameters: model : MultiCompartmentModel instance,
A dmipy MultiCompartmentModel.
S0 : array of size (Ndata,) or (N_data, N_DWIs),
Array containing the estimated S0 values of the data. If data is 4D, then S0 is 3D if there is only one TE, and the same 4D size of the data if there are multiple TEs.
mask : array of size (N_data,),
boolean mask of voxels that were fitted.
fitted_parameters_vector : array of size (N_data, Nparameters),
fitted model parameters array.
Attributes
Methods

R2_coefficient_of_determination
(data)¶ Calculates the Rsquared of the model fit.

fitted_and_linked_parameters
¶ Returns the fitted and linked parameters as a dictionary.

fitted_parameters
¶ Returns the fitted parameters as a dictionary.

fod
(vertices, visual_odi_lower_bound=0.0)¶ Returns the Fiber Orientation Distribution if it is available.
Parameters: vertices : array of size (Nvertices, 3),
Array of cartesian unit vectors at which to sample the FOD.
visual_odi_lower_bound : float,
gives a lower bound to the Orientation Distribution Index (ODI) of FODs of Watson and Bingham distributions. This can be useful to visualize FOD fields where some FODs are extremely sharp.
Returns: fods : array of size (Ndata, Nvertices),
the FODs of the fitted model, scaled by volume fraction.

fod_sh
(sh_order=8, basis_type=None)¶ Returns the spherical harmonics coefficients of the Fiber Orientation Distribution (FOD) if it is available. Uses are 724 spherical tessellation to do the spherical harmonics transform.
Parameters: sh_order : integer,
the maximum spherical harmonics order of the coefficient expansion.
basis_type : string,
type of spherical harmonics basis to use for the expansion, see sh_to_sf_matrix for more info.
Returns: fods_sh : array of size (Ndata, Ncoefficients),
spherical harmonics coefficients of the FODs, scaled by volume fraction.

mean_squared_error
(data)¶ Calculates the mean squared error of the model fit.

peaks_cartesian
()¶ Returns the cartesian peak unit vectors of the model.

peaks_spherical
()¶ Returns the peak angles of the model.

predict
(acquisition_scheme=None, S0=None, mask=None)¶ simulates the dMRI signal of the fitted MultiCompartmentModel for the estimated model parameters. If no acquisition_scheme is given, then the same acquisition_scheme that was used for the fitting is used. If no S0 is given then it is assumed to be the estimated one. If no mask is given then all voxels are assumed to have been fitted.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
S0 : None or float,
Signal intensity without diffusion sensitization. If None, uses estimated SO from fitting process. If float, uses that value.
mask : (N1)dimensional integer/boolean array of size (N_x, N_y, …),
mask of voxels to simulate data at.
Returns: predicted_signal : array of size (Ndata, N_DWIS),
predicted DWIs for the given model parameters and acquisition scheme.


class
dmipy.core.fitted_modeling_framework.
FittedMultiCompartmentSphericalMeanModel
(model, S0, mask, fitted_parameters_vector)¶ The FittedMultiCompartmentModel instance contains information about the original MultiCompartmentModel, the estimated S0 values, the fitting mask and the fitted model parameters.
Parameters: model : MultiCompartmentModel instance,
A dmipy MultiCompartmentModel.
S0 : array of size (Ndata,) or (N_data, N_DWIs),
Array containing the estimated S0 values of the data. If data is 4D, then S0 is 3D if there is only one TE, and the same 4D size of the data if there are multiple TEs.
mask : array of size (N_data,),
boolean mask of voxels that were fitted.
fitted_parameters_vector : array of size (N_data, Nparameters),
fitted model parameters array.
Attributes
Methods

R2_coefficient_of_determination
(data)¶ Calculates the Rsquared of the model fit.

fitted_and_linked_parameters
¶ Returns the fitted and linked parameters as a dictionary.

fitted_parameters
¶ Returns the fitted parameters as a dictionary.

mean_squared_error
(data)¶ Calculates the mean squared error of the model fit.

predict
(acquisition_scheme=None, S0=None, mask=None)¶ simulates the dMRI signal of the fitted MultiCompartmentModel for the estimated model parameters. If no acquisition_scheme is given, then the same acquisition_scheme that was used for the fitting is used. If no S0 is given then it is assumed to be the estimated one. If no mask is given then all voxels are assumed to have been fitted.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
S0 : None or float,
Signal intensity without diffusion sensitization. If None, uses estimated SO from fitting process. If float, uses that value.
mask : (N1)dimensional integer/boolean array of size (N_x, N_y, …),
mask of voxels to simulate data at.
Returns: predicted_signal : array of size (Ndata, N_DWIS),
predicted DWIs for the given model parameters and acquisition scheme.

return_parametric_fod_model
(distribution='watson', Ncompartments=1)¶ Retuns parametric FOD model using the rotational harmonics of the fitted spherical mean model as the convolution kernel. It can be called with any implemented parametric distribution (Watson/Bingham) and for any number of compartments.
Internally, the input models to the spherical mean model are given to a spherically distributed model where the parameter links are replayed such that the distributed model has the same parameter constraints as the spherical mean model. This distributed model now represents one compartment of “bundle”. This bundle representation is copied Ncompartment times and given as input to a MultiCompartmentModel, where now the nonlinear are all linked such that each bundle has the same convolution kernel. Finally, the FittedSphericalMeanModel parameters are given as fixed parameters for the kernel (the kernel will not be fitted while the FOD’s distribution parameters are being optimized).
The function returns a MultiCompartmentModel instance that can be interacted with as usual to fit dMRI data.
Parameters: distribution: string, :
Choice of parametric spherical distribution. Can be ‘watson’, or ‘bingham’.
Ncompartments: integer, :
Number of bundles that will be fitted. Must be larger than zero.
Returns: mc_bundles_model: Dmipy MultiCompartmentModel instance, :
MultiCompartmentModel instance that can be used to estimate parametric FODs using the fitted spherical mean model as a kernel.

Module: core.gradient_conversions
¶

dmipy.core.gradient_conversions.
q_from_b
(b, delta, Delta)¶ Compute qvalue from bvalue. Units are standard units.

dmipy.core.gradient_conversions.
b_from_q
(q, delta, Delta)¶ Compute bvalue from qvalue. Units are standard units.

dmipy.core.gradient_conversions.
q_from_g
(g, delta, gyromagnetic_ratio=267513000.0)¶ Compute qvalue from gradient strength. Units are standard units.

dmipy.core.gradient_conversions.
g_from_q
(q, delta, gyromagnetic_ratio=267513000.0)¶ Compute gradient strength from qvalue. Units are standard units.

dmipy.core.gradient_conversions.
b_from_g
(g, delta, Delta, gyromagnetic_ratio=267513000.0)¶ Compute bvalue from gradient strength. Units are standard units.

dmipy.core.gradient_conversions.
g_from_b
(b, delta, Delta, gyromagnetic_ratio=267513000.0)¶ Compute gradient strength from bvalue. Units are standard units.
Module: core.modeling_framework
¶
Document Module

class
dmipy.core.modeling_framework.
ModelProperties
¶ Contains various properties for CompartmentModels.
Attributes

parameter_cardinality
¶ Returns the cardinality of model parameters

parameter_names
¶ Returns the names of model parameters.

parameter_ranges
¶ Returns the optimization ranges of the model parameters. These ranges are given in O(1) scale so optimization algorithms don’t suffer from large scale differences in optimization parameters.

parameter_scales
¶ Returns the optimization scales for the model parameters. The scales scale the parameter_ranges to their actual size inside optimization algorithms.

parameter_types
¶ Returns the optimization scales for the model parameters. The scales scale the parameter_ranges to their actual size inside optimization algorithms.


class
dmipy.core.modeling_framework.
MultiCompartmentModelProperties
¶ Class that contains various properties of MultiCompartmentModel instance.
Attributes
Methods

add_linked_parameters_to_parameters
(parameters)¶ When making the MultiCompartmentModel function call, adds the linked parameter to the optimized parameters by evaluating the parameter link function.

bounds_for_optimization
¶ Returns the linear parameter bounds for the model optimization.

opt_params_for_optimization
¶ Returns the linear bools whether to optimize a model parameter.

parameter_initial_guess_to_parameter_vector
(**parameters)¶ Function that returns a parameter_vector while allowing for partial input of model parameters, setting the ones that were not given to ‘None’. Such an array can be given to the fit() function to provide an initial parameter guess when fitting the data to the model.
Parameters: parameters: keyword arguments of parameter names, :
parameter values of only the parameters you want to give as an initial condition for the optimizer.
Returns: parameter_vector: array of size (Ndata_x, Ndata_y, …, Nparameters), :
array that contains the linearized model parameters for an NDarray of data voxels, with None’s for nongiven parameters.

parameter_names
¶ Returns the names of model parameters.

parameter_vector_to_parameters
(parameter_vector)¶ Returns the model parameters in dictionary format according to their parameter_names. Takes parameter_vector as input, which is the same as the output of a FittedMultiCompartmentModel.fitted_parameter_vector.
Parameters: parameter_vector: array of size (Ndata_x, Ndata_y, …, Nparameters), :
array that contains the linearized model parameters for an NDarray of data voxels.
Returns: parameter: dictionary with parameter_names as parameter keys, :
contains the model parameters in dictionary format.

parameters_to_parameter_vector
(**parameters)¶ Returns the model parameters in array format. The input is a parameters dictionary that has parameter_names as keys. This is also the output of a FittedMultiCompartmentModel.fitted_parameters.
It’s possible to give an array of values for one parameter and only a float for others. The function will automatically assume that that the float parameters are constant in the data set and broadcast them accordingly.
The output parameter_vector can be used in simulate_data() to generate data according to the given input parameters.
Parameters: parameters: keyword arguments of parameter_names. :
Can be given as **parameter_dictionary that contains the model parameter values.
Returns: parameter_vector: array of size (Ndata_x, Ndata_y, …, Nparameters), :
array that contains the linearized model parameters for an NDarray of data voxels.

scales_for_optimization
¶ Returns the linear parameter scales for model optimization.

set_equal_parameter
(parameter_name_in, parameter_name_out)¶ Allows the user to set two parameters equal to each other. This is used for example in the NODDI model to set the parallel diffusivities of the Stick and Zeppelin compartment to the same value.
The second input parameter will be removed from the optimized parameters and added as a linked parameter.
Parameters: parameter_name_in: string :
the first parameter name, see self.parameter_names.
parameter_name_out: string, :
the second parameter name, see self.parameter_names. This is the parameter that will be removed form the optimzed parameters.

set_fixed_parameter
(parameter_name, value)¶ Allows the user to fix an optimization parameter to a static value. The fixed parameter will be removed from the optimized parameters and added as a linked parameter.
Parameters: parameter_name: string :
name of the tobefixed parameters, see self.parameter_names.
value: float or list of corresponding parameter_cardinality. :
the value to fix the parameter at in SI units.

set_fractional_parameter
(parameter1_smaller_equal_than, parameter2)¶ Allows to impose a constraint to make one parameter smaller or equal to another parameter. This is done by replacing parameter1 with a new parameter that is defined as a fraction between 0 and 1 of parameter2. The new parameter will be the same as the old parameter name with “_fraction” appended to it.
Parameters: parameter1_smaller_equal_than: string :
parameter name to be made a fraction of parameter2
parameter2: string :
the parameter that is larger or equal than parameter1

set_initial_guess_parameter
(parameter_name, value)¶ Allows the user to fix an optimization parameter to a static value. The fixed parameter will be removed from the optimized parameters and added as a linked parameter.
Parameters: parameter_name: string :
name of the tobefixed parameters, see self.parameter_names.
value: float or list of corresponding parameter_cardinality. :
the value to fix the parameter at in SI units.

set_tortuous_parameter
(lambda_perp_parameter_name, lambda_par_parameter_name, volume_fraction_intra_parameter_name, volume_fraction_extra_parameter_name)¶ Allows the user to set a tortuosity constraint on the perpendicular diffusivity of the extraaxonal compartment, which depends on the intraaxonal volume fraction and parallel diffusivity.
The perpendicular diffusivity parameter will be removed from the optimized parameters and added as a linked parameter.
Parameters: lambda_perp_parameter_name: string :
name of the perpendicular diffusivity parameter, see self.parameter_names.
lambda_par_parameter_name: string :
name of the parallel diffusivity parameter, see self.parameter_names.
volume_fraction_intra_parameter_name: string :
name of the intraaxonal volume fraction parameter, see self.parameter_names.
volume_fraction_extra_parameter_name: string :
name of the extraaxonal volume fraction parameter, see self.parameter_names.


class
dmipy.core.modeling_framework.
MultiCompartmentModel
(models, parameter_links=None)¶ The MultiCompartmentModel class allows to combine any number of CompartmentModels and DistributedModels into one combined model that can be used to fit and simulate dMRI data.
Parameters: models : list of N CompartmentModel instances,
the models to combine into the MultiCompartmentModel.
parameter_links : list of iterables (model, parameter name, link function,
argument list), deprecated, for testing only.
Attributes
Methods

fit
(acquisition_scheme, data, mask=None, solver='brute2fine', Ns=5, maxiter=300, N_sphere_samples=30, use_parallel_processing=False, number_of_processors=None)¶ The main data fitting function of a MultiCompartmentModel.
This function can fit it to an Ndimensional dMRI data set, and returns a FittedMultiCompartmentModel instance that contains the fitted parameters and other useful functions to study the results.
No initial guess needs to be given to fit a model, but a partial or complete initial guess can be given if the user wants to have a solution that is a local minimum close to that guess. The parameter_initial_guess input can be created using parameter_initial_guess_to_parameter_vector().
A mask can also be given to exclude voxels from fitting (e.g. voxels that are outside the brain). If no mask is given then all voxels are included.
An optimization approach can be chosen as either ‘brute2fine’ or ‘mix’.  Choosing brute2fine will first use a bruteforce optimization to find
an initial guess for parameters without one, and will then refine the result using gradientdescentbased optimization.
Note that given no initial guess will make brute2fine precompute an global parameter grid that will be reused for all voxels, which in many cases is much faster than giving voxelvarying initial condition that requires a grid to be estimated per voxel.
 Choosing mix will use the recent MIX algorithm based on separation of linear and nonlinear parameters. MIX first uses a stochastic algorithm to find the nonlinear parameters (nonvolume fractions), then estimates the volume fractions while fixing the estimates of the nonlinear parameters, and then finally refines the solution using a gradientdescentbased algorithm.
The fitting process can be readily parallelized using the optional “pathos” package. If it is installed then it will automatically use it, but it can be turned off by setting use_parallel_processing=False. The algorithm will automatically use all cores in the machine, unless otherwise specified in number_of_processors.
Data with multiple TE are normalized in separate segments using the b0values according that TE.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
data : Ndimensional array of size (N_x, N_y, …, N_dwis),
The measured DWI signal attenuation array of either a single voxel or an Ndimensional dataset.
mask : (N1)dimensional integer/boolean array of size (N_x, N_y, …),
Optional mask of voxels to be included in the optimization.
solver : string,
Selection of optimization algorithm.  ‘brute2fine’ to use bruteforce optimization.  ‘mix’ to use Microstructure Imaging of Crossing (MIX)
optimization.
Ns : integer,
for brute optimization, decised how many steps are sampled for every parameter.
maxiter : integer,
for MIX optimization, how many iterations are allowed.
N_sphere_samples : integer,
for brute optimization, how many spherical orientations are sampled for ‘mu’.
use_parallel_processing : bool,
whether or not to use parallel processing using pathos.
number_of_processors : integer,
number of processors to use for parallel processing. Defaults to the number of processors in the computer according to cpu_count().
Returns: FittedCompartmentModel: class instance that contains fitted parameters, :
Can be used to recover parameters themselves or other useful functions.

simulate_signal
(acquisition_scheme, parameters_array_or_dict)¶ Function to simulate diffusion data for a given acquisition_scheme and model parameters for the MultiCompartmentModel.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy
model_parameters_array : 1D array of size (N_parameters) or
Ndimensional array the same size as the data. The model parameters of the MultiCompartmentModel model.
Returns: E_simulated: 1D array of size (N_parameters) or Ndimensional :
array the same size as x0. The simulated signal of the microstructure model.


class
dmipy.core.modeling_framework.
MultiCompartmentSphericalMeanModel
(models, parameter_links=None)¶ The MultiCompartmentModel class allows to combine any number of CompartmentModels and DistributedModels into one combined model that can be used to fit and simulate dMRI data.
Parameters: models : list of N CompartmentModel instances,
the models to combine into the MultiCompartmentModel.
parameter_links : list of iterables (model, parameter name, link function,
argument list), deprecated, for testing only.
Attributes
Methods

fit
(acquisition_scheme, data, mask=None, solver='brute2fine', Ns=5, maxiter=300, N_sphere_samples=30, use_parallel_processing=False, number_of_processors=None)¶ The main data fitting function of a MultiCompartmentModel.
This function can fit it to an Ndimensional dMRI data set, and returns a FittedMultiCompartmentModel instance that contains the fitted parameters and other useful functions to study the results.
No initial guess needs to be given to fit a model, but a partial or complete initial guess can be given if the user wants to have a solution that is a local minimum close to that guess. The parameter_initial_guess input can be created using parameter_initial_guess_to_parameter_vector().
A mask can also be given to exclude voxels from fitting (e.g. voxels that are outside the brain). If no mask is given then all voxels are included.
An optimization approach can be chosen as either ‘brute2fine’ or ‘mix’.  Choosing brute2fine will first use a bruteforce optimization to find
an initial guess for parameters without one, and will then refine the result using gradientdescentbased optimization.
Note that given no initial guess will make brute2fine precompute an global parameter grid that will be reused for all voxels, which in many cases is much faster than giving voxelvarying initial condition that requires a grid to be estimated per voxel.
 Choosing mix will use the recent MIX algorithm based on separation of linear and nonlinear parameters. MIX first uses a stochastic algorithm to find the nonlinear parameters (nonvolume fractions), then estimates the volume fractions while fixing the estimates of the nonlinear parameters, and then finally refines the solution using a gradientdescentbased algorithm.
The fitting process can be readily parallelized using the optional “pathos” package. If it is installed then it will automatically use it, but it can be turned off by setting use_parallel_processing=False. The algorithm will automatically use all cores in the machine, unless otherwise specified in number_of_processors.
Data with multiple TE are normalized in separate segments using the b0values according that TE.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
data : Ndimensional array of size (N_x, N_y, …, N_dwis),
The measured DWI signal attenuation array of either a single voxel or an Ndimensional dataset.
mask : (N1)dimensional integer/boolean array of size (N_x, N_y, …),
Optional mask of voxels to be included in the optimization.
solver : string,
Selection of optimization algorithm.  ‘brute2fine’ to use bruteforce optimization.  ‘mix’ to use Microstructure Imaging of Crossing (MIX)
optimization.
Ns : integer,
for brute optimization, decised how many steps are sampled for every parameter.
maxiter : integer,
for MIX optimization, how many iterations are allowed.
N_sphere_samples : integer,
for brute optimization, how many spherical orientations are sampled for ‘mu’.
use_parallel_processing : bool,
whether or not to use parallel processing using pathos.
number_of_processors : integer,
number of processors to use for parallel processing. Defaults to the number of processors in the computer according to cpu_count().
Returns: FittedCompartmentModel: class instance that contains fitted parameters, :
Can be used to recover parameters themselves or other useful functions.

simulate_signal
(acquisition_scheme, parameters_array_or_dict)¶ Function to simulate diffusion data for a given acquisition_scheme and model parameters for the MultiCompartmentModel.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy
model_parameters_array : 1D array of size (N_parameters) or
Ndimensional array the same size as the data. The model parameters of the MultiCompartmentModel model.
Returns: E_simulated: 1D array of size (N_parameters) or Ndimensional :
array the same size as x0. The simulated signal of the microstructure model.


class
dmipy.core.modeling_framework.
MultiCompartmentSphericalHarmonicsModel
(models, sh_order=8)¶ The MultiCompartmentModel class allows to combine any number of CompartmentModels and DistributedModels into one combined model that can be used to fit and simulate dMRI data.
Parameters: models : list of N CompartmentModel instances,
the models to combine into the MultiCompartmentModel.
Attributes
Methods

fit
(acquisition_scheme, data, mask=None, solver='cvxpy', unity_constraint=True, use_parallel_processing=False, number_of_processors=None)¶ The main data fitting function of a MultiCompartmentSphericalHarmonicsModel.
This function can fit it to an Ndimensional dMRI data set, and returns a FittedMultiCompartmentModel instance that contains the fitted parameters and other useful functions to study the results.
A mask can also be given to exclude voxels from fitting (e.g. voxels that are outside the brain). If no mask is given then all voxels are included.
The fitting process can be readily parallelized using the optional “pathos” package. If it is installed then it will automatically use it, but it can be turned off by setting use_parallel_processing=False. The algorithm will automatically use all cores in the machine, unless otherwise specified in number_of_processors.
Data with multiple TE are normalized in separate segments using the b0values according that TE.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
data : Ndimensional array of size (N_x, N_y, …, N_dwis),
The measured DWI signal attenuation array of either a single voxel or an Ndimensional dataset.
mask : (N1)dimensional integer/boolean array of size (N_x, N_y, …),
Optional mask of voxels to be included in the optimization.
solver : string,
can only be ‘cvxpy’ at this point for generalpurpose csd optimization using cvxpy [R1].
unity_constraint: bool, :
whether or not to constrain the volume fractions of the FOD to unity.
use_parallel_processing : bool,
whether or not to use parallel processing using pathos.
number_of_processors : integer,
number of processors to use for parallel processing. Defaults to the number of processors in the computer according to cpu_count().
Returns: FittedCompartmentModel: class instance that contains fitted parameters, :
Can be used to recover parameters themselves or other useful functions.
References
[R1] (1, 2) Diamond, Steven, and Stephen Boyd. “CVXPY: A Pythonembedded modeling language for convex optimization.” The Journal of Machine Learning Research 17.1 (2016): 29092913.

simulate_signal
(acquisition_scheme, parameters_array_or_dict)¶ Function to simulate diffusion data for a given acquisition_scheme and model parameters for the MultiCompartmentModel.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy
model_parameters_array : 1D array of size (N_parameters) or
Ndimensional array the same size as the data. The model parameters of the MultiCompartmentModel model.
Returns: E_simulated: 1D array of size (N_parameters) or Ndimensional :
array the same size as x0. The simulated signal of the microstructure model.


dmipy.core.modeling_framework.
homogenize_x0_to_data
(data, x0)¶ Function that checks if data and initial guess x0 are of the same size. If x0 is 1D, it will be tiled to be the same size as data.

class
dmipy.core.modeling_framework.
ReturnFixedValue
(value)¶ Parameter fixing class for parameter links.
Methods
DmipyAcquisitionScheme
¶

class
dmipy.core.acquisition_scheme.
DmipyAcquisitionScheme
(bvalues, gradient_directions, qvalues, gradient_strengths, delta, Delta, TE, min_b_shell_distance, b0_threshold) Class that calculates and contains all information needed to simulate and fit data using microstructure models.
Attributes
Methods

__init__
(bvalues, gradient_directions, qvalues, gradient_strengths, delta, Delta, TE, min_b_shell_distance, b0_threshold)¶

print_acquisition_info
prints a small summary of the acquisition scheme. Is useful to check if the function correctly separated the shells and if the input parameters were given in the right scale.

to_schemefile
(filename) Exports acquisition scheme information in schemefile format, which can be used by the Camino MonteCarlo simulator.
Parameters: filename : string,
location at which to save the schemefile.

visualise_acquisition_G_Delta_rainbow
(Delta_start=None, 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 qtau 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 bvector, with a background of bvalue isolines for reference. It assumes there is only one unique pulse length (small_delta) in the acquisition scheme.
Parameters: Delta_start : float,
optional minimum big_delta that is plotted in seconds
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 taht is plotted in T/m
bval_isolines : array,
optional array of bvalue isolines that are plotted in background given in s/mm^2
alpha_shading : float between [01]
optional shading of the bvalue colors in the background

GradientTable
¶

class
dmipy.core.acquisition_scheme.
GradientTable
(gradients, big_delta=None, small_delta=None, b0_threshold=0)¶ Bases:
object
Diffusion gradient information
Parameters: gradients : array_like (N, 3)
Diffusion gradients. The direction of each of these vectors corresponds to the bvector, and the length corresponds to the bvalue.
b0_threshold : float
Gradients with bvalue less than or equal to b0_threshold are considered as b0s i.e. without diffusion weighting.
See also
Notes
The GradientTable object is immutable. Do NOT assign attributes. If you have your gradient table in a bval & bvec format, we recommend using the factory function gradient_table
Attributes
gradients (N,3) ndarray diffusion gradients qvals: (N,) ndarray The qvalue for each gradient direction. Needs big and small delta. b0_threshold float Gradients with bvalue less than or equal to b0_threshold are considered to not have diffusion weighting. Methods

__init__
(gradients, big_delta=None, small_delta=None, b0_threshold=0)¶ Constructor for GradientTable class

b0s_mask
()¶

bvals
()¶

bvecs
()¶

info
¶

qvals
()¶

RotationalHarmonicsAcquisitionScheme
¶

class
dmipy.core.acquisition_scheme.
RotationalHarmonicsAcquisitionScheme
(dmipy_acquisition_scheme, N_angular_samples=10) AcquisitionScheme instance that contains the information necessary to calculate the rotational harmonics for a model for every acquisition shell. It is instantiated using a regular DmipyAcquisitionScheme and N_angular_samples determines how many samples are taken between mu=[0., 0.] and mu=[np.pi/2, 0.].
Parameters: dmipy_acquisition_scheme: DmipyAcquisitionScheme instance :
An acquisition scheme that has been instantiated using dMipy.
N_angular_samples: int :
Integer representing the number of angular samples per shell.

__init__
(dmipy_acquisition_scheme, N_angular_samples=10)¶

SphericalMeanAcquisitionScheme
¶

class
dmipy.core.acquisition_scheme.
SphericalMeanAcquisitionScheme
(bvalues, qvalues, gradient_strengths, Deltas, deltas) Acquisition scheme for isotropic spherical mean models.

__init__
(bvalues, qvalues, gradient_strengths, Deltas, deltas)¶

acquisition_scheme_from_bvalues¶

dmipy.core.acquisition_scheme.
acquisition_scheme_from_bvalues
(bvalues, gradient_directions, delta, Delta, TE=None, min_b_shell_distance=50000000.0, b0_threshold=10000000.0) Creates an acquisition scheme object from bvalues, gradient directions, pulse duration \(\delta\) and pulse separation time \(\Delta\).
Parameters: bvalues: 1D numpy array of shape (Ndata) :
bvalues of the acquisition in s/m^2. e.g., a bvalue of 1000 s/mm^2 must be entered as 1000 * 1e6 s/m^2
gradient_directions: 2D numpy array of shape (Ndata, 3) :
gradient directions array of cartesian unit vectors.
delta: float or 1D numpy array of shape (Ndata) :
if float, pulse duration of every measurements in seconds. if array, potentially varying pulse duration per measurement.
Delta: float or 1D numpy array of shape (Ndata) :
if float, pulse separation time of every measurements in seconds. if array, potentially varying pulse separation time per measurement.
min_b_shell_distance : float
minimum bvalue distance between different shells. This parameter is used to separate measurements into different shells, which is necessary for any model using spherical convolution or spherical mean.
b0_threshold : float
bvalue threshold for a measurement to be considered a b0 measurement.
Returns: DmipyAcquisitionScheme: acquisition scheme object :
contains all information of the acquisition scheme to be used in any microstructure model.
acquisition_scheme_from_gradient_strengths¶

dmipy.core.acquisition_scheme.
acquisition_scheme_from_gradient_strengths
(gradient_strengths, gradient_directions, delta, Delta, TE=None, min_b_shell_distance=50000000.0, b0_threshold=10000000.0) Creates an acquisition scheme object from gradient strengths, gradient directions pulse duration \(\delta\) and pulse separation time \(\Delta\).
Parameters: gradient_strengths: 1D numpy array of shape (Ndata) :
gradient strength of the acquisition in T/m. e.g., a gradient strength of 300 mT/m must be entered as 300 / 1e3 T/m
gradient_directions: 2D numpy array of shape (Ndata, 3) :
gradient directions array of cartesian unit vectors.
delta: float or 1D numpy array of shape (Ndata) :
if float, pulse duration of every measurements in seconds. if array, potentially varying pulse duration per measurement.
Delta: float or 1D numpy array of shape (Ndata) :
if float, pulse separation time of every measurements in seconds. if array, potentially varying pulse separation time per measurement.
min_b_shell_distance : float
minimum bvalue distance between different shells. This parameter is used to separate measurements into different shells, which is necessary for any model using spherical convolution or spherical mean.
b0_threshold : float
bvalue threshold for a measurement to be considered a b0 measurement.
Returns: DmipyAcquisitionScheme: acquisition scheme object :
contains all information of the acquisition scheme to be used in any microstructure model.
acquisition_scheme_from_qvalues¶

dmipy.core.acquisition_scheme.
acquisition_scheme_from_qvalues
(qvalues, gradient_directions, delta, Delta, TE=None, min_b_shell_distance=50000000.0, b0_threshold=10000000.0) Creates an acquisition scheme object from qvalues, gradient directions, pulse duration \(\delta\) and pulse separation time \(\Delta\).
Parameters: qvalues: 1D numpy array of shape (Ndata) :
diffusion sensitization of the acquisition in 1/m. e.g. a qvalue of 10 1/mm must be entered as 10 * 1e3 1/m
gradient_directions: 2D numpy array of shape (Ndata, 3) :
gradient directions array of cartesian unit vectors.
delta: float or 1D numpy array of shape (Ndata) :
if float, pulse duration of every measurements in seconds. if array, potentially varying pulse duration per measurement.
Delta: float or 1D numpy array of shape (Ndata) :
if float, pulse separation time of every measurements in seconds. if array, potentially varying pulse separation time per measurement.
min_b_shell_distance : float
minimum bvalue distance between different shells. This parameter is used to separate measurements into different shells, which is necessary for any model using spherical convolution or spherical mean.
b0_threshold : float
bvalue threshold for a measurement to be considered a b0 measurement.
Returns: DmipyAcquisitionScheme: acquisition scheme object :
contains all information of the acquisition scheme to be used in any microstructure model.
acquisition_scheme_from_schemefile¶

dmipy.core.acquisition_scheme.
acquisition_scheme_from_schemefile
(file_path, min_b_shell_distance=50000000.0, b0_threshold=10000000.0) Created an acquisition scheme object from a Camino scheme file, containing gradient directions, strengths, pulse duration \(\delta\) and pulse separation time \(\Delta\) and TE.
Parameters: file_path: string :
absolute file path to schemefile location
Returns: DmipyAcquisitionScheme: acquisition scheme object :
contains all information of the acquisition scheme to be used in any microstructure model.
b_from_g¶

dmipy.core.acquisition_scheme.
b_from_g
(g, delta, Delta, gyromagnetic_ratio=267513000.0)¶ Compute bvalue from gradient strength. Units are standard units.
b_from_q¶

dmipy.core.acquisition_scheme.
b_from_q
(q, delta, Delta)¶ Compute bvalue from qvalue. Units are standard units.
calculate_shell_bvalues_and_indices¶

dmipy.core.acquisition_scheme.
calculate_shell_bvalues_and_indices
(bvalues, max_distance=20000000.0) Calculates which measurements belong to different acquisition shells. It uses scipy’s linkage clustering algorithm, which uses the max_distance input as a limit of including measurements in the same cluster.
For example, if bvalues were [1, 2, 3, 4, 5] and max_distance was 1, then all bvalues would belong to the same cluster. However, if bvalues were [1, 2, 4, 5] max max_distance was 1, then this would result in 2 clusters.
Parameters: bvalues: 1D numpy array of shape (Ndata) :
bvalues of the acquisition in s/m^2.
max_distance: float :
maximum bvalue distance for a measurement to be included in the same shell.
Returns: shell_indices: 1D numpy array of shape (Ndata) :
array of integers, starting from 0, representing to which shell a measurement belongs. The number itself has no meaning other than just being different for different shells.
shell_bvalues: 1D numpy array of shape (Nshells) :
array of the mean bvalues for every acquisition shell.
check_acquisition_scheme¶

dmipy.core.acquisition_scheme.
check_acquisition_scheme
(bqg_values, gradient_directions, delta, Delta, TE) function to check the validity of the input parameters.
fcluster¶

dmipy.core.acquisition_scheme.
fcluster
(Z, t, criterion='inconsistent', depth=2, R=None, monocrit=None)¶ Form flat clusters from the hierarchical clustering defined by the given linkage matrix.
Parameters: Z : ndarray
The hierarchical clustering encoded with the matrix returned by the linkage function.
t : float
The threshold to apply when forming flat clusters.
criterion : str, optional
The criterion to use in forming flat clusters. This can be any of the following values:
inconsistent
: If a cluster node and all itsdescendants have an inconsistent value less than or equal to t then all its leaf descendants belong to the same flat cluster. When no nonsingleton cluster meets this criterion, every node is assigned to its own cluster. (Default)
distance
: Forms flat clusters so that the originalobservations in each flat cluster have no greater a cophenetic distance than t.
maxclust
: Finds a minimum thresholdr
so thatthe cophenetic distance between any two original observations in the same flat cluster is no more than
r
and no more than t flat clusters are formed.monocrit
: Forms a flat cluster from a cluster node cwith index i when
monocrit[j] <= t
.For example, to threshold on the maximum mean distance as computed in the inconsistency matrix R with a threshold of 0.8 do:
MR = maxRstat(Z, R, 3) cluster(Z, t=0.8, criterion='monocrit', monocrit=MR)
maxclust_monocrit
: Forms a flat cluster from anonsingleton cluster node
c
whenmonocrit[i] <= r
for all cluster indicesi
below and includingc
.r
is minimized such that no more thant
flat clusters are formed. monocrit must be monotonic. For example, to minimize the threshold t on maximum inconsistency values so that no more than 3 flat clusters are formed, do:MI = maxinconsts(Z, R) cluster(Z, t=3, criterion='maxclust_monocrit', monocrit=MI)
depth : int, optional
The maximum depth to perform the inconsistency calculation. It has no meaning for the other criteria. Default is 2.
R : ndarray, optional
The inconsistency matrix to use for the ‘inconsistent’ criterion. This matrix is computed if not provided.
monocrit : ndarray, optional
An array of length n1. monocrit[i] is the statistics upon which nonsingleton i is thresholded. The monocrit vector must be monotonic, i.e. given a node c with index i, for all node indices j corresponding to nodes below c,
monocrit[i] >= monocrit[j]
.Returns: fcluster : ndarray
An array of length
n
.T[i]
is the flat cluster number to which original observationi
belongs.
g_from_b¶

dmipy.core.acquisition_scheme.
g_from_b
(b, delta, Delta, gyromagnetic_ratio=267513000.0)¶ Compute gradient strength from bvalue. Units are standard units.
g_from_q¶

dmipy.core.acquisition_scheme.
g_from_q
(q, delta, gyromagnetic_ratio=267513000.0)¶ Compute gradient strength from qvalue. Units are standard units.
get_sh_order_from_bval¶

dmipy.core.acquisition_scheme.
get_sh_order_from_bval
(bval) Estimates minimum sh_order to represent data of given bvalue.
gradient_table¶

dmipy.core.acquisition_scheme.
gradient_table
(bvals, bvecs=None, big_delta=None, small_delta=None, b0_threshold=0, atol=0.01)¶ A general function for creating diffusion MR gradients.
It reads, loads and prepares scanner parameters like the bvalues and bvectors so that they can be useful during the reconstruction process.
Parameters: bvals : can be any of the four options
 an array of shape (N,) or (1, N) or (N, 1) with the bvalues.
 a path for the file which contains an array like the above (1).
 an array of shape (N, 4) or (4, N). Then this parameter is considered to be a btable which contains both bvals and bvecs. In this case the next parameter is skipped.
 a path for the file which contains an array like the one at (3).
bvecs : can be any of two options
 an array of shape (N, 3) or (3, N) with the bvectors.
 a path for the file which contains an array like the previous.
big_delta : float
acquisition timing duration (default None)
small_delta : float
acquisition timing duration (default None)
b0_threshold : float
All bvalues with values less than or equal to bo_threshold are considered as b0s i.e. without diffusion weighting.
atol : float
All bvectors need to be unit vectors up to a tolerance.
Returns: gradients : GradientTable
A GradientTable with all the gradient information.
Notes
 Often b0s (bvalues which correspond to images without diffusion weighting) have 0 values however in some cases the scanner cannot provide b0s of an exact 0 value and it gives a bit higher values e.g. 6 or 12. This is the purpose of the b0_threshold in the __init__.
 We assume that the minimum number of bvalues is 7.
 Bvectors should be unit vectors.
Examples
>>> from dipy.core.gradients import gradient_table >>> bvals=1500*np.ones(7) >>> bvals[0]=0 >>> sq2=np.sqrt(2)/2 >>> bvecs=np.array([[0, 0, 0], ... [1, 0, 0], ... [0, 1, 0], ... [0, 0, 1], ... [sq2, sq2, 0], ... [sq2, 0, sq2], ... [0, sq2, sq2]]) >>> gt = gradient_table(bvals, bvecs) >>> gt.bvecs.shape == bvecs.shape True >>> gt = gradient_table(bvals, bvecs.T) >>> gt.bvecs.shape == bvecs.T.shape False
gtab_dipy2mipy¶

dmipy.core.acquisition_scheme.
gtab_dipy2mipy
(dipy_gradient_table) Converts a dipy gradient_table to a dmipy acquisition_scheme.
gtab_mipy2dipy¶

dmipy.core.acquisition_scheme.
gtab_mipy2dipy
(dmipy_gradient_table) Converts a dmipy acquisition scheme to a dipy gradient_table.
linkage¶

dmipy.core.acquisition_scheme.
linkage
(y, method='single', metric='euclidean', optimal_ordering=False)¶ Perform hierarchical/agglomerative clustering.
The input y may be either a 1d compressed distance matrix or a 2d array of observation vectors.
If y is a 1d compressed distance matrix, then y must be a \({n \choose 2}\) sized vector where n is the number of original observations paired in the distance matrix. The behavior of this function is very similar to the MATLAB linkage function.
A \((n1)\) by 4 matrix
Z
is returned. At the \(i\)th iteration, clusters with indicesZ[i, 0]
andZ[i, 1]
are combined to form cluster \(n + i\). A cluster with an index less than \(n\) corresponds to one of the \(n\) original observations. The distance between clustersZ[i, 0]
andZ[i, 1]
is given byZ[i, 2]
. The fourth valueZ[i, 3]
represents the number of original observations in the newly formed cluster.The following linkage methods are used to compute the distance \(d(s, t)\) between two clusters \(s\) and \(t\). The algorithm begins with a forest of clusters that have yet to be used in the hierarchy being formed. When two clusters \(s\) and \(t\) from this forest are combined into a single cluster \(u\), \(s\) and \(t\) are removed from the forest, and \(u\) is added to the forest. When only one cluster remains in the forest, the algorithm stops, and this cluster becomes the root.
A distance matrix is maintained at each iteration. The
d[i,j]
entry corresponds to the distance between cluster \(i\) and \(j\) in the original forest.At each iteration, the algorithm must update the distance matrix to reflect the distance of the newly formed cluster u with the remaining clusters in the forest.
Suppose there are \(u\) original observations \(u[0], \ldots, u[u1]\) in cluster \(u\) and \(v\) original objects \(v[0], \ldots, v[v1]\) in cluster \(v\). Recall \(s\) and \(t\) are combined to form cluster \(u\). Let \(v\) be any remaining cluster in the forest that is not \(u\).
The following are methods for calculating the distance between the newly formed cluster \(u\) and each \(v\).
method=’single’ assigns
\[d(u,v) = \min(dist(u[i],v[j]))\]for all points \(i\) in cluster \(u\) and \(j\) in cluster \(v\). This is also known as the Nearest Point Algorithm.
method=’complete’ assigns
\[d(u, v) = \max(dist(u[i],v[j]))\]for all points \(i\) in cluster u and \(j\) in cluster \(v\). This is also known by the Farthest Point Algorithm or Voor Hees Algorithm.
method=’average’ assigns
\[d(u,v) = \sum_{ij} \frac{d(u[i], v[j])} {(u*v)}\]for all points \(i\) and \(j\) where \(u\) and \(v\) are the cardinalities of clusters \(u\) and \(v\), respectively. This is also called the UPGMA algorithm.
method=’weighted’ assigns
\[d(u,v) = (dist(s,v) + dist(t,v))/2\]where cluster u was formed with cluster s and t and v is a remaining cluster in the forest. (also called WPGMA)
method=’centroid’ assigns
\[dist(s,t) = c_sc_t_2\]where \(c_s\) and \(c_t\) are the centroids of clusters \(s\) and \(t\), respectively. When two clusters \(s\) and \(t\) are combined into a new cluster \(u\), the new centroid is computed over all the original objects in clusters \(s\) and \(t\). The distance then becomes the Euclidean distance between the centroid of \(u\) and the centroid of a remaining cluster \(v\) in the forest. This is also known as the UPGMC algorithm.
method=’median’ assigns \(d(s,t)\) like the
centroid
method. When two clusters \(s\) and \(t\) are combined into a new cluster \(u\), the average of centroids s and t give the new centroid \(u\). This is also known as the WPGMC algorithm.method=’ward’ uses the Ward variance minimization algorithm. The new entry \(d(u,v)\) is computed as follows,
\[d(u,v) = \sqrt{\frac{v+s} {T}d(v,s)^2 + \frac{v+t} {T}d(v,t)^2  \frac{v} {T}d(s,t)^2}\]where \(u\) is the newly joined cluster consisting of clusters \(s\) and \(t\), \(v\) is an unused cluster in the forest, \(T=v+s+t\), and \(*\) is the cardinality of its argument. This is also known as the incremental algorithm.
Warning: When the minimum distance pair in the forest is chosen, there may be two or more pairs with the same minimum distance. This implementation may choose a different minimum than the MATLAB version.
Parameters: y : ndarray
A condensed distance matrix. A condensed distance matrix is a flat array containing the upper triangular of the distance matrix. This is the form that
pdist
returns. Alternatively, a collection of \(m\) observation vectors in \(n\) dimensions may be passed as an \(m\) by \(n\) array. All elements of the condensed distance matrix must be finite, i.e. no NaNs or infs.method : str, optional
The linkage algorithm to use. See the
Linkage Methods
section below for full descriptions.metric : str or function, optional
The distance metric to use in the case that y is a collection of observation vectors; ignored otherwise. See the
pdist
function for a list of valid distance metrics. A custom distance function can also be used.optimal_ordering : bool, optional
If True, the linkage matrix will be reordered so that the distance between successive leaves is minimal. This results in a more intuitive tree structure when the data are visualized. defaults to False, because this algorithm can be slow, particularly on large datasets [R3]. See also the optimal_leaf_ordering function.
New in version 1.0.0.
Returns: Z : ndarray
The hierarchical clustering encoded as a linkage matrix.
See also
scipy.spatial.distance.pdist
 pairwise distance metrics
Notes
 For method ‘single’ an optimized algorithm based on minimum spanning tree is implemented. It has time complexity \(O(n^2)\). For methods ‘complete’, ‘average’, ‘weighted’ and ‘ward’ an algorithm called nearestneighbors chain is implemented. It also has time complexity \(O(n^2)\). For other methods a naive algorithm is implemented with \(O(n^3)\) time complexity. All algorithms use \(O(n^2)\) memory. Refer to [R2] for details about the algorithms.
 Methods ‘centroid’, ‘median’ and ‘ward’ are correctly defined only if Euclidean pairwise metric is used. If y is passed as precomputed pairwise distances, then it is a user responsibility to assure that these distances are in fact Euclidean, otherwise the produced result will be incorrect.
References
[R2] (1, 2) Daniel Mullner, “Modern hierarchical, agglomerative clustering algorithms”, :arXiv:`1109.2378v1`. [R3] (1, 2) Ziv BarJoseph, David K. Gifford, Tommi S. Jaakkola, “Fast optimal leaf ordering for hierarchical clustering”, 2001. Bioinformatics https://doi.org/10.1093/bioinformatics/17.suppl_1.S22 Examples
>>> from scipy.cluster.hierarchy import dendrogram, linkage >>> from matplotlib import pyplot as plt >>> X = [[i] for i in [2, 8, 0, 4, 1, 9, 9, 0]]
>>> Z = linkage(X, 'ward') >>> fig = plt.figure(figsize=(25, 10)) >>> dn = dendrogram(Z)
>>> Z = linkage(X, 'single') >>> fig = plt.figure(figsize=(25, 10)) >>> dn = dendrogram(Z) >>> plt.show()
q_from_b¶

dmipy.core.acquisition_scheme.
q_from_b
(b, delta, Delta)¶ Compute qvalue from bvalue. Units are standard units.
q_from_g¶

dmipy.core.acquisition_scheme.
q_from_g
(g, delta, gyromagnetic_ratio=267513000.0)¶ Compute qvalue from gradient strength. Units are standard units.
real_sym_rh_basis¶

dmipy.core.acquisition_scheme.
real_sym_rh_basis
(sh_order, theta, phi)¶ Samples a real symmetric rotational harmonic basis at point on the sphere
Samples the basis functions up to order sh_order at points on the sphere given by theta and phi. The basis functions are defined here the same way as in fibernavigator, where the real harmonic \(Y^m_n\) is defined to be:
\(Y^0_n\) if m = 0Parameters: sh_order : int
even int > 0, max spherical harmonic degree
theta : float [0, 2*pi]
The azimuthal (longitudinal) coordinate.
phi : float [0, pi]
The polar (colatitudinal) coordinate.
Returns: real_rh_matrix : array of shape ()
The real harmonic \(Y^0_n\) sampled at theta and phi
real_sym_sh_mrtrix¶

dmipy.core.acquisition_scheme.
real_sym_sh_mrtrix
(sh_order, theta, phi)¶ Compute real spherical harmonics as in mrtrix, where the real harmonic \(Y^m_n\) is defined to be:
Real(:math:`Y^m_n`) if m > 0 :math:`Y^0_n` if m = 0 Imag(:math:`Y^m_n`) if m < 0
This may take scalar or array arguments. The inputs will be broadcasted against each other.
Parameters: sh_order : int
The maximum degree or the spherical harmonic basis.
theta : float [0, pi]
The polar (colatitudinal) coordinate.
phi : float [0, 2*pi]
The azimuthal (longitudinal) coordinate.
Returns: y_mn : real float
The real harmonic \(Y^m_n\) sampled at theta and phi as implemented in mrtrix. Warning: the basis is Tournier et al 2004 and 2007 is slightly different.
m : array
The order of the harmonics.
n : array
The degree of the harmonics.
unify_length_reference_delta_Delta¶

dmipy.core.acquisition_scheme.
unify_length_reference_delta_Delta
(reference_array, delta, Delta, TE) If either delta or Delta are given as float, makes them an array the same size as the reference array.
Parameters: reference_array : array of size (Nsamples)
typically bvalues, qvalues or gradient strengths.
delta : float or array of size (Nsamples)
pulse duration in seconds.
Delta : float or array of size (Nsamples)
pulse separation in seconds.
TE : None, float or array of size (Nsamples)
Echo time of the acquisition in seconds.
Returns: delta_ : array of size (Nsamples)
pulse duration copied to be same size as reference_array
Delta_ : array of size (Nsamples)
pulse separation copied to be same size as reference_array
TE_ : None or array of size (Nsamples)
Echo time copied to be same size as reference_array
warn¶

dmipy.core.acquisition_scheme.
warn
()¶ Issue a warning, or maybe ignore it or raise an exception.
FittedMultiCompartmentModel
¶

class
dmipy.core.fitted_modeling_framework.
FittedMultiCompartmentModel
(model, S0, mask, fitted_parameters_vector) The FittedMultiCompartmentModel instance contains information about the original MultiCompartmentModel, the estimated S0 values, the fitting mask and the fitted model parameters.
Parameters: model : MultiCompartmentModel instance,
A dmipy MultiCompartmentModel.
S0 : array of size (Ndata,) or (N_data, N_DWIs),
Array containing the estimated S0 values of the data. If data is 4D, then S0 is 3D if there is only one TE, and the same 4D size of the data if there are multiple TEs.
mask : array of size (N_data,),
boolean mask of voxels that were fitted.
fitted_parameters_vector : array of size (N_data, Nparameters),
fitted model parameters array.
Attributes
Methods

__init__
(model, S0, mask, fitted_parameters_vector)¶

R2_coefficient_of_determination
(data) Calculates the Rsquared of the model fit.

fitted_and_linked_parameters
Returns the fitted and linked parameters as a dictionary.

fitted_parameters
Returns the fitted parameters as a dictionary.

fod
(vertices, visual_odi_lower_bound=0.0) Returns the Fiber Orientation Distribution if it is available.
Parameters: vertices : array of size (Nvertices, 3),
Array of cartesian unit vectors at which to sample the FOD.
visual_odi_lower_bound : float,
gives a lower bound to the Orientation Distribution Index (ODI) of FODs of Watson and Bingham distributions. This can be useful to visualize FOD fields where some FODs are extremely sharp.
Returns: fods : array of size (Ndata, Nvertices),
the FODs of the fitted model, scaled by volume fraction.

fod_sh
(sh_order=8, basis_type=None) Returns the spherical harmonics coefficients of the Fiber Orientation Distribution (FOD) if it is available. Uses are 724 spherical tessellation to do the spherical harmonics transform.
Parameters: sh_order : integer,
the maximum spherical harmonics order of the coefficient expansion.
basis_type : string,
type of spherical harmonics basis to use for the expansion, see sh_to_sf_matrix for more info.
Returns: fods_sh : array of size (Ndata, Ncoefficients),
spherical harmonics coefficients of the FODs, scaled by volume fraction.

mean_squared_error
(data) Calculates the mean squared error of the model fit.

peaks_cartesian
() Returns the cartesian peak unit vectors of the model.

peaks_spherical
() Returns the peak angles of the model.

predict
(acquisition_scheme=None, S0=None, mask=None) simulates the dMRI signal of the fitted MultiCompartmentModel for the estimated model parameters. If no acquisition_scheme is given, then the same acquisition_scheme that was used for the fitting is used. If no S0 is given then it is assumed to be the estimated one. If no mask is given then all voxels are assumed to have been fitted.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
S0 : None or float,
Signal intensity without diffusion sensitization. If None, uses estimated SO from fitting process. If float, uses that value.
mask : (N1)dimensional integer/boolean array of size (N_x, N_y, …),
mask of voxels to simulate data at.
Returns: predicted_signal : array of size (Ndata, N_DWIS),
predicted DWIs for the given model parameters and acquisition scheme.

FittedMultiCompartmentSphericalHarmonicsModel
¶

class
dmipy.core.fitted_modeling_framework.
FittedMultiCompartmentSphericalHarmonicsModel
(model, S0, mask, fitted_parameters_vector)¶ The FittedMultiCompartmentModel instance contains information about the original MultiCompartmentModel, the estimated S0 values, the fitting mask and the fitted model parameters.
Parameters: model : MultiCompartmentModel instance,
A dmipy MultiCompartmentModel.
S0 : array of size (Ndata,) or (N_data, N_DWIs),
Array containing the estimated S0 values of the data. If data is 4D, then S0 is 3D if there is only one TE, and the same 4D size of the data if there are multiple TEs.
mask : array of size (N_data,),
boolean mask of voxels that were fitted.
fitted_parameters_vector : array of size (N_data, Nparameters),
fitted model parameters array.
Attributes
Methods

__init__
(model, S0, mask, fitted_parameters_vector)¶

R2_coefficient_of_determination
(data)¶ Calculates the Rsquared of the model fit.

anisotropy_index
()¶ Estimates anisotropy index of spherical harmonics [R4].
References
[R4] (1, 2) Jespersen, Sune N., et al. “Modeling dendrite density from magnetic resonance diffusion measurements.” Neuroimage 34.4 (2007): 14731486.

fitted_and_linked_parameters
¶ Returns the fitted and linked parameters as a dictionary.

fitted_parameters
¶ Returns the fitted parameters as a dictionary.

fod
(vertices)¶ Returns the Fiber Orientation Distribution if it is available.
Parameters: vertices : array of size (Nvertices, 3),
Array of cartesian unit vectors at which to sample the FOD.
visual_odi_lower_bound : float,
gives a lower bound to the Orientation Distribution Index (ODI) of FODs of Watson and Bingham distributions. This can be useful to visualize FOD fields where some FODs are extremely sharp.
Returns: fods : array of size (Ndata, Nvertices),
the FODs of the fitted model, scaled by volume fraction.

fod_sh
()¶ Returns the spherical harmonics coefficients of the Fiber Orientation Distribution (FOD) if it is available. Uses are 724 spherical tessellation to do the spherical harmonics transform.
Parameters: sh_order : integer,
the maximum spherical harmonics order of the coefficient expansion.
basis_type : string,
type of spherical harmonics basis to use for the expansion, see sh_to_sf_matrix for more info.
Returns: fods_sh : array of size (Ndata, Ncoefficients),
spherical harmonics coefficients of the FODs, scaled by volume fraction.

mean_squared_error
(data)¶ Calculates the mean squared error of the model fit.

predict
(acquisition_scheme=None, S0=None, mask=None)¶ simulates the dMRI signal of the fitted MultiCompartmentModel for the estimated model parameters. If no acquisition_scheme is given, then the same acquisition_scheme that was used for the fitting is used. If no S0 is given then it is assumed to be the estimated one. If no mask is given then all voxels are assumed to have been fitted.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
S0 : None or float,
Signal intensity without diffusion sensitization. If None, uses estimated SO from fitting process. If float, uses that value.
mask : (N1)dimensional integer/boolean array of size (N_x, N_y, …),
mask of voxels to simulate data at.
Returns: predicted_signal : array of size (Ndata, N_DWIS),
predicted DWIs for the given model parameters and acquisition scheme.

FittedMultiCompartmentSphericalMeanModel
¶

class
dmipy.core.fitted_modeling_framework.
FittedMultiCompartmentSphericalMeanModel
(model, S0, mask, fitted_parameters_vector) The FittedMultiCompartmentModel instance contains information about the original MultiCompartmentModel, the estimated S0 values, the fitting mask and the fitted model parameters.
Parameters: model : MultiCompartmentModel instance,
A dmipy MultiCompartmentModel.
S0 : array of size (Ndata,) or (N_data, N_DWIs),
Array containing the estimated S0 values of the data. If data is 4D, then S0 is 3D if there is only one TE, and the same 4D size of the data if there are multiple TEs.
mask : array of size (N_data,),
boolean mask of voxels that were fitted.
fitted_parameters_vector : array of size (N_data, Nparameters),
fitted model parameters array.
Attributes
Methods

__init__
(model, S0, mask, fitted_parameters_vector)¶

R2_coefficient_of_determination
(data) Calculates the Rsquared of the model fit.

fitted_and_linked_parameters
Returns the fitted and linked parameters as a dictionary.

fitted_parameters
Returns the fitted parameters as a dictionary.

mean_squared_error
(data) Calculates the mean squared error of the model fit.

predict
(acquisition_scheme=None, S0=None, mask=None) simulates the dMRI signal of the fitted MultiCompartmentModel for the estimated model parameters. If no acquisition_scheme is given, then the same acquisition_scheme that was used for the fitting is used. If no S0 is given then it is assumed to be the estimated one. If no mask is given then all voxels are assumed to have been fitted.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
S0 : None or float,
Signal intensity without diffusion sensitization. If None, uses estimated SO from fitting process. If float, uses that value.
mask : (N1)dimensional integer/boolean array of size (N_x, N_y, …),
mask of voxels to simulate data at.
Returns: predicted_signal : array of size (Ndata, N_DWIS),
predicted DWIs for the given model parameters and acquisition scheme.

return_parametric_fod_model
(distribution='watson', Ncompartments=1) Retuns parametric FOD model using the rotational harmonics of the fitted spherical mean model as the convolution kernel. It can be called with any implemented parametric distribution (Watson/Bingham) and for any number of compartments.
Internally, the input models to the spherical mean model are given to a spherically distributed model where the parameter links are replayed such that the distributed model has the same parameter constraints as the spherical mean model. This distributed model now represents one compartment of “bundle”. This bundle representation is copied Ncompartment times and given as input to a MultiCompartmentModel, where now the nonlinear are all linked such that each bundle has the same convolution kernel. Finally, the FittedSphericalMeanModel parameters are given as fixed parameters for the kernel (the kernel will not be fitted while the FOD’s distribution parameters are being optimized).
The function returns a MultiCompartmentModel instance that can be interacted with as usual to fit dMRI data.
Parameters: distribution: string, :
Choice of parametric spherical distribution. Can be ‘watson’, or ‘bingham’.
Ncompartments: integer, :
Number of bundles that will be fitted. Must be larger than zero.
Returns: mc_bundles_model: Dmipy MultiCompartmentModel instance, :
MultiCompartmentModel instance that can be used to estimate parametric FODs using the fitted spherical mean model as a kernel.

T1_tortuosity¶

dmipy.core.fitted_modeling_framework.
T1_tortuosity
(lambda_par, vf_intra, vf_extra=None)¶ Tortuosity model for perpendicular extraaxonal diffusivity [1, 2, 3]. If vf_extra=None, then vf_intra must be a nested volume fraction, in the sense that E_bundle = vf_intra * E_intra + (1  vf_intra) * E_extra, with vf_intra + (1  vf_intra) = 1. If both vf_intra and vf_extra are given, then they have be be normalized fractions, in the sense that vf_intra + vf_extra <= 1.
Parameters: lambda_par : float,
parallel diffusivity.
vf_intra : float,
intraaxonal volume fraction [0, 1].
vf_extra : float, (optional)
extraaxonal volume fraction [0, 1].
Returns: lambda_perp : float,
Rotation matrix.
References :
—— :
.. [1] Bruggeman, Von DAG. “Berechnung verschiedener physikalischer :
Konstanten von heterogenen Substanzen. I. Dielektrizitätskonstanten und Leitfähigkeiten der Mischkörper aus isotropen Substanzen.” Annalen der physik 416.7 (1935): 636664.
.. [2] Sen et al. “A selfsimilar model for sedimentary rocks with :
application to the dielectric constant of fused glass beads.” Geophysics 46.5 (1981): 781795.
.. [3] Szafer et al. “Theoretical model for water diffusion in tissues.” :
Magnetic resonance in medicine 33.5 (1995): 697712.
cart2mu¶

dmipy.core.fitted_modeling_framework.
cart2mu
(xyz)¶ Function to estimate spherical coordinates from cartesian coordinates according to wikipedia. Conforms with the dipy notation.
Parameters: cartesian_coordinates : array of size (3) or (N x 3),
array of cartesian coordinate vectors [x, y, z].
Returns: spherical_coordinates : array of size (2) or (N x 2),
array of spherical coordinate vectors [theta, phi]. range of theta [0, pi]. range of phi [pi, pi].
estimate_spherical_mean_multi_shell¶

dmipy.core.fitted_modeling_framework.
estimate_spherical_mean_multi_shell
(E_attenuation, acquisition_scheme, sh_order=6)¶ Estimates the spherical mean per shell of multishell acquisition. Uses spherical harmonics to do the estimation.
Parameters: E_attenuation : array, shape (N),
signal attenuation.
bvecs : array, shape (N x 3),
x, y, z components of cartesian unit bvectors.
b_shell_indices : array, shape (N)
array of integers indicating which measurement belongs to which shell. 0 should be used for b0 measurements, 1 for the lowest bvalue shell, 2 for the second lowest etc.
Returns: E_mean : array, shape (number of bshells)
spherical means of the signal attenuation per shell of the. For example, if there are three shells in the acquisition then the array is of length 3.
fractional_parameter¶

dmipy.core.fitted_modeling_framework.
fractional_parameter
(fractional_parameter, parameter2)¶ Defines fractional parameter link where the original parameter ranges between 01 of parameter2.
Parameters: fractional_parameter : string
new parameter that ranges between 0 and 1.
parameter2 : string
parameter that is larger or equal than the original parameter
get_sphere¶

dmipy.core.fitted_modeling_framework.
get_sphere
(name='symmetric362')¶ provide triangulated spheres
Parameters: name : str
which sphere  one of: * ‘symmetric362’ * ‘symmetric642’ * ‘symmetric724’ * ‘repulsion724’ * ‘repulsion100’ * ‘repulsion200’
Returns: sphere : a dipy.core.sphere.Sphere class instance
Examples
>>> import numpy as np >>> from dipy.data import get_sphere >>> sphere = get_sphere('symmetric362') >>> verts, faces = sphere.vertices, sphere.faces >>> verts.shape == (362, 3) True >>> faces.shape == (720, 3) True >>> verts, faces = get_sphere('not a sphere name') Traceback (most recent call last): ... DataError: No sphere called "not a sphere name"
real_sym_sh_mrtrix¶

dmipy.core.fitted_modeling_framework.
real_sym_sh_mrtrix
(sh_order, theta, phi)¶ Compute real spherical harmonics as in mrtrix, where the real harmonic \(Y^m_n\) is defined to be:
Real(:math:`Y^m_n`) if m > 0 :math:`Y^0_n` if m = 0 Imag(:math:`Y^m_n`) if m < 0
This may take scalar or array arguments. The inputs will be broadcasted against each other.
Parameters: sh_order : int
The maximum degree or the spherical harmonic basis.
theta : float [0, pi]
The polar (colatitudinal) coordinate.
phi : float [0, 2*pi]
The azimuthal (longitudinal) coordinate.
Returns: y_mn : real float
The real harmonic \(Y^m_n\) sampled at theta and phi as implemented in mrtrix. Warning: the basis is Tournier et al 2004 and 2007 is slightly different.
m : array
The order of the harmonics.
n : array
The degree of the harmonics.
sh_to_sf_matrix¶

dmipy.core.fitted_modeling_framework.
sh_to_sf_matrix
(sphere, sh_order, basis_type=None, return_inv=True, smooth=0)¶ Matrix that transforms Spherical harmonics (SH) to spherical function (SF).
Parameters: sphere : Sphere
The points on which to sample the spherical function.
sh_order : int, optional
Maximum SH order in the SH fit. For sh_order, there will be
(sh_order + 1) * (sh_order_2) / 2
SH coefficients (default 4).basis_type : {None, ‘mrtrix’, ‘fibernav’}
None
for the default dipy basis,mrtrix
for the MRtrix basis, andfibernav
for the FiberNavigator basis (defaultNone
).return_inv : bool
If True then the inverse of the matrix is also returned
smooth : float, optional
Lambdaregularization in the SH fit (default 0.0).
Returns: B : ndarray
Matrix that transforms spherical harmonics to spherical function
sf = np.dot(sh, B)
.invB : ndarray
Inverse of B.
unitsphere2cart_Nd¶

dmipy.core.fitted_modeling_framework.
unitsphere2cart_Nd
(mu)¶ Optimized function deicated to convert 1D unit sphere coordinates to cartesian coordinates.
Parameters: mu : Nd array of size (…, 2)
unit sphere coordinates, as theta, phi = mu
Returns: mu_cart, Nd array of size (…, 3) :
mu in cartesian coordinates, as x, y, z = mu_cart
b_from_g¶

dmipy.core.gradient_conversions.
b_from_g
(g, delta, Delta, gyromagnetic_ratio=267513000.0) Compute bvalue from gradient strength. Units are standard units.
b_from_q¶

dmipy.core.gradient_conversions.
b_from_q
(q, delta, Delta) Compute bvalue from qvalue. Units are standard units.
g_from_b¶

dmipy.core.gradient_conversions.
g_from_b
(b, delta, Delta, gyromagnetic_ratio=267513000.0) Compute gradient strength from bvalue. Units are standard units.
g_from_q¶

dmipy.core.gradient_conversions.
g_from_q
(q, delta, gyromagnetic_ratio=267513000.0) Compute gradient strength from qvalue. Units are standard units.
q_from_b¶

dmipy.core.gradient_conversions.
q_from_b
(b, delta, Delta) Compute qvalue from bvalue. Units are standard units.
q_from_g¶

dmipy.core.gradient_conversions.
q_from_g
(g, delta, gyromagnetic_ratio=267513000.0) Compute qvalue from gradient strength. Units are standard units.
Brute2FineOptimizer
¶

class
dmipy.core.modeling_framework.
Brute2FineOptimizer
(model, acquisition_scheme, Ns=5)¶ Brute force optimizer with refining. Essentially this function does both the brute force optimization like GlobalBruteOptimizer (without treating mu differently, which is currently suboptimal), but then follows it with a gradientdescent based refining step [1, 2] to find the local minimum.
All parameters are optimized within their parameter_bounds. Volume fraction are optimized by ‘nesting’ them, such that given a set of models \(m_1...m_N\), and the partial volume ratios math:v_1…v_{N1}, the partial volume function is
\[v_1 m_1 + (1  v_1) v_2 m_2 + ... + (1  v_1)...(1v_{N1}) m_N\]Parameters: model: dmipy MultiCompartmentModel instance, :
Can be composed of any model combination.
acquisition_scheme: DmipyAcquisitionScheme instance, :
acquisition scheme of the tobefitted data.
Ns: integer, :
number of equally spaced sampling points for regular parameters.
References
[R5] Byrd, R H and P Lu and J. Nocedal. 1995. A Limited Memory Algorithm for Bound Constrained Optimization. SIAM Journal on Scientific and Statistical Computing 16 (5): 11901208. [R6] Zhu, C and R H Byrd and J Nocedal. 1997. LBFGSB: Algorithm 778: LBFGSB, FORTRAN routines for large scale bound constrained optimization. ACM Transactions on Mathematical Software 23 (4): 550560. Methods

__init__
(model, acquisition_scheme, Ns=5)¶

objective_function
(parameter_vector, data)¶ The objective function for bruteforce and gradientbased optimizer.

FittedMultiCompartmentModel
¶

class
dmipy.core.modeling_framework.
FittedMultiCompartmentModel
(model, S0, mask, fitted_parameters_vector)¶ The FittedMultiCompartmentModel instance contains information about the original MultiCompartmentModel, the estimated S0 values, the fitting mask and the fitted model parameters.
Parameters: model : MultiCompartmentModel instance,
A dmipy MultiCompartmentModel.
S0 : array of size (Ndata,) or (N_data, N_DWIs),
Array containing the estimated S0 values of the data. If data is 4D, then S0 is 3D if there is only one TE, and the same 4D size of the data if there are multiple TEs.
mask : array of size (N_data,),
boolean mask of voxels that were fitted.
fitted_parameters_vector : array of size (N_data, Nparameters),
fitted model parameters array.
Attributes
Methods

__init__
(model, S0, mask, fitted_parameters_vector)¶

R2_coefficient_of_determination
(data)¶ Calculates the Rsquared of the model fit.

fitted_and_linked_parameters
¶ Returns the fitted and linked parameters as a dictionary.

fitted_parameters
¶ Returns the fitted parameters as a dictionary.

fod
(vertices, visual_odi_lower_bound=0.0)¶ Returns the Fiber Orientation Distribution if it is available.
Parameters: vertices : array of size (Nvertices, 3),
Array of cartesian unit vectors at which to sample the FOD.
visual_odi_lower_bound : float,
gives a lower bound to the Orientation Distribution Index (ODI) of FODs of Watson and Bingham distributions. This can be useful to visualize FOD fields where some FODs are extremely sharp.
Returns: fods : array of size (Ndata, Nvertices),
the FODs of the fitted model, scaled by volume fraction.

fod_sh
(sh_order=8, basis_type=None)¶ Returns the spherical harmonics coefficients of the Fiber Orientation Distribution (FOD) if it is available. Uses are 724 spherical tessellation to do the spherical harmonics transform.
Parameters: sh_order : integer,
the maximum spherical harmonics order of the coefficient expansion.
basis_type : string,
type of spherical harmonics basis to use for the expansion, see sh_to_sf_matrix for more info.
Returns: fods_sh : array of size (Ndata, Ncoefficients),
spherical harmonics coefficients of the FODs, scaled by volume fraction.

mean_squared_error
(data)¶ Calculates the mean squared error of the model fit.

peaks_cartesian
()¶ Returns the cartesian peak unit vectors of the model.

peaks_spherical
()¶ Returns the peak angles of the model.

predict
(acquisition_scheme=None, S0=None, mask=None)¶ simulates the dMRI signal of the fitted MultiCompartmentModel for the estimated model parameters. If no acquisition_scheme is given, then the same acquisition_scheme that was used for the fitting is used. If no S0 is given then it is assumed to be the estimated one. If no mask is given then all voxels are assumed to have been fitted.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
S0 : None or float,
Signal intensity without diffusion sensitization. If None, uses estimated SO from fitting process. If float, uses that value.
mask : (N1)dimensional integer/boolean array of size (N_x, N_y, …),
mask of voxels to simulate data at.
Returns: predicted_signal : array of size (Ndata, N_DWIS),
predicted DWIs for the given model parameters and acquisition scheme.

FittedMultiCompartmentSphericalHarmonicsModel
¶

class
dmipy.core.modeling_framework.
FittedMultiCompartmentSphericalHarmonicsModel
(model, S0, mask, fitted_parameters_vector)¶ The FittedMultiCompartmentModel instance contains information about the original MultiCompartmentModel, the estimated S0 values, the fitting mask and the fitted model parameters.
Parameters: model : MultiCompartmentModel instance,
A dmipy MultiCompartmentModel.
S0 : array of size (Ndata,) or (N_data, N_DWIs),
Array containing the estimated S0 values of the data. If data is 4D, then S0 is 3D if there is only one TE, and the same 4D size of the data if there are multiple TEs.
mask : array of size (N_data,),
boolean mask of voxels that were fitted.
fitted_parameters_vector : array of size (N_data, Nparameters),
fitted model parameters array.
Attributes
Methods

__init__
(model, S0, mask, fitted_parameters_vector)¶

R2_coefficient_of_determination
(data)¶ Calculates the Rsquared of the model fit.

anisotropy_index
()¶ Estimates anisotropy index of spherical harmonics [R7].
References
[R7] (1, 2) Jespersen, Sune N., et al. “Modeling dendrite density from magnetic resonance diffusion measurements.” Neuroimage 34.4 (2007): 14731486.

fitted_and_linked_parameters
¶ Returns the fitted and linked parameters as a dictionary.

fitted_parameters
¶ Returns the fitted parameters as a dictionary.

fod
(vertices)¶ Returns the Fiber Orientation Distribution if it is available.
Parameters: vertices : array of size (Nvertices, 3),
Array of cartesian unit vectors at which to sample the FOD.
visual_odi_lower_bound : float,
gives a lower bound to the Orientation Distribution Index (ODI) of FODs of Watson and Bingham distributions. This can be useful to visualize FOD fields where some FODs are extremely sharp.
Returns: fods : array of size (Ndata, Nvertices),
the FODs of the fitted model, scaled by volume fraction.

fod_sh
()¶ Returns the spherical harmonics coefficients of the Fiber Orientation Distribution (FOD) if it is available. Uses are 724 spherical tessellation to do the spherical harmonics transform.
Parameters: sh_order : integer,
the maximum spherical harmonics order of the coefficient expansion.
basis_type : string,
type of spherical harmonics basis to use for the expansion, see sh_to_sf_matrix for more info.
Returns: fods_sh : array of size (Ndata, Ncoefficients),
spherical harmonics coefficients of the FODs, scaled by volume fraction.

mean_squared_error
(data)¶ Calculates the mean squared error of the model fit.

predict
(acquisition_scheme=None, S0=None, mask=None)¶ simulates the dMRI signal of the fitted MultiCompartmentModel for the estimated model parameters. If no acquisition_scheme is given, then the same acquisition_scheme that was used for the fitting is used. If no S0 is given then it is assumed to be the estimated one. If no mask is given then all voxels are assumed to have been fitted.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
S0 : None or float,
Signal intensity without diffusion sensitization. If None, uses estimated SO from fitting process. If float, uses that value.
mask : (N1)dimensional integer/boolean array of size (N_x, N_y, …),
mask of voxels to simulate data at.
Returns: predicted_signal : array of size (Ndata, N_DWIS),
predicted DWIs for the given model parameters and acquisition scheme.

FittedMultiCompartmentSphericalMeanModel
¶

class
dmipy.core.modeling_framework.
FittedMultiCompartmentSphericalMeanModel
(model, S0, mask, fitted_parameters_vector)¶ The FittedMultiCompartmentModel instance contains information about the original MultiCompartmentModel, the estimated S0 values, the fitting mask and the fitted model parameters.
Parameters: model : MultiCompartmentModel instance,
A dmipy MultiCompartmentModel.
S0 : array of size (Ndata,) or (N_data, N_DWIs),
Array containing the estimated S0 values of the data. If data is 4D, then S0 is 3D if there is only one TE, and the same 4D size of the data if there are multiple TEs.
mask : array of size (N_data,),
boolean mask of voxels that were fitted.
fitted_parameters_vector : array of size (N_data, Nparameters),
fitted model parameters array.
Attributes
Methods

__init__
(model, S0, mask, fitted_parameters_vector)¶

R2_coefficient_of_determination
(data)¶ Calculates the Rsquared of the model fit.

fitted_and_linked_parameters
¶ Returns the fitted and linked parameters as a dictionary.

fitted_parameters
¶ Returns the fitted parameters as a dictionary.

mean_squared_error
(data)¶ Calculates the mean squared error of the model fit.

predict
(acquisition_scheme=None, S0=None, mask=None)¶ simulates the dMRI signal of the fitted MultiCompartmentModel for the estimated model parameters. If no acquisition_scheme is given, then the same acquisition_scheme that was used for the fitting is used. If no S0 is given then it is assumed to be the estimated one. If no mask is given then all voxels are assumed to have been fitted.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
S0 : None or float,
Signal intensity without diffusion sensitization. If None, uses estimated SO from fitting process. If float, uses that value.
mask : (N1)dimensional integer/boolean array of size (N_x, N_y, …),
mask of voxels to simulate data at.
Returns: predicted_signal : array of size (Ndata, N_DWIS),
predicted DWIs for the given model parameters and acquisition scheme.

return_parametric_fod_model
(distribution='watson', Ncompartments=1)¶ Retuns parametric FOD model using the rotational harmonics of the fitted spherical mean model as the convolution kernel. It can be called with any implemented parametric distribution (Watson/Bingham) and for any number of compartments.
Internally, the input models to the spherical mean model are given to a spherically distributed model where the parameter links are replayed such that the distributed model has the same parameter constraints as the spherical mean model. This distributed model now represents one compartment of “bundle”. This bundle representation is copied Ncompartment times and given as input to a MultiCompartmentModel, where now the nonlinear are all linked such that each bundle has the same convolution kernel. Finally, the FittedSphericalMeanModel parameters are given as fixed parameters for the kernel (the kernel will not be fitted while the FOD’s distribution parameters are being optimized).
The function returns a MultiCompartmentModel instance that can be interacted with as usual to fit dMRI data.
Parameters: distribution: string, :
Choice of parametric spherical distribution. Can be ‘watson’, or ‘bingham’.
Ncompartments: integer, :
Number of bundles that will be fitted. Must be larger than zero.
Returns: mc_bundles_model: Dmipy MultiCompartmentModel instance, :
MultiCompartmentModel instance that can be used to estimate parametric FODs using the fitted spherical mean model as a kernel.

GeneralPurposeCSDOptimizer
¶

class
dmipy.core.modeling_framework.
GeneralPurposeCSDOptimizer
(acquisition_scheme, model, sh_order=8, unity_constraint=True)¶ General purpose optimizer for multicompartment constrained spherical deconvolution (MCCSD) to estimate Fiber Orientation Distributions (FODs). It can take any number of compartment models as convolution kernels as long as all the kernel’s parameters are fixed. If more than one kernel is given, then the optimizer estimates the volume fractions of the different kernels as well as the FOD.
The optimization package CVXPY [R8] is used for this MCCSD implementation.
Limitations: It cannot estimate the FOD of multiple kernels that each have an orientation. E.g. it is possible to have a cylinder and a ball kernel as input, but not two cylinders.
IMPORTANT NOTE: This multicompartment CSD implementation is NOT the same MultiTissue CSD (MTCSD) as proposed by Jeurissen et al. [R9]. In MTCSD they input tissue response kernels that INCLUDES the differences in b0intensities between different tissue types. In this current implementation of MCCSD, the different compartment kernels are directly fitted to the signal attenuation, implicitly assuming each compartment has the same b0intensity.
Parameters: acquisition_scheme: DmipyAcquisitionScheme instance, :
acquisition scheme of the tobefitted data.
model: dmipy MultiCompartmentModel instance, :
Can be composed of any model combination.
sh_order: even integer larger or equal to zero, :
maximum spherical harmonics order to be included in the FOD estimation.
unity_constrain: bool, :
whether or not to impose that the FOD integrates to unity.
References
[R8] (1, 2) Diamond, Steven, and Stephen Boyd. “CVXPY: A Pythonembedded modeling language for convex optimization.” The Journal of Machine Learning Research 17.1 (2016): 29092913. [R9] (1, 2) Jeurissen, Ben, et al. “Multitissue constrained spherical deconvolution for improved analysis of multishell diffusion MRI data.” NeuroImage 103 (2014): 411426. Methods

__init__
(acquisition_scheme, model, sh_order=8, unity_constraint=True)¶

prepare_rotational_harmonics
(rh_array, rh_order)¶ Function to extend rotational harmonics and prepare them for MSE.

recover_rotational_harmonics
(x0_vector)¶ Recovers list of rotational harmonics for each model.

GlobalBruteOptimizer
¶

class
dmipy.core.modeling_framework.
GlobalBruteOptimizer
(model, acquisition_scheme, x0_vector=None, Ns=5, N_sphere_samples=30)¶ BruteForce optimizer. Given a model and an acquisition scheme, first computes a global grid of parameters and corresponding signal attenuations. All parameters except the spherical orientation parameter ‘mu’ are sampled between their corresponding parameter_ranges in ‘Ns’ equal steps. For ‘mu’ a spherical grid of ‘N_sphere_samples” points is used, which were generated using the work of Caruyer et al. [1].
When calling the function with measured data, the closest parameters are return based on the sumsquared error between the signal grid and the data.
Parameters: model: dmipy MultiCompartmentModel instance, :
Can be composed of any model combination.
acquisition_scheme: DmipyAcquisitionScheme instance, :
acquisition scheme of the tobefitted data.
x0_vector: array of size (Nparameters,) :
optional initial guess parameters. As long as the initial guess does not vary voxelbyvoxel the parameter grid will be estimated, only including the initial guess value for the parameters that were included in x0_vector.
Ns: integer, :
number of equally spaced sampling points for regular parameters.
N_sphere_sampled: integer, :
number of sampled sphere points to sample orientation ‘mu’.
References
[R10] Caruyer, Emmanuel, et al. “Design of multishell sampling schemes with uniform coverage in diffusion MRI.” Magnetic resonance in medicine 69.6 (2013): 15341540. Methods

__init__
(model, acquisition_scheme, x0_vector=None, Ns=5, N_sphere_samples=30)¶

precompute_signal_grid
(model, x0_vector, Ns, N_sphere_samples)¶ Function that estimates the parameter grid and corresponding signal attenuation.
NOTE: In the current implementation initial guesses for volume fractions are still ignored

MixOptimizer
¶

class
dmipy.core.modeling_framework.
MixOptimizer
(model, acquisition_scheme, maxiter=150)¶ The stochastic Microstructure In Crossings (MIX) optimizer [1] uses a threestep process to fit the parameters of a multicompartment (MC) model to data. The key innovation is that they separate linear from nonlinear parameters in the fitting process, meaning the linear volume fractions and nonlinear other ones(e.g. diffusivities) are optimized at different stages in the process.
In the first step [1] describes using a genetic algorithm to estimate the nonlinear parameters of an MC model. For this we use scipy’s differential_evolution algorithm.
In the second step [1] describes using CVX to estimate the linear volume fractions of an MC model. For this we use scipy’s COBYLA algorithm since it allows us to impose the parameter constraints we need for volume fractions; namely that they are positive and sum up to one.
The third and last step in [1] is a refining step to find a local minimum given the solutions of step one and two. For this we use scipy’s gradientbased LBFGSB algorithm with nested volume fractions.
The final result takes a model’s parameter_ranges into account, only yielding parameters within their allowed optimization domain.
Parameters: model : MultiCompartmentModel instance,
A multicompartment model that has been instantiated using dMipy.
acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
maxiter : integer
The maximum allowed iterations for the differential evolution algorithm
References
[R11] Farooq, Hamza, et al. “Microstructure Imaging of Crossing (MIX) White Matter Fibers from diffusion MRI.” Nature Scientific reports 6 (2016). Methods

__init__
(model, acquisition_scheme, maxiter=150)¶

cobyla_cost_function
(fractions, phi, data)¶ Objective function of linear parameter estimation using COBYLA.

objective_function
(optimized_parameter_vector, data, acquisition_scheme, x0_params)¶ Objective function of final refining step using LBFGSB

stochastic_objective_function
(optimized_parameter_vector, data, acquisition_scheme, x0_params)¶ Objective function for stochastic nonlinear parameter estimation using differential_evolution

ModelProperties
¶

class
dmipy.core.modeling_framework.
ModelProperties
Contains various properties for CompartmentModels.
Attributes

parameter_cardinality
Returns the cardinality of model parameters

parameter_names
Returns the names of model parameters.

parameter_ranges
Returns the optimization ranges of the model parameters. These ranges are given in O(1) scale so optimization algorithms don’t suffer from large scale differences in optimization parameters.

parameter_scales
Returns the optimization scales for the model parameters. The scales scale the parameter_ranges to their actual size inside optimization algorithms.

parameter_types
Returns the optimization scales for the model parameters. The scales scale the parameter_ranges to their actual size inside optimization algorithms.

MultiCompartmentModel
¶

class
dmipy.core.modeling_framework.
MultiCompartmentModel
(models, parameter_links=None) Bases:
dmipy.core.modeling_framework.MultiCompartmentModelProperties
The MultiCompartmentModel class allows to combine any number of CompartmentModels and DistributedModels into one combined model that can be used to fit and simulate dMRI data.
Parameters: models : list of N CompartmentModel instances,
the models to combine into the MultiCompartmentModel.
parameter_links : list of iterables (model, parameter name, link function,
argument list), deprecated, for testing only.
Attributes
Methods

__init__
(models, parameter_links=None)¶

fit
(acquisition_scheme, data, mask=None, solver='brute2fine', Ns=5, maxiter=300, N_sphere_samples=30, use_parallel_processing=False, number_of_processors=None) The main data fitting function of a MultiCompartmentModel.
This function can fit it to an Ndimensional dMRI data set, and returns a FittedMultiCompartmentModel instance that contains the fitted parameters and other useful functions to study the results.
No initial guess needs to be given to fit a model, but a partial or complete initial guess can be given if the user wants to have a solution that is a local minimum close to that guess. The parameter_initial_guess input can be created using parameter_initial_guess_to_parameter_vector().
A mask can also be given to exclude voxels from fitting (e.g. voxels that are outside the brain). If no mask is given then all voxels are included.
An optimization approach can be chosen as either ‘brute2fine’ or ‘mix’.  Choosing brute2fine will first use a bruteforce optimization to find
an initial guess for parameters without one, and will then refine the result using gradientdescentbased optimization.
Note that given no initial guess will make brute2fine precompute an global parameter grid that will be reused for all voxels, which in many cases is much faster than giving voxelvarying initial condition that requires a grid to be estimated per voxel.
 Choosing mix will use the recent MIX algorithm based on separation of linear and nonlinear parameters. MIX first uses a stochastic algorithm to find the nonlinear parameters (nonvolume fractions), then estimates the volume fractions while fixing the estimates of the nonlinear parameters, and then finally refines the solution using a gradientdescentbased algorithm.
The fitting process can be readily parallelized using the optional “pathos” package. If it is installed then it will automatically use it, but it can be turned off by setting use_parallel_processing=False. The algorithm will automatically use all cores in the machine, unless otherwise specified in number_of_processors.
Data with multiple TE are normalized in separate segments using the b0values according that TE.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
data : Ndimensional array of size (N_x, N_y, …, N_dwis),
The measured DWI signal attenuation array of either a single voxel or an Ndimensional dataset.
mask : (N1)dimensional integer/boolean array of size (N_x, N_y, …),
Optional mask of voxels to be included in the optimization.
solver : string,
Selection of optimization algorithm.  ‘brute2fine’ to use bruteforce optimization.  ‘mix’ to use Microstructure Imaging of Crossing (MIX)
optimization.
Ns : integer,
for brute optimization, decised how many steps are sampled for every parameter.
maxiter : integer,
for MIX optimization, how many iterations are allowed.
N_sphere_samples : integer,
for brute optimization, how many spherical orientations are sampled for ‘mu’.
use_parallel_processing : bool,
whether or not to use parallel processing using pathos.
number_of_processors : integer,
number of processors to use for parallel processing. Defaults to the number of processors in the computer according to cpu_count().
Returns: FittedCompartmentModel: class instance that contains fitted parameters, :
Can be used to recover parameters themselves or other useful functions.

simulate_signal
(acquisition_scheme, parameters_array_or_dict) Function to simulate diffusion data for a given acquisition_scheme and model parameters for the MultiCompartmentModel.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy
model_parameters_array : 1D array of size (N_parameters) or
Ndimensional array the same size as the data. The model parameters of the MultiCompartmentModel model.
Returns: E_simulated: 1D array of size (N_parameters) or Ndimensional :
array the same size as x0. The simulated signal of the microstructure model.

MultiCompartmentModelProperties
¶

class
dmipy.core.modeling_framework.
MultiCompartmentModelProperties
Class that contains various properties of MultiCompartmentModel instance.
Attributes
Methods

add_linked_parameters_to_parameters
(parameters) When making the MultiCompartmentModel function call, adds the linked parameter to the optimized parameters by evaluating the parameter link function.

bounds_for_optimization
Returns the linear parameter bounds for the model optimization.

opt_params_for_optimization
Returns the linear bools whether to optimize a model parameter.

parameter_initial_guess_to_parameter_vector
(**parameters) Function that returns a parameter_vector while allowing for partial input of model parameters, setting the ones that were not given to ‘None’. Such an array can be given to the fit() function to provide an initial parameter guess when fitting the data to the model.
Parameters: parameters: keyword arguments of parameter names, :
parameter values of only the parameters you want to give as an initial condition for the optimizer.
Returns: parameter_vector: array of size (Ndata_x, Ndata_y, …, Nparameters), :
array that contains the linearized model parameters for an NDarray of data voxels, with None’s for nongiven parameters.

parameter_names
Returns the names of model parameters.

parameter_vector_to_parameters
(parameter_vector) Returns the model parameters in dictionary format according to their parameter_names. Takes parameter_vector as input, which is the same as the output of a FittedMultiCompartmentModel.fitted_parameter_vector.
Parameters: parameter_vector: array of size (Ndata_x, Ndata_y, …, Nparameters), :
array that contains the linearized model parameters for an NDarray of data voxels.
Returns: parameter: dictionary with parameter_names as parameter keys, :
contains the model parameters in dictionary format.

parameters_to_parameter_vector
(**parameters) Returns the model parameters in array format. The input is a parameters dictionary that has parameter_names as keys. This is also the output of a FittedMultiCompartmentModel.fitted_parameters.
It’s possible to give an array of values for one parameter and only a float for others. The function will automatically assume that that the float parameters are constant in the data set and broadcast them accordingly.
The output parameter_vector can be used in simulate_data() to generate data according to the given input parameters.
Parameters: parameters: keyword arguments of parameter_names. :
Can be given as **parameter_dictionary that contains the model parameter values.
Returns: parameter_vector: array of size (Ndata_x, Ndata_y, …, Nparameters), :
array that contains the linearized model parameters for an NDarray of data voxels.

scales_for_optimization
Returns the linear parameter scales for model optimization.

set_equal_parameter
(parameter_name_in, parameter_name_out) Allows the user to set two parameters equal to each other. This is used for example in the NODDI model to set the parallel diffusivities of the Stick and Zeppelin compartment to the same value.
The second input parameter will be removed from the optimized parameters and added as a linked parameter.
Parameters: parameter_name_in: string :
the first parameter name, see self.parameter_names.
parameter_name_out: string, :
the second parameter name, see self.parameter_names. This is the parameter that will be removed form the optimzed parameters.

set_fixed_parameter
(parameter_name, value) Allows the user to fix an optimization parameter to a static value. The fixed parameter will be removed from the optimized parameters and added as a linked parameter.
Parameters: parameter_name: string :
name of the tobefixed parameters, see self.parameter_names.
value: float or list of corresponding parameter_cardinality. :
the value to fix the parameter at in SI units.

set_fractional_parameter
(parameter1_smaller_equal_than, parameter2) Allows to impose a constraint to make one parameter smaller or equal to another parameter. This is done by replacing parameter1 with a new parameter that is defined as a fraction between 0 and 1 of parameter2. The new parameter will be the same as the old parameter name with “_fraction” appended to it.
Parameters: parameter1_smaller_equal_than: string :
parameter name to be made a fraction of parameter2
parameter2: string :
the parameter that is larger or equal than parameter1

set_initial_guess_parameter
(parameter_name, value) Allows the user to fix an optimization parameter to a static value. The fixed parameter will be removed from the optimized parameters and added as a linked parameter.
Parameters: parameter_name: string :
name of the tobefixed parameters, see self.parameter_names.
value: float or list of corresponding parameter_cardinality. :
the value to fix the parameter at in SI units.

set_tortuous_parameter
(lambda_perp_parameter_name, lambda_par_parameter_name, volume_fraction_intra_parameter_name, volume_fraction_extra_parameter_name) Allows the user to set a tortuosity constraint on the perpendicular diffusivity of the extraaxonal compartment, which depends on the intraaxonal volume fraction and parallel diffusivity.
The perpendicular diffusivity parameter will be removed from the optimized parameters and added as a linked parameter.
Parameters: lambda_perp_parameter_name: string :
name of the perpendicular diffusivity parameter, see self.parameter_names.
lambda_par_parameter_name: string :
name of the parallel diffusivity parameter, see self.parameter_names.
volume_fraction_intra_parameter_name: string :
name of the intraaxonal volume fraction parameter, see self.parameter_names.
volume_fraction_extra_parameter_name: string :
name of the extraaxonal volume fraction parameter, see self.parameter_names.

MultiCompartmentSphericalHarmonicsModel
¶

class
dmipy.core.modeling_framework.
MultiCompartmentSphericalHarmonicsModel
(models, sh_order=8) Bases:
dmipy.core.modeling_framework.MultiCompartmentModelProperties
The MultiCompartmentModel class allows to combine any number of CompartmentModels and DistributedModels into one combined model that can be used to fit and simulate dMRI data.
Parameters: models : list of N CompartmentModel instances,
the models to combine into the MultiCompartmentModel.
Attributes
Methods

__init__
(models, sh_order=8)¶

fit
(acquisition_scheme, data, mask=None, solver='cvxpy', unity_constraint=True, use_parallel_processing=False, number_of_processors=None) The main data fitting function of a MultiCompartmentSphericalHarmonicsModel.
This function can fit it to an Ndimensional dMRI data set, and returns a FittedMultiCompartmentModel instance that contains the fitted parameters and other useful functions to study the results.
A mask can also be given to exclude voxels from fitting (e.g. voxels that are outside the brain). If no mask is given then all voxels are included.
The fitting process can be readily parallelized using the optional “pathos” package. If it is installed then it will automatically use it, but it can be turned off by setting use_parallel_processing=False. The algorithm will automatically use all cores in the machine, unless otherwise specified in number_of_processors.
Data with multiple TE are normalized in separate segments using the b0values according that TE.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
data : Ndimensional array of size (N_x, N_y, …, N_dwis),
The measured DWI signal attenuation array of either a single voxel or an Ndimensional dataset.
mask : (N1)dimensional integer/boolean array of size (N_x, N_y, …),
Optional mask of voxels to be included in the optimization.
solver : string,
can only be ‘cvxpy’ at this point for generalpurpose csd optimization using cvxpy [R12].
unity_constraint: bool, :
whether or not to constrain the volume fractions of the FOD to unity.
use_parallel_processing : bool,
whether or not to use parallel processing using pathos.
number_of_processors : integer,
number of processors to use for parallel processing. Defaults to the number of processors in the computer according to cpu_count().
Returns: FittedCompartmentModel: class instance that contains fitted parameters, :
Can be used to recover parameters themselves or other useful functions.
References
[R12] (1, 2) Diamond, Steven, and Stephen Boyd. “CVXPY: A Pythonembedded modeling language for convex optimization.” The Journal of Machine Learning Research 17.1 (2016): 29092913.

simulate_signal
(acquisition_scheme, parameters_array_or_dict) Function to simulate diffusion data for a given acquisition_scheme and model parameters for the MultiCompartmentModel.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy
model_parameters_array : 1D array of size (N_parameters) or
Ndimensional array the same size as the data. The model parameters of the MultiCompartmentModel model.
Returns: E_simulated: 1D array of size (N_parameters) or Ndimensional :
array the same size as x0. The simulated signal of the microstructure model.

MultiCompartmentSphericalMeanModel
¶

class
dmipy.core.modeling_framework.
MultiCompartmentSphericalMeanModel
(models, parameter_links=None) Bases:
dmipy.core.modeling_framework.MultiCompartmentModelProperties
The MultiCompartmentModel class allows to combine any number of CompartmentModels and DistributedModels into one combined model that can be used to fit and simulate dMRI data.
Parameters: models : list of N CompartmentModel instances,
the models to combine into the MultiCompartmentModel.
parameter_links : list of iterables (model, parameter name, link function,
argument list), deprecated, for testing only.
Attributes
Methods

__init__
(models, parameter_links=None)¶

fit
(acquisition_scheme, data, mask=None, solver='brute2fine', Ns=5, maxiter=300, N_sphere_samples=30, use_parallel_processing=False, number_of_processors=None) The main data fitting function of a MultiCompartmentModel.
This function can fit it to an Ndimensional dMRI data set, and returns a FittedMultiCompartmentModel instance that contains the fitted parameters and other useful functions to study the results.
No initial guess needs to be given to fit a model, but a partial or complete initial guess can be given if the user wants to have a solution that is a local minimum close to that guess. The parameter_initial_guess input can be created using parameter_initial_guess_to_parameter_vector().
A mask can also be given to exclude voxels from fitting (e.g. voxels that are outside the brain). If no mask is given then all voxels are included.
An optimization approach can be chosen as either ‘brute2fine’ or ‘mix’.  Choosing brute2fine will first use a bruteforce optimization to find
an initial guess for parameters without one, and will then refine the result using gradientdescentbased optimization.
Note that given no initial guess will make brute2fine precompute an global parameter grid that will be reused for all voxels, which in many cases is much faster than giving voxelvarying initial condition that requires a grid to be estimated per voxel.
 Choosing mix will use the recent MIX algorithm based on separation of linear and nonlinear parameters. MIX first uses a stochastic algorithm to find the nonlinear parameters (nonvolume fractions), then estimates the volume fractions while fixing the estimates of the nonlinear parameters, and then finally refines the solution using a gradientdescentbased algorithm.
The fitting process can be readily parallelized using the optional “pathos” package. If it is installed then it will automatically use it, but it can be turned off by setting use_parallel_processing=False. The algorithm will automatically use all cores in the machine, unless otherwise specified in number_of_processors.
Data with multiple TE are normalized in separate segments using the b0values according that TE.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
data : Ndimensional array of size (N_x, N_y, …, N_dwis),
The measured DWI signal attenuation array of either a single voxel or an Ndimensional dataset.
mask : (N1)dimensional integer/boolean array of size (N_x, N_y, …),
Optional mask of voxels to be included in the optimization.
solver : string,
Selection of optimization algorithm.  ‘brute2fine’ to use bruteforce optimization.  ‘mix’ to use Microstructure Imaging of Crossing (MIX)
optimization.
Ns : integer,
for brute optimization, decised how many steps are sampled for every parameter.
maxiter : integer,
for MIX optimization, how many iterations are allowed.
N_sphere_samples : integer,
for brute optimization, how many spherical orientations are sampled for ‘mu’.
use_parallel_processing : bool,
whether or not to use parallel processing using pathos.
number_of_processors : integer,
number of processors to use for parallel processing. Defaults to the number of processors in the computer according to cpu_count().
Returns: FittedCompartmentModel: class instance that contains fitted parameters, :
Can be used to recover parameters themselves or other useful functions.

simulate_signal
(acquisition_scheme, parameters_array_or_dict) Function to simulate diffusion data for a given acquisition_scheme and model parameters for the MultiCompartmentModel.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy
model_parameters_array : 1D array of size (N_parameters) or
Ndimensional array the same size as the data. The model parameters of the MultiCompartmentModel model.
Returns: E_simulated: 1D array of size (N_parameters) or Ndimensional :
array the same size as x0. The simulated signal of the microstructure model.

OrderedDict
¶

class
dmipy.core.modeling_framework.
OrderedDict
(*args, **kwds)¶ Bases:
dict
Dictionary that remembers insertion order
Methods

__init__
(*args, **kwds)¶ Initialize an ordered dictionary. The signature is the same as regular dictionaries, but keyword arguments are not recommended because their insertion order is arbitrary.

clear
() → None. Remove all items from od.¶

copy
() → a shallow copy of od¶

classmethod
fromkeys
(S[, v]) → New ordered dictionary with keys from S.¶ If not specified, the value defaults to None.

items
() → list of (key, value) pairs in od¶

iteritems
()¶ od.iteritems > an iterator over the (key, value) pairs in od

iterkeys
() → an iterator over the keys in od¶

itervalues
()¶ od.itervalues > an iterator over the values in od

keys
() → list of keys in od¶

pop
(k[, d]) → v, remove specified key and return the corresponding¶ value. If key is not found, d is returned if given, otherwise KeyError is raised.

popitem
() → (k, v), return and remove a (key, value) pair.¶ Pairs are returned in LIFO order if last is true or FIFO order if false.

setdefault
(k[, d]) → od.get(k,d), also set od[k]=d if k not in od¶

update
([E, ]**F) → None. Update D from mapping/iterable E and F.¶ If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v

values
() → list of values in od¶

viewitems
() → a setlike object providing a view on od's items¶

viewkeys
() → a setlike object providing a view on od's keys¶

viewvalues
() → an object providing a view on od's values¶

ReturnFixedValue
¶

class
dmipy.core.modeling_framework.
ReturnFixedValue
(value) Parameter fixing class for parameter links.
Methods

__init__
(value)¶

T1_tortuosity¶

dmipy.core.modeling_framework.
T1_tortuosity
(lambda_par, vf_intra, vf_extra=None)¶ Tortuosity model for perpendicular extraaxonal diffusivity [1, 2, 3]. If vf_extra=None, then vf_intra must be a nested volume fraction, in the sense that E_bundle = vf_intra * E_intra + (1  vf_intra) * E_extra, with vf_intra + (1  vf_intra) = 1. If both vf_intra and vf_extra are given, then they have be be normalized fractions, in the sense that vf_intra + vf_extra <= 1.
Parameters: lambda_par : float,
parallel diffusivity.
vf_intra : float,
intraaxonal volume fraction [0, 1].
vf_extra : float, (optional)
extraaxonal volume fraction [0, 1].
Returns: lambda_perp : float,
Rotation matrix.
References :
—— :
.. [1] Bruggeman, Von DAG. “Berechnung verschiedener physikalischer :
Konstanten von heterogenen Substanzen. I. Dielektrizitätskonstanten und Leitfähigkeiten der Mischkörper aus isotropen Substanzen.” Annalen der physik 416.7 (1935): 636664.
.. [2] Sen et al. “A selfsimilar model for sedimentary rocks with :
application to the dielectric constant of fused glass beads.” Geophysics 46.5 (1981): 781795.
.. [3] Szafer et al. “Theoretical model for water diffusion in tissues.” :
Magnetic resonance in medicine 33.5 (1995): 697712.
estimate_spherical_mean_multi_shell¶

dmipy.core.modeling_framework.
estimate_spherical_mean_multi_shell
(E_attenuation, acquisition_scheme, sh_order=6)¶ Estimates the spherical mean per shell of multishell acquisition. Uses spherical harmonics to do the estimation.
Parameters: E_attenuation : array, shape (N),
signal attenuation.
bvecs : array, shape (N x 3),
x, y, z components of cartesian unit bvectors.
b_shell_indices : array, shape (N)
array of integers indicating which measurement belongs to which shell. 0 should be used for b0 measurements, 1 for the lowest bvalue shell, 2 for the second lowest etc.
Returns: E_mean : array, shape (number of bshells)
spherical means of the signal attenuation per shell of the. For example, if there are three shells in the acquisition then the array is of length 3.
fractional_parameter¶

dmipy.core.modeling_framework.
fractional_parameter
(fractional_parameter, parameter2)¶ Defines fractional parameter link where the original parameter ranges between 01 of parameter2.
Parameters: fractional_parameter : string
new parameter that ranges between 0 and 1.
parameter2 : string
parameter that is larger or equal than the original parameter
homogenize_x0_to_data¶

dmipy.core.modeling_framework.
homogenize_x0_to_data
(data, x0) Function that checks if data and initial guess x0 are of the same size. If x0 is 1D, it will be tiled to be the same size as data.
optional_package¶

dmipy.core.modeling_framework.
optional_package
(name, trip_msg=None)¶ Return packagelike thing and module setup for package name
Parameters: name : str
package name
trip_msg : None or str
message to give when someone tries to use the return package, but we could not import it, and have returned a TripWire object instead. Default message if None.
Returns: pkg_like : module or
TripWire
instanceIf we can import the package, return it. Otherwise return an object raising an error when accessed
have_pkg : bool
True if import for package was successful, false otherwise
module_setup : function
callable usually set as
setup_module
in calling namespace, to allow skipping tests.
parameter_equality¶

dmipy.core.modeling_framework.
parameter_equality
(param)¶ Function to force two model parameters to be equal in the optimization
sh_convolution¶

dmipy.core.modeling_framework.
sh_convolution
(f_distribution_sh, kernel_rh)¶ Spherical convolution between a fiber distribution (f) in spherical harmonics and a kernel in terms of rotational harmonics (oriented along the zaxis).
Parameters: f_distribution_sh : array, shape (sh_coef)
spherical harmonic coefficients of a fiber distribution.
kernel_rh : array, shape (sh_coef),
rotational harmonic coefficients of the convolution kernel. In our case this is the spherical signal of one microenvironment at one bvalue.
Returns: f_kernel_convolved : array, shape (sh_coef)
spherical harmonic coefficients of the convolved kernel and distribution.
data
¶
Module: data.saved_acquisition_schemes
¶

dmipy.data.saved_acquisition_schemes.
wu_minn_hcp_acquisition_scheme
()¶ Returns DmipyAcquisitionScheme of WuMinn HCP project.

dmipy.data.saved_acquisition_schemes.
duval_cat_spinal_cord_2d_acquisition_scheme
()¶ Returns 2D DmipyAcquisitionScheme of cat spinal cord data.
Module: data.saved_data
¶

dmipy.data.saved_data.
wu_minn_hcp_coronal_slice
()¶ Returns example slice of WuMinn HCP data subject 100307.

dmipy.data.saved_data.
duval_cat_spinal_cord_2d
()¶ Returns 2D multidiffusion time AxCaliber data of cat spinal cord.

dmipy.data.saved_data.
synthetic_camino_data_parallel
()¶ The parallel data was generated using the Camino MonteCarlo Diffusion Simulator. See http://camino.cs.ucl.ac.uk/.

dmipy.data.saved_data.
synthetic_camino_data_dispersed
()¶ The dispersed data was generated by using the parallel Camino data as an described above, and then dispersing it using Watson and Bingham distributions.

dmipy.data.saved_data.
visualize_correlation_camino_and_estimated_fractions
(estim_fractions_parallel, estim_fractions_dispersed)¶ Function that visualizes Camino estimated results versus ground truth.
acquisition_scheme_from_bvalues¶

dmipy.data.saved_acquisition_schemes.
acquisition_scheme_from_bvalues
(bvalues, gradient_directions, delta, Delta, TE=None, min_b_shell_distance=50000000.0, b0_threshold=10000000.0)¶ Creates an acquisition scheme object from bvalues, gradient directions, pulse duration \(\delta\) and pulse separation time \(\Delta\).
Parameters: bvalues: 1D numpy array of shape (Ndata) :
bvalues of the acquisition in s/m^2. e.g., a bvalue of 1000 s/mm^2 must be entered as 1000 * 1e6 s/m^2
gradient_directions: 2D numpy array of shape (Ndata, 3) :
gradient directions array of cartesian unit vectors.
delta: float or 1D numpy array of shape (Ndata) :
if float, pulse duration of every measurements in seconds. if array, potentially varying pulse duration per measurement.
Delta: float or 1D numpy array of shape (Ndata) :
if float, pulse separation time of every measurements in seconds. if array, potentially varying pulse separation time per measurement.
min_b_shell_distance : float
minimum bvalue distance between different shells. This parameter is used to separate measurements into different shells, which is necessary for any model using spherical convolution or spherical mean.
b0_threshold : float
bvalue threshold for a measurement to be considered a b0 measurement.
Returns: DmipyAcquisitionScheme: acquisition scheme object :
contains all information of the acquisition scheme to be used in any microstructure model.
acquisition_scheme_from_gradient_strengths¶

dmipy.data.saved_acquisition_schemes.
acquisition_scheme_from_gradient_strengths
(gradient_strengths, gradient_directions, delta, Delta, TE=None, min_b_shell_distance=50000000.0, b0_threshold=10000000.0)¶ Creates an acquisition scheme object from gradient strengths, gradient directions pulse duration \(\delta\) and pulse separation time \(\Delta\).
Parameters: gradient_strengths: 1D numpy array of shape (Ndata) :
gradient strength of the acquisition in T/m. e.g., a gradient strength of 300 mT/m must be entered as 300 / 1e3 T/m
gradient_directions: 2D numpy array of shape (Ndata, 3) :
gradient directions array of cartesian unit vectors.
delta: float or 1D numpy array of shape (Ndata) :
if float, pulse duration of every measurements in seconds. if array, potentially varying pulse duration per measurement.
Delta: float or 1D numpy array of shape (Ndata) :
if float, pulse separation time of every measurements in seconds. if array, potentially varying pulse separation time per measurement.
min_b_shell_distance : float
minimum bvalue distance between different shells. This parameter is used to separate measurements into different shells, which is necessary for any model using spherical convolution or spherical mean.
b0_threshold : float
bvalue threshold for a measurement to be considered a b0 measurement.
Returns: DmipyAcquisitionScheme: acquisition scheme object :
contains all information of the acquisition scheme to be used in any microstructure model.
acquisition_scheme_from_schemefile¶

dmipy.data.saved_acquisition_schemes.
acquisition_scheme_from_schemefile
(file_path, min_b_shell_distance=50000000.0, b0_threshold=10000000.0)¶ Created an acquisition scheme object from a Camino scheme file, containing gradient directions, strengths, pulse duration \(\delta\) and pulse separation time \(\Delta\) and TE.
Parameters: file_path: string :
absolute file path to schemefile location
Returns: DmipyAcquisitionScheme: acquisition scheme object :
contains all information of the acquisition scheme to be used in any microstructure model.
de_santis_generated_acquisition_scheme¶

dmipy.data.saved_acquisition_schemes.
de_santis_generated_acquisition_scheme
()¶ Returns 2D DmipyAcquisitionScheme of de Santis.
duval_cat_spinal_cord_2d_acquisition_scheme¶

dmipy.data.saved_acquisition_schemes.
duval_cat_spinal_cord_2d_acquisition_scheme
() Returns 2D DmipyAcquisitionScheme of cat spinal cord data.
duval_cat_spinal_cord_3d_acquisition_scheme¶

dmipy.data.saved_acquisition_schemes.
duval_cat_spinal_cord_3d_acquisition_scheme
()¶ Returns 3D DmipyAcquisitionScheme of cat spinal cord data.
isbi2015_white_matter_challenge_scheme¶

dmipy.data.saved_acquisition_schemes.
isbi2015_white_matter_challenge_scheme
()¶ Returns 35shell ISBI 2015 challenge DmipyAcquisitionScheme.
join¶

dmipy.data.saved_acquisition_schemes.
join
(a, *p)¶ Join two or more pathname components, inserting ‘/’ as needed. If any component is an absolute path, all previous path components will be discarded. An empty last part will result in a path that ends with a separator.
panagiotaki_verdict_acquisition_scheme¶

dmipy.data.saved_acquisition_schemes.
panagiotaki_verdict_acquisition_scheme
()¶ Returns acquisition scheme for VERDICT tumor characterization.
urlopen¶

dmipy.data.saved_acquisition_schemes.
urlopen
(url, data=None, timeout=<object object>, cafile=None, capath=None, cadefault=False, context=None)¶
wu_minn_hcp_acquisition_scheme¶

dmipy.data.saved_acquisition_schemes.
wu_minn_hcp_acquisition_scheme
() Returns DmipyAcquisitionScheme of WuMinn HCP project.
de_santis_camino_data¶

dmipy.data.saved_data.
de_santis_camino_data
()¶ Downloads and returns the 4shell multidelta/Delta/G scheme based on acquistion scheme defined in [R13]. Note that acquisition parameters in [R13] used for a STEAM sequence, are used here to generate a PGSE one.
Returns: scheme: DmipyAcquisitionScheme instance, :
acquisition scheme of the generated de Santis data.
data_genu: array of size (50, 54), :
contains 50 repetitions with added rician noise SNR=30.
References
[R13] (1, 2, 3) De Santis, S., Jones, D. K., & Roebroeck, A. (2016). Including diffusion time dependence in the extraaxonal space improves in vivo estimates of axonal diameter and density in human white matter. NeuroImage, 130, 91103.
duval_cat_spinal_cord_2d¶

dmipy.data.saved_data.
duval_cat_spinal_cord_2d
() Returns 2D multidiffusion time AxCaliber data of cat spinal cord.
duval_cat_spinal_cord_3d¶

dmipy.data.saved_data.
duval_cat_spinal_cord_3d
()¶ Returns 2D multidiffusion time AxCaliber data of cat spinal cord.
isbi2015_white_matter_challenge¶

dmipy.data.saved_data.
isbi2015_white_matter_challenge
()¶ Downloads and returns the 35shell multidelta/Delta/G scheme and data for the fornix and genu data that was used for the ISBI 2015 white matter challenge [R14].
Returns: scheme: DmipyAcquisitionScheme instance, :
acquisition scheme of the challenge data.
data_genu: array of size (3612, 6), :
contains the DWIs for 6 genu voxels.
data_fornix: array of size (3612, 6), :
contains the DWIs for 6 fornix voxels.
References
[R14] (1, 2) Ferizi, Uran, et al. “Diffusion MRI microstructure models with in vivo human brain Connectome data: results from a multigroup comparison.” NMR in Biomedicine 30.9 (2017)
join¶

dmipy.data.saved_data.
join
(a, *p)¶ Join two or more pathname components, inserting ‘/’ as needed. If any component is an absolute path, all previous path components will be discarded. An empty last part will result in a path that ends with a separator.
panagiotaki_verdict¶

dmipy.data.saved_data.
panagiotaki_verdict
()¶ Downloads and returns the example VERDICT acquisition scheme and data that is available at the UCL website. The data is an example of [R15].
Returns: scheme: DmipyAcquisitionScheme instance, :
acquisition scheme of the challenge data.
data_verdict: array, :
contains the DWIs for a single tumor voxel.
References
[R15] (1, 2) Panagiotaki, Eletheria, et al. “Noninvasive quantification of solid tumor microstructure using VERDICT MRI.” Cancer research 74.7 (2014): 19021912.
pearsonr¶

dmipy.data.saved_data.
pearsonr
(x, y)¶ Calculate a Pearson correlation coefficient and the pvalue for testing noncorrelation.
The Pearson correlation coefficient measures the linear relationship between two datasets. Strictly speaking, Pearson’s correlation requires that each dataset be normally distributed, and not necessarily zeromean. Like other correlation coefficients, this one varies between 1 and +1 with 0 implying no correlation. Correlations of 1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases.
The pvalue roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. The pvalues are not entirely reliable but are probably reasonable for datasets larger than 500 or so.
Parameters: x : (N,) array_like
Input
y : (N,) array_like
Input
Returns: r : float
Pearson’s correlation coefficient
pvalue : float
2tailed pvalue
Notes
The correlation coefficient is calculated as follows:
\[r_{pb} = \frac{\sum (x  m_x) (y  m_y) }{\sqrt{\sum (x  m_x)^2 (y  m_y)^2}}\]where \(m_x\) is the mean of the vector \(x\) and \(m_y\) is the mean of the vector \(y\).
References
http://www.statsoft.com/textbook/glosp.html#Pearson%20Correlation
Examples
>>> from scipy import stats >>> a = np.array([0, 0, 0, 1, 1, 1, 1]) >>> b = np.arange(7) >>> stats.pearsonr(a, b) (0.8660254037844386, 0.011724811003954654)
>>> stats.pearsonr([1,2,3,4,5], [5,6,7,8,7]) (0.83205029433784372, 0.080509573298498519)
synthetic_camino_data_dispersed¶

dmipy.data.saved_data.
synthetic_camino_data_dispersed
() The dispersed data was generated by using the parallel Camino data as an described above, and then dispersing it using Watson and Bingham distributions.
synthetic_camino_data_parallel¶

dmipy.data.saved_data.
synthetic_camino_data_parallel
() The parallel data was generated using the Camino MonteCarlo Diffusion Simulator. See http://camino.cs.ucl.ac.uk/.
urlopen¶

dmipy.data.saved_data.
urlopen
(url, data=None, timeout=<object object>, cafile=None, capath=None, cadefault=False, context=None)¶
visualize_correlation_camino_and_estimated_fractions¶

dmipy.data.saved_data.
visualize_correlation_camino_and_estimated_fractions
(estim_fractions_parallel, estim_fractions_dispersed) Function that visualizes Camino estimated results versus ground truth.
wu_minn_hcp_coronal_slice¶

dmipy.data.saved_data.
wu_minn_hcp_coronal_slice
() Returns example slice of WuMinn HCP data subject 100307.
distributions
¶
Module: distributions.distribute_models
¶

class
dmipy.distributions.distribute_models.
DistributedModel
¶ Contains various properties of distributed models.
Attributes
Methods

add_linked_parameters_to_parameters
(parameters)¶ Adds the linked parameters to the optimized parameters.
Parameters: parameters: dictionary of model parameters, :
contains the optimized parameters.
Returns: parameters: dictionary of model parameters, :
contains the optimzed and linked parameters.

copy
()¶ Retuns a different instantiation of the DistributedModel with the same configuration, which can be used together with the original in a MultiCompartmentModel. For example, to do NODDI with multiple orientations.

fod
(vertices, **kwargs)¶ Returns the Fiber Orientation Distribution (FOD) of a dispersed model.
Parameters: vertices: array of size (N_samples, 3) :
cartesian unit vectors at which to sample the FOD
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.

integrated_model
(acquisition_scheme, **kwargs)¶ The spatially integrated function call for spatial distributions like Gamma. Currently, the model assumed we are distributing diameters.
First, the linked parameters are added to the optimized parameters, and the probability that a water particle exists inside a cylinder of a certain size in the distribution is sampled for a range of diameters. The volume fractions are also converted from nested to regular ones (although typically not more than 1 model is used for a Gamma distribution).
Then, for every model in the DistributedModel, the signal attenuations of the model are are recovered for the sampled diameters and multiplied and integrated over their probabilities. The resulting values are multiplied with the volume fractions and finally the integrated signal attenuation is returned.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.

parameter_names
¶ Retuns the DistributedModel parameter names.

set_equal_parameter
(parameter_name_in, parameter_name_out)¶ Allows the user to set two parameters equal to each other. This is used for example in the NODDI model to set the parallel diffusivities of the Stick and Zeppelin compartment to the same value.
The second input parameter will be removed from the optimized parameters and added as a linked parameter.
Parameters: parameter_name_in: string :
the first parameter name, see self.parameter_names.
parameter_name_out: string, :
the second parameter name, see self.parameter_names. This is the parameter that will be removed form the optimzed parameters.

set_fixed_parameter
(parameter_name, value)¶ Allows the user to fix an optimization parameter to a static value. The fixed parameter will be removed from the optimized parameters and added as a linked parameter.
Parameters: parameter_name: string :
name of the tobefixed parameters, see self.parameter_names.
value: float or list of corresponding parameter_cardinality. :
the value to fix the parameter at in SI units.

set_tortuous_parameter
(lambda_perp, lambda_par, volume_fraction_intra)¶ Allows the user to set a tortuosity constraint on the perpendicular diffusivity of the extraaxonal compartment, which depends on the intraaxonal volume fraction and parallel diffusivity.
The perpendicular diffusivity parameter will be removed from the optimized parameters and added as a linked parameter.
Parameters: lambda_perp: string :
name of the perpendicular diffusivity parameter, see self.parameter_names.
lambda_par: string :
name of the parallel diffusivity parameter, see self.parameter_names.
volume_fraction_intra: string :
name of the intraaxonal volume fraction parameter, see self.parameter_names.

sh_convolved_model
(acquisition_scheme, **kwargs)¶ The spherical harmonics convolved function call for spherically distributions like Watson and Bingham.
First, the linked parameters are added to the optimized parameters, and the spherical harmonics of the spherical distribution are recovered. The volume fractions are also converted from nested to regular ones.
Then, for every model in the DistributedModel, and for every acquisition shell, the rotational harmonics of the model are recovered and convolved with the distribution spherical harmonics. The resulting values are multiplied with the volume fractions and finally the dispersed signal attenuation is returned.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.


class
dmipy.distributions.distribute_models.
SD1WatsonDistributed
(models, parameter_links=None)¶ The DistributedModel instantiation for a Watsondispersed model. Multiple models can be dispersed at the same time (like a Stick and Zeppelin for NODDI for example). The parameter ‘mu’ of the models will be removed and replaced by the ‘mu’ and ‘odi’ of the Watson distribution.
After instantiation the WatsonDistributed model can be treated exactly the same as a CompartmentModel as an input for a MultiCompartmentModel.
Parameters: models: list of length 1 or more, :
list of models to be Watsondispersed.
parameters_links: list of length 1 or more, :
deprecated for testing use only.
Attributes
Methods

class
dmipy.distributions.distribute_models.
SD2BinghamDistributed
(models, parameter_links=None)¶ The DistributedModel instantiation for a Binghamdispersed model. Multiple models can be dispersed at the same time (like a Stick and Zeppelin for NODDI for example). The parameter ‘mu’ of the models will be removed and replaced by the ‘mu’, ‘odi’, ‘beta_fraction’ and ‘psi’ of the Bingham distribution.
After instantiation the BinghamDistributed model can be treated exactly the same as a CompartmentModel as an input for a MultiCompartmentModel.
Parameters: models: list of length 1 or more, :
list of models to be Watsondispersed.
parameters_links: list of length 1 or more, :
deprecated for testing use only.
Attributes
Methods

class
dmipy.distributions.distribute_models.
DD1GammaDistributed
(models, parameter_links=None, target_parameter='diameter')¶ The DistributedModel instantiation for a Gammadistributed model for cylinder or sphere models. Multiple models can be distributed at the same time (but such multicylinderdistribution models have never been used as far as we know). The parameter ‘diameter’ of the models will be removed and replaced by the ‘alpha’ and ‘beta’, of the Gamma distribution.
After instantiation the GammaDistributed model can be treated exactly the same as a CompartmentModel as an input for a MultiCompartmentModel.
Parameters: models: list of length 1 or more, :
list of models to be Watsondispersed.
parameters_links: list of length 1 or more, :
deprecated for testing use only.
Attributes
Methods

rotational_harmonics_representation
(acquisition_scheme, **kwargs)¶ The rotational harmonics of the model, such that Y_lm = Yl0. Axis aligned with zaxis to be used as kernel for spherical convolution. Returns an array with rotational harmonics for each shell.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: rh_array : array, shape(Nshells, N_rh_coef),
Rotational harmonics coefficients for each shell.

set_diameter_constrained_parameter_beta
(diameter_min, diameter_max)¶

spherical_mean
(acquisition_scheme, **kwargs)¶ Estimates spherical mean for every shell in acquisition scheme.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: E_mean : float,
spherical mean of the model for every acquisition shell.


class
dmipy.distributions.distribute_models.
ReturnFixedValue
(value)¶ Parameter fixing class for parameter links.
Methods
Module: distributions.distributions
¶
Document Module

dmipy.distributions.distributions.
get_sh_order_from_odi
(odi)¶ Returns minimum sh_order to estimate spherical harmonics for given odi.

class
dmipy.distributions.distributions.
SD1Watson
(mu=None, odi=None)¶ The Watson spherical distribution model [R16] [R17].
Parameters: mu : array, shape(2),
angles [theta, phi] representing main orientation on the sphere. theta is inclination of polar angle of main angle mu [0, pi]. phi is polar angle of main angle mu [pi, pi].
kappa : float,
concentration parameter of the Watson distribution.
References
[R16] (1, 2) Kaden et al. “Parametric spherical deconvolution: inferring anatomical
connectivity using diffusion MR imaging”. NeuroImage (2007)[R17] (1, 2) Zhang et al. “NODDI: practical in vivo neurite orientation dispersion and density
imaging of the human brain”. NeuroImage (2012)Attributes
Methods

spherical_harmonics_representation
(sh_order=None, **kwargs)¶ The Watson spherical distribution model in spherical harmonics. The minimum order is automatically derived from numerical experiments to ensure fast function executation and accurate results.
Parameters: sh_order : int,
maximum spherical harmonics order to be used in the approximation.
Returns: watson_sh : array,
spherical harmonics of Watson probability density.


class
dmipy.distributions.distributions.
SD2Bingham
(mu=None, psi=None, odi=None, beta_fraction=None)¶ The Bingham spherical distribution model [R18] [R19] [R20] using angles.
Parameters: mu : array, shape(2),
angles [theta, phi] representing main orientation on the sphere. theta is inclination of polar angle of main angle mu [0, pi]. phi is polar angle of main angle mu [pi, pi].
psi : float,
angle in radians of the bingham distribution around mu [0, pi].
kappa : float,
first concentration parameter of the Bingham distribution. defined as kappa = kappa1  kappa3.
beta : float,
second concentration parameter of the Bingham distribution. defined as beta = kappa2  kappa3. Bingham becomes Watson when beta=0.
References
[R18] (1, 2) Kaden et al. “Parametric spherical deconvolution: inferring anatomical
connectivity using diffusion MR imaging”. NeuroImage (2007)[R19] (1, 2) Sotiropoulos et al. “Ball and rackets: inferring fiber fanning from
diffusionweighted MRI”. NeuroImage (2012)[R20] (1, 2) Tariq et al. “Bingham–NODDI: Mapping anisotropic orientation dispersion of
neurites using diffusion MRI”. NeuroImage (2016)Attributes
Methods

spherical_harmonics_representation
(sh_order=None, **kwargs)¶ The Bingham spherical distribution model in spherical harmonics. The minimum order is automatically derived from numerical experiments to ensure fast function executation and accurate results.
Parameters: sh_order : int,
maximum spherical harmonics order to be used in the approximation.
Returns: bingham_sh : array,
spherical harmonics of Bingham probability density.


class
dmipy.distributions.distributions.
DD1Gamma
(alpha=None, beta=None, Nsteps=30, normalization='standard')¶ A Gamma distribution of cylinder diameter for given alpha and beta parameters. NOTE: This is a distribution for axon DIAMETER and not SURFACE. To simulate the diffusion signal of an ensemble of gammadistributed cylinders the probability still needs to be corrected for cylinder surface by multiplying by np.pi * radius ** 2 and renormalizing [R21]. Reason being that diffusion signals are generated by the volume of spins inside axons (cylinders), which is proportional to cylinder surface and not to diameter.
Parameters: alpha : float,
shape of the gamma distribution.
beta : float,
scale of the gamma distrubution. Different from Bingham distribution!
References
[R21] (1, 2) Assaf, Yaniv, et al. “AxCaliber: a method for measuring axon diameter distribution from diffusion MRI.” Magnetic resonance in medicine 59.6 (2008): 13471354. Attributes
Methods

calculate_sampling_start_and_end_points
(norm_func, gridsize=50)¶ For a given normalization function calculates the best start and end points to sample for all possible values of alpha, beta. This is done to make sure the function does not sample where the probability of basically zero.
The function is based on first doing a dense sampling and then finding out which points need to be included to have sampled at least 99% of the area under the probability density curve.
It sets two interpolator functions that can be called for any combination of alpha,beta and to return the appropriate start and end sampling points.
Parameters: norm_func : normalization function,
normalization of the model, depends on if it’s a sphere/cylinder.
gridsize : integer,
value that decides how big the grid will be on which we define the start and end sampling points.

length_plane
(radius)¶ The distance normalization function for planes.

surface_cylinder
(radius)¶ The surface normalization function for cylinders.

unity
(radius)¶ The standard normalization for the Gamma distribution (none).

volume_sphere
(radius)¶ The volume normalization function for spheres.


dmipy.distributions.distributions.
odi2kappa
(odi)¶ Calculates concentration (kappa) from orientation dispersion index (odi).

dmipy.distributions.distributions.
kappa2odi
(kappa)¶ Calculates orientation dispersion index (odi) from concentration (kappa).
DD1GammaDistributed
¶

class
dmipy.distributions.distribute_models.
DD1GammaDistributed
(models, parameter_links=None, target_parameter='diameter') Bases:
dmipy.distributions.distribute_models.DistributedModel
The DistributedModel instantiation for a Gammadistributed model for cylinder or sphere models. Multiple models can be distributed at the same time (but such multicylinderdistribution models have never been used as far as we know). The parameter ‘diameter’ of the models will be removed and replaced by the ‘alpha’ and ‘beta’, of the Gamma distribution.
After instantiation the GammaDistributed model can be treated exactly the same as a CompartmentModel as an input for a MultiCompartmentModel.
Parameters: models: list of length 1 or more, :
list of models to be Watsondispersed.
parameters_links: list of length 1 or more, :
deprecated for testing use only.
Attributes
Methods

__init__
(models, parameter_links=None, target_parameter='diameter')¶

rotational_harmonics_representation
(acquisition_scheme, **kwargs) The rotational harmonics of the model, such that Y_lm = Yl0. Axis aligned with zaxis to be used as kernel for spherical convolution. Returns an array with rotational harmonics for each shell.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: rh_array : array, shape(Nshells, N_rh_coef),
Rotational harmonics coefficients for each shell.

set_diameter_constrained_parameter_beta
(diameter_min, diameter_max)

spherical_mean
(acquisition_scheme, **kwargs) Estimates spherical mean for every shell in acquisition scheme.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: E_mean : float,
spherical mean of the model for every acquisition shell.

DistributedModel
¶

class
dmipy.distributions.distribute_models.
DistributedModel
Contains various properties of distributed models.
Attributes
Methods

add_linked_parameters_to_parameters
(parameters) Adds the linked parameters to the optimized parameters.
Parameters: parameters: dictionary of model parameters, :
contains the optimized parameters.
Returns: parameters: dictionary of model parameters, :
contains the optimzed and linked parameters.

copy
() Retuns a different instantiation of the DistributedModel with the same configuration, which can be used together with the original in a MultiCompartmentModel. For example, to do NODDI with multiple orientations.

fod
(vertices, **kwargs) Returns the Fiber Orientation Distribution (FOD) of a dispersed model.
Parameters: vertices: array of size (N_samples, 3) :
cartesian unit vectors at which to sample the FOD
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.

integrated_model
(acquisition_scheme, **kwargs) The spatially integrated function call for spatial distributions like Gamma. Currently, the model assumed we are distributing diameters.
First, the linked parameters are added to the optimized parameters, and the probability that a water particle exists inside a cylinder of a certain size in the distribution is sampled for a range of diameters. The volume fractions are also converted from nested to regular ones (although typically not more than 1 model is used for a Gamma distribution).
Then, for every model in the DistributedModel, the signal attenuations of the model are are recovered for the sampled diameters and multiplied and integrated over their probabilities. The resulting values are multiplied with the volume fractions and finally the integrated signal attenuation is returned.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.

parameter_names
Retuns the DistributedModel parameter names.

set_equal_parameter
(parameter_name_in, parameter_name_out) Allows the user to set two parameters equal to each other. This is used for example in the NODDI model to set the parallel diffusivities of the Stick and Zeppelin compartment to the same value.
The second input parameter will be removed from the optimized parameters and added as a linked parameter.
Parameters: parameter_name_in: string :
the first parameter name, see self.parameter_names.
parameter_name_out: string, :
the second parameter name, see self.parameter_names. This is the parameter that will be removed form the optimzed parameters.

set_fixed_parameter
(parameter_name, value) Allows the user to fix an optimization parameter to a static value. The fixed parameter will be removed from the optimized parameters and added as a linked parameter.
Parameters: parameter_name: string :
name of the tobefixed parameters, see self.parameter_names.
value: float or list of corresponding parameter_cardinality. :
the value to fix the parameter at in SI units.

set_tortuous_parameter
(lambda_perp, lambda_par, volume_fraction_intra) Allows the user to set a tortuosity constraint on the perpendicular diffusivity of the extraaxonal compartment, which depends on the intraaxonal volume fraction and parallel diffusivity.
The perpendicular diffusivity parameter will be removed from the optimized parameters and added as a linked parameter.
Parameters: lambda_perp: string :
name of the perpendicular diffusivity parameter, see self.parameter_names.
lambda_par: string :
name of the parallel diffusivity parameter, see self.parameter_names.
volume_fraction_intra: string :
name of the intraaxonal volume fraction parameter, see self.parameter_names.

sh_convolved_model
(acquisition_scheme, **kwargs) The spherical harmonics convolved function call for spherically distributions like Watson and Bingham.
First, the linked parameters are added to the optimized parameters, and the spherical harmonics of the spherical distribution are recovered. The volume fractions are also converted from nested to regular ones.
Then, for every model in the DistributedModel, and for every acquisition shell, the rotational harmonics of the model are recovered and convolved with the distribution spherical harmonics. The resulting values are multiplied with the volume fractions and finally the dispersed signal attenuation is returned.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.

OrderedDict
¶

class
dmipy.distributions.distribute_models.
OrderedDict
(*args, **kwds)¶ Bases:
dict
Dictionary that remembers insertion order
Methods

__init__
(*args, **kwds)¶ Initialize an ordered dictionary. The signature is the same as regular dictionaries, but keyword arguments are not recommended because their insertion order is arbitrary.

clear
() → None. Remove all items from od.¶

copy
() → a shallow copy of od¶

classmethod
fromkeys
(S[, v]) → New ordered dictionary with keys from S.¶ If not specified, the value defaults to None.

items
() → list of (key, value) pairs in od¶

iteritems
()¶ od.iteritems > an iterator over the (key, value) pairs in od

iterkeys
() → an iterator over the keys in od¶

itervalues
()¶ od.itervalues > an iterator over the values in od

keys
() → list of keys in od¶

pop
(k[, d]) → v, remove specified key and return the corresponding¶ value. If key is not found, d is returned if given, otherwise KeyError is raised.

popitem
() → (k, v), return and remove a (key, value) pair.¶ Pairs are returned in LIFO order if last is true or FIFO order if false.

setdefault
(k[, d]) → od.get(k,d), also set od[k]=d if k not in od¶

update
([E, ]**F) → None. Update D from mapping/iterable E and F.¶ If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v

values
() → list of values in od¶

viewitems
() → a setlike object providing a view on od's items¶

viewkeys
() → a setlike object providing a view on od's keys¶

viewvalues
() → an object providing a view on od's values¶

ReturnFixedValue
¶

class
dmipy.distributions.distribute_models.
ReturnFixedValue
(value) Parameter fixing class for parameter links.
Methods

__init__
(value)¶

SD1WatsonDistributed
¶

class
dmipy.distributions.distribute_models.
SD1WatsonDistributed
(models, parameter_links=None) Bases:
dmipy.distributions.distribute_models.DistributedModel
The DistributedModel instantiation for a Watsondispersed model. Multiple models can be dispersed at the same time (like a Stick and Zeppelin for NODDI for example). The parameter ‘mu’ of the models will be removed and replaced by the ‘mu’ and ‘odi’ of the Watson distribution.
After instantiation the WatsonDistributed model can be treated exactly the same as a CompartmentModel as an input for a MultiCompartmentModel.
Parameters: models: list of length 1 or more, :
list of models to be Watsondispersed.
parameters_links: list of length 1 or more, :
deprecated for testing use only.
Attributes
Methods

__init__
(models, parameter_links=None)¶

SD2BinghamDistributed
¶

class
dmipy.distributions.distribute_models.
SD2BinghamDistributed
(models, parameter_links=None) Bases:
dmipy.distributions.distribute_models.DistributedModel
The DistributedModel instantiation for a Binghamdispersed model. Multiple models can be dispersed at the same time (like a Stick and Zeppelin for NODDI for example). The parameter ‘mu’ of the models will be removed and replaced by the ‘mu’, ‘odi’, ‘beta_fraction’ and ‘psi’ of the Bingham distribution.
After instantiation the BinghamDistributed model can be treated exactly the same as a CompartmentModel as an input for a MultiCompartmentModel.
Parameters: models: list of length 1 or more, :
list of models to be Watsondispersed.
parameters_links: list of length 1 or more, :
deprecated for testing use only.
Attributes
Methods

__init__
(models, parameter_links=None)¶

chain
¶

class
dmipy.distributions.distribute_models.
chain
¶ Bases:
object
chain(*iterables) –> chain object
Return a chain object whose .next() method returns elements from the first iterable until it is exhausted, then elements from the next iterable, until all of the iterables are exhausted.
Methods

__init__
()¶ x.__init__(…) initializes x; see help(type(x)) for signature

from_iterable
()¶ chain.from_iterable(iterable) –> chain object
Alternate chain() contructor taking a single iterable argument that evaluates lazily.

next
¶

T1_tortuosity¶

dmipy.distributions.distribute_models.
T1_tortuosity
(lambda_par, vf_intra, vf_extra=None)¶ Tortuosity model for perpendicular extraaxonal diffusivity [1, 2, 3]. If vf_extra=None, then vf_intra must be a nested volume fraction, in the sense that E_bundle = vf_intra * E_intra + (1  vf_intra) * E_extra, with vf_intra + (1  vf_intra) = 1. If both vf_intra and vf_extra are given, then they have be be normalized fractions, in the sense that vf_intra + vf_extra <= 1.
Parameters: lambda_par : float,
parallel diffusivity.
vf_intra : float,
intraaxonal volume fraction [0, 1].
vf_extra : float, (optional)
extraaxonal volume fraction [0, 1].
Returns: lambda_perp : float,
Rotation matrix.
References :
—— :
.. [1] Bruggeman, Von DAG. “Berechnung verschiedener physikalischer :
Konstanten von heterogenen Substanzen. I. Dielektrizitätskonstanten und Leitfähigkeiten der Mischkörper aus isotropen Substanzen.” Annalen der physik 416.7 (1935): 636664.
.. [2] Sen et al. “A selfsimilar model for sedimentary rocks with :
application to the dielectric constant of fused glass beads.” Geophysics 46.5 (1981): 781795.
.. [3] Szafer et al. “Theoretical model for water diffusion in tissues.” :
Magnetic resonance in medicine 33.5 (1995): 697712.
parameter_equality¶

dmipy.distributions.distribute_models.
parameter_equality
(param)¶ Function to force two model parameters to be equal in the optimization
sh_convolution¶

dmipy.distributions.distribute_models.
sh_convolution
(f_distribution_sh, kernel_rh)¶ Spherical convolution between a fiber distribution (f) in spherical harmonics and a kernel in terms of rotational harmonics (oriented along the zaxis).
Parameters: f_distribution_sh : array, shape (sh_coef)
spherical harmonic coefficients of a fiber distribution.
kernel_rh : array, shape (sh_coef),
rotational harmonic coefficients of the convolution kernel. In our case this is the spherical signal of one microenvironment at one bvalue.
Returns: f_kernel_convolved : array, shape (sh_coef)
spherical harmonic coefficients of the convolved kernel and distribution.
DD1Gamma
¶

class
dmipy.distributions.distributions.
DD1Gamma
(alpha=None, beta=None, Nsteps=30, normalization='standard') Bases:
dmipy.core.modeling_framework.ModelProperties
A Gamma distribution of cylinder diameter for given alpha and beta parameters. NOTE: This is a distribution for axon DIAMETER and not SURFACE. To simulate the diffusion signal of an ensemble of gammadistributed cylinders the probability still needs to be corrected for cylinder surface by multiplying by np.pi * radius ** 2 and renormalizing [R22]. Reason being that diffusion signals are generated by the volume of spins inside axons (cylinders), which is proportional to cylinder surface and not to diameter.
Parameters: alpha : float,
shape of the gamma distribution.
beta : float,
scale of the gamma distrubution. Different from Bingham distribution!
References
[R22] (1, 2) Assaf, Yaniv, et al. “AxCaliber: a method for measuring axon diameter distribution from diffusion MRI.” Magnetic resonance in medicine 59.6 (2008): 13471354. Attributes
Methods

__init__
(alpha=None, beta=None, Nsteps=30, normalization='standard')¶

calculate_sampling_start_and_end_points
(norm_func, gridsize=50) For a given normalization function calculates the best start and end points to sample for all possible values of alpha, beta. This is done to make sure the function does not sample where the probability of basically zero.
The function is based on first doing a dense sampling and then finding out which points need to be included to have sampled at least 99% of the area under the probability density curve.
It sets two interpolator functions that can be called for any combination of alpha,beta and to return the appropriate start and end sampling points.
Parameters: norm_func : normalization function,
normalization of the model, depends on if it’s a sphere/cylinder.
gridsize : integer,
value that decides how big the grid will be on which we define the start and end sampling points.

length_plane
(radius) The distance normalization function for planes.

surface_cylinder
(radius) The surface normalization function for cylinders.

unity
(radius) The standard normalization for the Gamma distribution (none).

volume_sphere
(radius) The volume normalization function for spheres.

HemiSphere
¶

class
dmipy.distributions.distributions.
HemiSphere
(x=None, y=None, z=None, theta=None, phi=None, xyz=None, faces=None, edges=None, tol=1e05)¶ Bases:
dipy.core.sphere.Sphere
Points on the unit sphere.
A HemiSphere is similar to a Sphere but it takes antipodal symmetry into account. Antipodal symmetry means that point v on a HemiSphere is the same as the point v. Duplicate points are discarded when constructing a HemiSphere (including antipodal duplicates). edges and faces are remapped to the remaining points as closely as possible.
The HemiSphere can be constructed using one of three conventions:
HemiSphere(x, y, z) HemiSphere(xyz=xyz) HemiSphere(theta=theta, phi=phi)
Parameters: x, y, z : 1D array_like
Vertices as xyz coordinates.
theta, phi : 1D array_like
Vertices as spherical coordinates. Theta and phi are the inclination and azimuth angles respectively.
xyz : (N, 3) ndarray
Vertices as xyz coordinates.
faces : (N, 3) ndarray
Indices into vertices that form triangular faces. If unspecified, the faces are computed using a Delaunay triangulation.
edges : (N, 2) ndarray
Edges between vertices. If unspecified, the edges are derived from the faces.
tol : float
Angle in degrees. Vertices that are less than tol degrees apart are treated as duplicates.
See also
Sphere
Attributes
Methods

__init__
(x=None, y=None, z=None, theta=None, phi=None, xyz=None, faces=None, edges=None, tol=1e05)¶ Create a HemiSphere from points

faces
()¶

find_closest
(xyz)¶ Find the index of the vertex in the Sphere closest to the input vector, taking into account antipodal symmetry
Parameters: xyz : arraylike, 3 elements
A unit vector

classmethod
from_sphere
(klass, sphere, tol=1e05)¶ Create instance from a Sphere

mirror
()¶ Create a full Sphere from a HemiSphere

subdivide
(n=1)¶ Create a more subdivided HemiSphere
See Sphere.subdivide for full documentation.

ModelProperties
¶

class
dmipy.distributions.distributions.
ModelProperties
¶ Contains various properties for CompartmentModels.
Attributes

parameter_cardinality
¶ Returns the cardinality of model parameters

parameter_names
¶ Returns the names of model parameters.

parameter_ranges
¶ Returns the optimization ranges of the model parameters. These ranges are given in O(1) scale so optimization algorithms don’t suffer from large scale differences in optimization parameters.

parameter_scales
¶ Returns the optimization scales for the model parameters. The scales scale the parameter_ranges to their actual size inside optimization algorithms.

parameter_types
¶ Returns the optimization scales for the model parameters. The scales scale the parameter_ranges to their actual size inside optimization algorithms.

SD1Watson
¶

class
dmipy.distributions.distributions.
SD1Watson
(mu=None, odi=None) Bases:
dmipy.core.modeling_framework.ModelProperties
The Watson spherical distribution model [R23] [R24].
Parameters: mu : array, shape(2),
angles [theta, phi] representing main orientation on the sphere. theta is inclination of polar angle of main angle mu [0, pi]. phi is polar angle of main angle mu [pi, pi].
kappa : float,
concentration parameter of the Watson distribution.
References
[R23] (1, 2) Kaden et al. “Parametric spherical deconvolution: inferring anatomical
connectivity using diffusion MR imaging”. NeuroImage (2007)[R24] (1, 2) Zhang et al. “NODDI: practical in vivo neurite orientation dispersion and density
imaging of the human brain”. NeuroImage (2012)Attributes
Methods

__init__
(mu=None, odi=None)¶

spherical_harmonics_representation
(sh_order=None, **kwargs) The Watson spherical distribution model in spherical harmonics. The minimum order is automatically derived from numerical experiments to ensure fast function executation and accurate results.
Parameters: sh_order : int,
maximum spherical harmonics order to be used in the approximation.
Returns: watson_sh : array,
spherical harmonics of Watson probability density.

SD2Bingham
¶

class
dmipy.distributions.distributions.
SD2Bingham
(mu=None, psi=None, odi=None, beta_fraction=None) Bases:
dmipy.core.modeling_framework.ModelProperties
The Bingham spherical distribution model [R25] [R26] [R27] using angles.
Parameters: mu : array, shape(2),
angles [theta, phi] representing main orientation on the sphere. theta is inclination of polar angle of main angle mu [0, pi]. phi is polar angle of main angle mu [pi, pi].
psi : float,
angle in radians of the bingham distribution around mu [0, pi].
kappa : float,
first concentration parameter of the Bingham distribution. defined as kappa = kappa1  kappa3.
beta : float,
second concentration parameter of the Bingham distribution. defined as beta = kappa2  kappa3. Bingham becomes Watson when beta=0.
References
[R25] (1, 2) Kaden et al. “Parametric spherical deconvolution: inferring anatomical
connectivity using diffusion MR imaging”. NeuroImage (2007)[R26] (1, 2) Sotiropoulos et al. “Ball and rackets: inferring fiber fanning from
diffusionweighted MRI”. NeuroImage (2012)[R27] (1, 2) Tariq et al. “Bingham–NODDI: Mapping anisotropic orientation dispersion of
neurites using diffusion MRI”. NeuroImage (2016)Attributes
Methods

__init__
(mu=None, psi=None, odi=None, beta_fraction=None)¶

spherical_harmonics_representation
(sh_order=None, **kwargs) The Bingham spherical distribution model in spherical harmonics. The minimum order is automatically derived from numerical experiments to ensure fast function executation and accurate results.
Parameters: sh_order : int,
maximum spherical harmonics order to be used in the approximation.
Returns: bingham_sh : array,
spherical harmonics of Bingham probability density.

get_sh_order_from_odi¶

dmipy.distributions.distributions.
get_sh_order_from_odi
(odi) Returns minimum sh_order to estimate spherical harmonics for given odi.
get_sphere¶

dmipy.distributions.distributions.
get_sphere
(name='symmetric362')¶ provide triangulated spheres
Parameters: name : str
which sphere  one of: * ‘symmetric362’ * ‘symmetric642’ * ‘symmetric724’ * ‘repulsion724’ * ‘repulsion100’ * ‘repulsion200’
Returns: sphere : a dipy.core.sphere.Sphere class instance
Examples
>>> import numpy as np >>> from dipy.data import get_sphere >>> sphere = get_sphere('symmetric362') >>> verts, faces = sphere.vertices, sphere.faces >>> verts.shape == (362, 3) True >>> faces.shape == (720, 3) True >>> verts, faces = get_sphere('not a sphere name') Traceback (most recent call last): ... DataError: No sphere called "not a sphere name"
join¶

dmipy.distributions.distributions.
join
(a, *p)¶ Join two or more pathname components, inserting ‘/’ as needed. If any component is an absolute path, all previous path components will be discarded. An empty last part will result in a path that ends with a separator.
kappa2odi¶

dmipy.distributions.distributions.
kappa2odi
(kappa) Calculates orientation dispersion index (odi) from concentration (kappa).
odi2kappa¶

dmipy.distributions.distributions.
odi2kappa
(odi) Calculates concentration (kappa) from orientation dispersion index (odi).
optional_package¶

dmipy.distributions.distributions.
optional_package
(name, trip_msg=None)¶ Return packagelike thing and module setup for package name
Parameters: name : str
package name
trip_msg : None or str
message to give when someone tries to use the return package, but we could not import it, and have returned a TripWire object instead. Default message if None.
Returns: pkg_like : module or
TripWire
instanceIf we can import the package, return it. Otherwise return an object raising an error when accessed
have_pkg : bool
True if import for package was successful, false otherwise
module_setup : function
callable usually set as
setup_module
in calling namespace, to allow skipping tests.
real_sym_sh_mrtrix¶

dmipy.distributions.distributions.
real_sym_sh_mrtrix
(sh_order, theta, phi)¶ Compute real spherical harmonics as in mrtrix, where the real harmonic \(Y^m_n\) is defined to be:
Real(:math:`Y^m_n`) if m > 0 :math:`Y^0_n` if m = 0 Imag(:math:`Y^m_n`) if m < 0
This may take scalar or array arguments. The inputs will be broadcasted against each other.
Parameters: sh_order : int
The maximum degree or the spherical harmonic basis.
theta : float [0, pi]
The polar (colatitudinal) coordinate.
phi : float [0, 2*pi]
The azimuthal (longitudinal) coordinate.
Returns: y_mn : real float
The real harmonic \(Y^m_n\) sampled at theta and phi as implemented in mrtrix. Warning: the basis is Tournier et al 2004 and 2007 is slightly different.
m : array
The order of the harmonics.
n : array
The degree of the harmonics.
hcp_interface
¶
Module: hcp_interface.downloader_aws
¶

class
dmipy.hcp_interface.downloader_aws.
HCPInterface
(your_aws_public_key, your_aws_secret_key)¶ Function to download HCP data directly from AWS server. Since HCP requires you to sign its user agreements, this function takes as input the user’s personal public and secret AWS key.
These keys can be generated following the the instructions here: https://wiki.humanconnectome.org/display/PublicData/How+To+Connect+to+Connectome+Data+via+AWS
The reason this function is set up this way is because we cannot sign the user agreement for the user. Now, the user takes its own responsibility and we can provide this convenient downloader without having to go through the HCP interface.
Parameters: your_aws_public_key : string
user aws public key
your_aws_secret_key : string
user aws secret key
Attributes
Methods

available_subjects
¶

download_and_prepare_dmipy_example_dataset
()¶ Downloads subect 100307 of the WuMinn HCP data and prepares it to be used for the dmipy example notebooks.

download_subject
(subject_ID)¶ Downloads WuMinn HCP subject data to the dmipy data folder. The downloaded data includes the bvalues, gradient orientations, diffusionweighted images and the binary brain mask.
Parameters: subject_ID: integer :
the identification number of the WuMinn HCP subject

prepare_example_slice
(subject_ID)¶ Prepares a coronal slice for the dmipy example notebooks.

HCPInterface
¶

class
dmipy.hcp_interface.downloader_aws.
HCPInterface
(your_aws_public_key, your_aws_secret_key) Function to download HCP data directly from AWS server. Since HCP requires you to sign its user agreements, this function takes as input the user’s personal public and secret AWS key.
These keys can be generated following the the instructions here: https://wiki.humanconnectome.org/display/PublicData/How+To+Connect+to+Connectome+Data+via+AWS
The reason this function is set up this way is because we cannot sign the user agreement for the user. Now, the user takes its own responsibility and we can provide this convenient downloader without having to go through the HCP interface.
Parameters: your_aws_public_key : string
user aws public key
your_aws_secret_key : string
user aws secret key
Attributes
Methods

__init__
(your_aws_public_key, your_aws_secret_key)¶

available_subjects

download_and_prepare_dmipy_example_dataset
() Downloads subect 100307 of the WuMinn HCP data and prepares it to be used for the dmipy example notebooks.

download_subject
(subject_ID) Downloads WuMinn HCP subject data to the dmipy data folder. The downloaded data includes the bvalues, gradient orientations, diffusionweighted images and the binary brain mask.
Parameters: subject_ID: integer :
the identification number of the WuMinn HCP subject

prepare_example_slice
(subject_ID) Prepares a coronal slice for the dmipy example notebooks.

optimizers
¶
Module: optimizers.brute2fine
¶

class
dmipy.optimizers.brute2fine.
GlobalBruteOptimizer
(model, acquisition_scheme, x0_vector=None, Ns=5, N_sphere_samples=30)¶ BruteForce optimizer. Given a model and an acquisition scheme, first computes a global grid of parameters and corresponding signal attenuations. All parameters except the spherical orientation parameter ‘mu’ are sampled between their corresponding parameter_ranges in ‘Ns’ equal steps. For ‘mu’ a spherical grid of ‘N_sphere_samples” points is used, which were generated using the work of Caruyer et al. [1].
When calling the function with measured data, the closest parameters are return based on the sumsquared error between the signal grid and the data.
Parameters: model: dmipy MultiCompartmentModel instance, :
Can be composed of any model combination.
acquisition_scheme: DmipyAcquisitionScheme instance, :
acquisition scheme of the tobefitted data.
x0_vector: array of size (Nparameters,) :
optional initial guess parameters. As long as the initial guess does not vary voxelbyvoxel the parameter grid will be estimated, only including the initial guess value for the parameters that were included in x0_vector.
Ns: integer, :
number of equally spaced sampling points for regular parameters.
N_sphere_sampled: integer, :
number of sampled sphere points to sample orientation ‘mu’.
References
[R28] Caruyer, Emmanuel, et al. “Design of multishell sampling schemes with uniform coverage in diffusion MRI.” Magnetic resonance in medicine 69.6 (2013): 15341540. Methods

precompute_signal_grid
(model, x0_vector, Ns, N_sphere_samples)¶ Function that estimates the parameter grid and corresponding signal attenuation.
NOTE: In the current implementation initial guesses for volume fractions are still ignored


class
dmipy.optimizers.brute2fine.
Brute2FineOptimizer
(model, acquisition_scheme, Ns=5)¶ Brute force optimizer with refining. Essentially this function does both the brute force optimization like GlobalBruteOptimizer (without treating mu differently, which is currently suboptimal), but then follows it with a gradientdescent based refining step [1, 2] to find the local minimum.
All parameters are optimized within their parameter_bounds. Volume fraction are optimized by ‘nesting’ them, such that given a set of models \(m_1...m_N\), and the partial volume ratios math:v_1…v_{N1}, the partial volume function is
\[v_1 m_1 + (1  v_1) v_2 m_2 + ... + (1  v_1)...(1v_{N1}) m_N\]Parameters: model: dmipy MultiCompartmentModel instance, :
Can be composed of any model combination.
acquisition_scheme: DmipyAcquisitionScheme instance, :
acquisition scheme of the tobefitted data.
Ns: integer, :
number of equally spaced sampling points for regular parameters.
References
[R29] Byrd, R H and P Lu and J. Nocedal. 1995. A Limited Memory Algorithm for Bound Constrained Optimization. SIAM Journal on Scientific and Statistical Computing 16 (5): 11901208. [R30] Zhu, C and R H Byrd and J Nocedal. 1997. LBFGSB: Algorithm 778: LBFGSB, FORTRAN routines for large scale bound constrained optimization. ACM Transactions on Mathematical Software 23 (4): 550560. Methods

objective_function
(parameter_vector, data)¶ The objective function for bruteforce and gradientbased optimizer.


dmipy.optimizers.brute2fine.
nested_to_normalized_fractions
(nested_fractions)¶ Calculates the normal volume fractions from nested ones.

dmipy.optimizers.brute2fine.
normalized_to_nested_fractions_array
(normalized_fractions)¶ Calculates the nested volume fractions from normal ones.

dmipy.optimizers.brute2fine.
find_minimum_argument
(data_grid, signal)¶ Finds the index in the simulated data_grid that has the lowest sumsquared error to the signal.
Module: optimizers.mix
¶

class
dmipy.optimizers.mix.
MixOptimizer
(model, acquisition_scheme, maxiter=150)¶ The stochastic Microstructure In Crossings (MIX) optimizer [1] uses a threestep process to fit the parameters of a multicompartment (MC) model to data. The key innovation is that they separate linear from nonlinear parameters in the fitting process, meaning the linear volume fractions and nonlinear other ones(e.g. diffusivities) are optimized at different stages in the process.
In the first step [1] describes using a genetic algorithm to estimate the nonlinear parameters of an MC model. For this we use scipy’s differential_evolution algorithm.
In the second step [1] describes using CVX to estimate the linear volume fractions of an MC model. For this we use scipy’s COBYLA algorithm since it allows us to impose the parameter constraints we need for volume fractions; namely that they are positive and sum up to one.
The third and last step in [1] is a refining step to find a local minimum given the solutions of step one and two. For this we use scipy’s gradientbased LBFGSB algorithm with nested volume fractions.
The final result takes a model’s parameter_ranges into account, only yielding parameters within their allowed optimization domain.
Parameters: model : MultiCompartmentModel instance,
A multicompartment model that has been instantiated using dMipy.
acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
maxiter : integer
The maximum allowed iterations for the differential evolution algorithm
References
[R31] Farooq, Hamza, et al. “Microstructure Imaging of Crossing (MIX) White Matter Fibers from diffusion MRI.” Nature Scientific reports 6 (2016). Methods

cobyla_cost_function
(fractions, phi, data)¶ Objective function of linear parameter estimation using COBYLA.

objective_function
(optimized_parameter_vector, data, acquisition_scheme, x0_params)¶ Objective function of final refining step using LBFGSB

stochastic_objective_function
(optimized_parameter_vector, data, acquisition_scheme, x0_params)¶ Objective function for stochastic nonlinear parameter estimation using differential_evolution


dmipy.optimizers.mix.
nested_to_normalized_fractions
(nested_fractions)¶ Function to convert nested to normalized volume fractions.

dmipy.optimizers.mix.
cobyla_positivity_constraint
(volume_fractions, *args)¶ COBYLA positivity constraint on volume fractions

dmipy.optimizers.mix.
cobyla_unity_constraint
(volume_fractions, *args)¶ COBYLA unity constraint on volume fractions
Brute2FineOptimizer
¶

class
dmipy.optimizers.brute2fine.
Brute2FineOptimizer
(model, acquisition_scheme, Ns=5) Brute force optimizer with refining. Essentially this function does both the brute force optimization like GlobalBruteOptimizer (without treating mu differently, which is currently suboptimal), but then follows it with a gradientdescent based refining step [1, 2] to find the local minimum.
All parameters are optimized within their parameter_bounds. Volume fraction are optimized by ‘nesting’ them, such that given a set of models \(m_1...m_N\), and the partial volume ratios math:v_1…v_{N1}, the partial volume function is
\[v_1 m_1 + (1  v_1) v_2 m_2 + ... + (1  v_1)...(1v_{N1}) m_N\]Parameters: model: dmipy MultiCompartmentModel instance, :
Can be composed of any model combination.
acquisition_scheme: DmipyAcquisitionScheme instance, :
acquisition scheme of the tobefitted data.
Ns: integer, :
number of equally spaced sampling points for regular parameters.
References
[R32] Byrd, R H and P Lu and J. Nocedal. 1995. A Limited Memory Algorithm for Bound Constrained Optimization. SIAM Journal on Scientific and Statistical Computing 16 (5): 11901208. [R33] Zhu, C and R H Byrd and J Nocedal. 1997. LBFGSB: Algorithm 778: LBFGSB, FORTRAN routines for large scale bound constrained optimization. ACM Transactions on Mathematical Software 23 (4): 550560. Methods

__init__
(model, acquisition_scheme, Ns=5)¶

objective_function
(parameter_vector, data) The objective function for bruteforce and gradientbased optimizer.

GlobalBruteOptimizer
¶

class
dmipy.optimizers.brute2fine.
GlobalBruteOptimizer
(model, acquisition_scheme, x0_vector=None, Ns=5, N_sphere_samples=30) BruteForce optimizer. Given a model and an acquisition scheme, first computes a global grid of parameters and corresponding signal attenuations. All parameters except the spherical orientation parameter ‘mu’ are sampled between their corresponding parameter_ranges in ‘Ns’ equal steps. For ‘mu’ a spherical grid of ‘N_sphere_samples” points is used, which were generated using the work of Caruyer et al. [1].
When calling the function with measured data, the closest parameters are return based on the sumsquared error between the signal grid and the data.
Parameters: model: dmipy MultiCompartmentModel instance, :
Can be composed of any model combination.
acquisition_scheme: DmipyAcquisitionScheme instance, :
acquisition scheme of the tobefitted data.
x0_vector: array of size (Nparameters,) :
optional initial guess parameters. As long as the initial guess does not vary voxelbyvoxel the parameter grid will be estimated, only including the initial guess value for the parameters that were included in x0_vector.
Ns: integer, :
number of equally spaced sampling points for regular parameters.
N_sphere_sampled: integer, :
number of sampled sphere points to sample orientation ‘mu’.
References
[R34] Caruyer, Emmanuel, et al. “Design of multishell sampling schemes with uniform coverage in diffusion MRI.” Magnetic resonance in medicine 69.6 (2013): 15341540. Methods

__init__
(model, acquisition_scheme, x0_vector=None, Ns=5, N_sphere_samples=30)¶

precompute_signal_grid
(model, x0_vector, Ns, N_sphere_samples) Function that estimates the parameter grid and corresponding signal attenuation.
NOTE: In the current implementation initial guesses for volume fractions are still ignored

brute¶

dmipy.optimizers.brute2fine.
brute
(func, ranges, args=(), Ns=20, full_output=0, finish=<function fmin>, disp=False)¶ Minimize a function over a given range by brute force.
Uses the “brute force” method, i.e. computes the function’s value at each point of a multidimensional grid of points, to find the global minimum of the function.
The function is evaluated everywhere in the range with the datatype of the first call to the function, as enforced by the
vectorize
NumPy function. The value and type of the function evaluation returned whenfull_output=True
are affected in addition by thefinish
argument (see Notes).Parameters: func : callable
The objective function to be minimized. Must be in the form
f(x, *args)
, wherex
is the argument in the form of a 1D array andargs
is a tuple of any additional fixed parameters needed to completely specify the function.ranges : tuple
Each component of the ranges tuple must be either a “slice object” or a range tuple of the form
(low, high)
. The program uses these to create the grid of points on which the objective function will be computed. See Note 2 for more detail.args : tuple, optional
Any additional fixed parameters needed to completely specify the function.
Ns : int, optional
Number of grid points along the axes, if not otherwise specified. See Note2.
full_output : bool, optional
If True, return the evaluation grid and the objective function’s values on it.
finish : callable, optional
An optimization function that is called with the result of brute force minimization as initial guess. finish should take func and the initial guess as positional arguments, and take args as keyword arguments. It may additionally take full_output and/or disp as keyword arguments. Use None if no “polishing” function is to be used. See Notes for more details.
disp : bool, optional
Set to True to print convergence messages.
Returns: x0 : ndarray
A 1D array containing the coordinates of a point at which the objective function had its minimum value. (See Note 1 for which point is returned.)
fval : float
Function value at the point x0. (Returned when full_output is True.)
grid : tuple
Representation of the evaluation grid. It has the same length as x0. (Returned when full_output is True.)
Jout : ndarray
Function values at each point of the evaluation grid, i.e.,
Jout = func(*grid)
. (Returned when full_output is True.)See also
basinhopping
,differential_evolution
Notes
Note 1: The program finds the gridpoint at which the lowest value of the objective function occurs. If finish is None, that is the point returned. When the global minimum occurs within (or not very far outside) the grid’s boundaries, and the grid is fine enough, that point will be in the neighborhood of the global minimum.
However, users often employ some other optimization program to “polish” the gridpoint values, i.e., to seek a more precise (local) minimum near brute’s best gridpoint. The brute function’s finish option provides a convenient way to do that. Any polishing program used must take brute’s output as its initial guess as a positional argument, and take brute’s input values for args as keyword arguments, otherwise an error will be raised. It may additionally take full_output and/or disp as keyword arguments.
brute assumes that the finish function returns either an OptimizeResult object or a tuple in the form:
(xmin, Jmin, ... , statuscode)
, wherexmin
is the minimizing value of the argument,Jmin
is the minimum value of the objective function, “…” may be some other returned values (which are not used by brute), andstatuscode
is the status code of the finish program.Note that when finish is not None, the values returned are those of the finish program, not the gridpoint ones. Consequently, while brute confines its search to the input grid points, the finish program’s results usually will not coincide with any gridpoint, and may fall outside the grid’s boundary. Thus, if a minimum only needs to be found over the provided grid points, make sure to pass in finish=None.
Note 2: The grid of points is a numpy.mgrid object. For brute the ranges and Ns inputs have the following effect. Each component of the ranges tuple can be either a slice object or a twotuple giving a range of values, such as (0, 5). If the component is a slice object, brute uses it directly. If the component is a twotuple range, brute internally converts it to a slice object that interpolates Ns points from its lowvalue to its highvalue, inclusive.
Examples
We illustrate the use of brute to seek the global minimum of a function of two variables that is given as the sum of a positivedefinite quadratic and two deep “Gaussianshaped” craters. Specifically, define the objective function f as the sum of three other functions,
f = f1 + f2 + f3
. We suppose each of these has a signature(z, *params)
, wherez = (x, y)
, andparams
and the functions are as defined below.>>> params = (2, 3, 7, 8, 9, 10, 44, 1, 2, 26, 1, 2, 0.5) >>> def f1(z, *params): ... x, y = z ... a, b, c, d, e, f, g, h, i, j, k, l, scale = params ... return (a * x**2 + b * x * y + c * y**2 + d*x + e*y + f)
>>> def f2(z, *params): ... x, y = z ... a, b, c, d, e, f, g, h, i, j, k, l, scale = params ... return (g*np.exp(((xh)**2 + (yi)**2) / scale))
>>> def f3(z, *params): ... x, y = z ... a, b, c, d, e, f, g, h, i, j, k, l, scale = params ... return (j*np.exp(((xk)**2 + (yl)**2) / scale))
>>> def f(z, *params): ... return f1(z, *params) + f2(z, *params) + f3(z, *params)
Thus, the objective function may have local minima near the minimum of each of the three functions of which it is composed. To use fmin to polish its gridpoint result, we may then continue as follows:
>>> rranges = (slice(4, 4, 0.25), slice(4, 4, 0.25)) >>> from scipy import optimize >>> resbrute = optimize.brute(f, rranges, args=params, full_output=True, ... finish=optimize.fmin) >>> resbrute[0] # global minimum array([1.05665192, 1.80834843]) >>> resbrute[1] # function value at global minimum 3.4085818767
Note that if finish had been set to None, we would have gotten the gridpoint [1.0 1.75] where the rounded function value is 2.892.
cart2mu¶

dmipy.optimizers.brute2fine.
cart2mu
(xyz)¶ Function to estimate spherical coordinates from cartesian coordinates according to wikipedia. Conforms with the dipy notation.
Parameters: cartesian_coordinates : array of size (3) or (N x 3),
array of cartesian coordinate vectors [x, y, z].
Returns: spherical_coordinates : array of size (2) or (N x 2),
array of spherical coordinate vectors [theta, phi]. range of theta [0, pi]. range of phi [pi, pi].
find_minimum_argument¶

dmipy.optimizers.brute2fine.
find_minimum_argument
(data_grid, signal) Finds the index in the simulated data_grid that has the lowest sumsquared error to the signal.
minimize¶

dmipy.optimizers.brute2fine.
minimize
(fun, x0, args=(), method=None, jac=None, hess=None, hessp=None, bounds=None, constraints=(), tol=None, callback=None, options=None)¶ Minimization of scalar function of one or more variables.
In general, the optimization problems are of the form:
minimize f(x) subject to g_i(x) >= 0, i = 1,...,m h_j(x) = 0, j = 1,...,p
where x is a vector of one or more variables.
g_i(x)
are the inequality constraints.h_j(x)
are the equality constrains.Optionally, the lower and upper bounds for each element in x can also be specified using the bounds argument.
Parameters: fun : callable
The objective function to be minimized. Must be in the form
f(x, *args)
. The optimizing argument,x
, is a 1D array of points, andargs
is a tuple of any additional fixed parameters needed to completely specify the function.x0 : ndarray
Initial guess.
len(x0)
is the dimensionality of the minimization problem.args : tuple, optional
Extra arguments passed to the objective function and its derivatives (Jacobian, Hessian).
method : str or callable, optional
Type of solver. Should be one of
 ‘NelderMead’ (see here)
 ‘Powell’ (see here)
 ‘CG’ (see here)
 ‘BFGS’ (see here)
 ‘NewtonCG’ (see here)
 ‘LBFGSB’ (see here)
 ‘TNC’ (see here)
 ‘COBYLA’ (see here)
 ‘SLSQP’ (see here)
 ‘dogleg’ (see here)
 ‘trustncg’ (see here)
 ‘trustexact’ (see here)
 ‘trustkrylov’ (see here)
 custom  a callable object (added in version 0.14.0), see below for description.
If not given, chosen to be one of
BFGS
,LBFGSB
,SLSQP
, depending if the problem has constraints or bounds.jac : bool or callable, optional
Jacobian (gradient) of objective function. Only for CG, BFGS, NewtonCG, LBFGSB, TNC, SLSQP, dogleg, trustncg, trustkrylov, trustregionexact. If jac is a Boolean and is True, fun is assumed to return the gradient along with the objective function. If False, the gradient will be estimated numerically. jac can also be a callable returning the gradient of the objective. In this case, it must accept the same arguments as fun.
hess, hessp : callable, optional
Hessian (matrix of secondorder derivatives) of objective function or Hessian of objective function times an arbitrary vector p. Only for NewtonCG, dogleg, trustncg, trustkrylov, trustregionexact. Only one of hessp or hess needs to be given. If hess is provided, then hessp will be ignored. If neither hess nor hessp is provided, then the Hessian product will be approximated using finite differences on jac. hessp must compute the Hessian times an arbitrary vector.
bounds : sequence, optional
Bounds for variables (only for LBFGSB, TNC and SLSQP).
(min, max)
pairs for each element inx
, defining the bounds on that parameter. Use None for one ofmin
ormax
when there is no bound in that direction.constraints : dict or sequence of dict, optional
Constraints definition (only for COBYLA and SLSQP). Each constraint is defined in a dictionary with fields:
 type : str
Constraint type: ‘eq’ for equality, ‘ineq’ for inequality.
 fun : callable
The function defining the constraint.
 jac : callable, optional
The Jacobian of fun (only for SLSQP).
 args : sequence, optional
Extra arguments to be passed to the function and Jacobian.
Equality constraint means that the constraint function result is to be zero whereas inequality means that it is to be nonnegative. Note that COBYLA only supports inequality constraints.
tol : float, optional
Tolerance for termination. For detailed control, use solverspecific options.
options : dict, optional
A dictionary of solver options. All methods accept the following generic options:
 maxiter : int
Maximum number of iterations to perform.
 disp : bool
Set to True to print convergence messages.
For methodspecific options, see
show_options()
.callback : callable, optional
Called after each iteration, as
callback(xk)
, wherexk
is the current parameter vector.Returns: res : OptimizeResult
The optimization result represented as a
OptimizeResult
object. Important attributes are:x
the solution array,success
a Boolean flag indicating if the optimizer exited successfully andmessage
which describes the cause of the termination. See OptimizeResult for a description of other attributes.See also
minimize_scalar
 Interface to minimization algorithms for scalar univariate functions
show_options
 Additional options accepted by the solvers
Notes
This section describes the available solvers that can be selected by the ‘method’ parameter. The default method is BFGS.
Unconstrained minimization
Method NelderMead uses the Simplex algorithm [R35], [R36]. This algorithm is robust in many applications. However, if numerical computation of derivative can be trusted, other algorithms using the first and/or second derivatives information might be preferred for their better performance in general.
Method Powell is a modification of Powell’s method [R37], [R38] which is a conjugate direction method. It performs sequential onedimensional minimizations along each vector of the directions set (direc field in options and info), which is updated at each iteration of the main minimization loop. The function need not be differentiable, and no derivatives are taken.
Method CG uses a nonlinear conjugate gradient algorithm by Polak and Ribiere, a variant of the FletcherReeves method described in [R39] pp. 120122. Only the first derivatives are used.
Method BFGS uses the quasiNewton method of Broyden, Fletcher, Goldfarb, and Shanno (BFGS) [R39] pp. 136. It uses the first derivatives only. BFGS has proven good performance even for nonsmooth optimizations. This method also returns an approximation of the Hessian inverse, stored as hess_inv in the OptimizeResult object.
Method NewtonCG uses a NewtonCG algorithm [R39] pp. 168 (also known as the truncated Newton method). It uses a CG method to the compute the search direction. See also TNC method for a boxconstrained minimization with a similar algorithm. Suitable for largescale problems.
Method dogleg uses the dogleg trustregion algorithm [R39] for unconstrained minimization. This algorithm requires the gradient and Hessian; furthermore the Hessian is required to be positive definite.
Method trustncg uses the Newton conjugate gradient trustregion algorithm [R39] for unconstrained minimization. This algorithm requires the gradient and either the Hessian or a function that computes the product of the Hessian with a given vector. Suitable for largescale problems.
Method trustkrylov uses the Newton GLTR trustregion algorithm [14]_, [15]_ for unconstrained minimization. This algorithm requires the gradient and either the Hessian or a function that computes the product of the Hessian with a given vector. Suitable for largescale problems. On indefinite problems it requires usually less iterations than the trustncg method and is recommended for medium and largescale problems.
Method trustexact is a trustregion method for unconstrained minimization in which quadratic subproblems are solved almost exactly [13]_. This algorithm requires the gradient and the Hessian (which is not required to be positive definite). It is, in many situations, the Newton method to converge in fewer iteraction and the most recommended for small and mediumsize problems.
Constrained minimization
Method LBFGSB uses the LBFGSB algorithm [R40], [R41] for bound constrained minimization.
Method TNC uses a truncated Newton algorithm [R39], [R42] to minimize a function with variables subject to bounds. This algorithm uses gradient information; it is also called Newton ConjugateGradient. It differs from the NewtonCG method described above as it wraps a C implementation and allows each variable to be given upper and lower bounds.
Method COBYLA uses the Constrained Optimization BY Linear Approximation (COBYLA) method [R43], [10]_, [11]_. The algorithm is based on linear approximations to the objective function and each constraint. The method wraps a FORTRAN implementation of the algorithm. The constraints functions ‘fun’ may return either a single number or an array or list of numbers.
Method SLSQP uses Sequential Least SQuares Programming to minimize a function of several variables with any combination of bounds, equality and inequality constraints. The method wraps the SLSQP Optimization subroutine originally implemented by Dieter Kraft [12]_. Note that the wrapper handles infinite values in bounds by converting them into large floating values.
Custom minimizers
It may be useful to pass a custom minimization method, for example when using a frontend to this method such as scipy.optimize.basinhopping or a different library. You can simply pass a callable as the
method
parameter.The callable is called as
method(fun, x0, args, **kwargs, **options)
wherekwargs
corresponds to any other parameters passed to minimize (such as callback, hess, etc.), except the options dict, which has its contents also passed as method parameters pair by pair. Also, if jac has been passed as a bool type, jac and fun are mangled so that fun returns just the function values and jac is converted to a function returning the Jacobian. The method shall return anOptimizeResult
object.The provided method callable must be able to accept (and possibly ignore) arbitrary parameters; the set of parameters accepted by minimize may expand in future versions and then these parameters will be passed to the method. You can find an example in the scipy.optimize tutorial.
New in version 0.11.0.
References
[R35] (1, 2) Nelder, J A, and R Mead. 1965. A Simplex Method for Function Minimization. The Computer Journal 7: 30813. [R36] (1, 2) Wright M H. 1996. Direct search methods: Once scorned, now respectable, in Numerical Analysis 1995: Proceedings of the 1995 Dundee Biennial Conference in Numerical Analysis (Eds. D F Griffiths and G A Watson). Addison Wesley Longman, Harlow, UK. 191208. [R37] (1, 2) Powell, M J D. 1964. An efficient method for finding the minimum of a function of several variables without calculating derivatives. The Computer Journal 7: 155162. [R38] (1, 2) Press W, S A Teukolsky, W T Vetterling and B P Flannery. Numerical Recipes (any edition), Cambridge University Press. [R39] (1, 2, 3, 4, 5, 6, 7, 8) Nocedal, J, and S J Wright. 2006. Numerical Optimization. Springer New York. [R40] (1, 2) Byrd, R H and P Lu and J. Nocedal. 1995. A Limited Memory Algorithm for Bound Constrained Optimization. SIAM Journal on Scientific and Statistical Computing 16 (5): 11901208. [R41] (1, 2) Zhu, C and R H Byrd and J Nocedal. 1997. LBFGSB: Algorithm 778: LBFGSB, FORTRAN routines for large scale bound constrained optimization. ACM Transactions on Mathematical Software 23 (4): 550560. [R42] (1, 2) Nash, S G. NewtonType Minimization Via the Lanczos Method. 1984. SIAM Journal of Numerical Analysis 21: 770778. [R43] (1, 2) Powell, M J D. A direct search optimization method that models the objective and constraint functions by linear interpolation. 1994. Advances in Optimization and Numerical Analysis, eds. S. Gomez and JP Hennart, Kluwer Academic (Dordrecht), 5167. [10] Powell M J D. Direct search algorithms for optimization calculations. 1998. Acta Numerica 7: 287336. [11] Powell M J D. A view of algorithms for optimization without derivatives. 2007.Cambridge University Technical Report DAMTP 2007/NA03 [12] Kraft, D. A software package for sequential quadratic programming. 1988. Tech. Rep. DFVLRFB 8828, DLR German Aerospace Center – Institute for Flight Mechanics, Koln, Germany. [13] Conn, A. R., Gould, N. I., and Toint, P. L. Trust region methods. 2000. Siam. pp. 169200. [14] F. Lenders, C. Kirches, A. Potschka: “trlib: A vectorfree implementation of the GLTR method for iterative solution of the trust region problem”, https://arxiv.org/abs/1611.04718 [15] N. Gould, S. Lucidi, M. Roma, P. Toint: “Solving the TrustRegion Subproblem using the Lanczos Method”, SIAM J. Optim., 9(2), 504–525, (1999). Examples
Let us consider the problem of minimizing the Rosenbrock function. This function (and its respective derivatives) is implemented in rosen (resp. rosen_der, rosen_hess) in the scipy.optimize.
>>> from scipy.optimize import minimize, rosen, rosen_der
A simple application of the NelderMead method is:
>>> x0 = [1.3, 0.7, 0.8, 1.9, 1.2] >>> res = minimize(rosen, x0, method='NelderMead', tol=1e6) >>> res.x array([ 1., 1., 1., 1., 1.])
Now using the BFGS algorithm, using the first derivative and a few options:
>>> res = minimize(rosen, x0, method='BFGS', jac=rosen_der, ... options={'gtol': 1e6, 'disp': True}) Optimization terminated successfully. Current function value: 0.000000 Iterations: 26 Function evaluations: 31 Gradient evaluations: 31 >>> res.x array([ 1., 1., 1., 1., 1.]) >>> print(res.message) Optimization terminated successfully. >>> res.hess_inv array([[ 0.00749589, 0.01255155, 0.02396251, 0.04750988, 0.09495377], # may vary [ 0.01255155, 0.02510441, 0.04794055, 0.09502834, 0.18996269], [ 0.02396251, 0.04794055, 0.09631614, 0.19092151, 0.38165151], [ 0.04750988, 0.09502834, 0.19092151, 0.38341252, 0.7664427 ], [ 0.09495377, 0.18996269, 0.38165151, 0.7664427, 1.53713523]])
Next, consider a minimization problem with several constraints (namely Example 16.4 from [R39]). The objective function is:
>>> fun = lambda x: (x[0]  1)**2 + (x[1]  2.5)**2
There are three constraints defined as:
>>> cons = ({'type': 'ineq', 'fun': lambda x: x[0]  2 * x[1] + 2}, ... {'type': 'ineq', 'fun': lambda x: x[0]  2 * x[1] + 6}, ... {'type': 'ineq', 'fun': lambda x: x[0] + 2 * x[1] + 2})
And variables must be positive, hence the following bounds:
>>> bnds = ((0, None), (0, None))
The optimization problem is solved using the SLSQP method as:
>>> res = minimize(fun, (2, 0), method='SLSQP', bounds=bnds, ... constraints=cons)
It should converge to the theoretical solution (1.4 ,1.7).
nested_to_normalized_fractions¶

dmipy.optimizers.brute2fine.
nested_to_normalized_fractions
(nested_fractions) Calculates the normal volume fractions from nested ones.
normalized_to_nested_fractions_array¶

dmipy.optimizers.brute2fine.
normalized_to_nested_fractions_array
(normalized_fractions) Calculates the nested volume fractions from normal ones.
optional_package¶

dmipy.optimizers.brute2fine.
optional_package
(name, trip_msg=None)¶ Return packagelike thing and module setup for package name
Parameters: name : str
package name
trip_msg : None or str
message to give when someone tries to use the return package, but we could not import it, and have returned a TripWire object instead. Default message if None.
Returns: pkg_like : module or
TripWire
instanceIf we can import the package, return it. Otherwise return an object raising an error when accessed
have_pkg : bool
True if import for package was successful, false otherwise
module_setup : function
callable usually set as
setup_module
in calling namespace, to allow skipping tests.
MixOptimizer
¶

class
dmipy.optimizers.mix.
MixOptimizer
(model, acquisition_scheme, maxiter=150) The stochastic Microstructure In Crossings (MIX) optimizer [1] uses a threestep process to fit the parameters of a multicompartment (MC) model to data. The key innovation is that they separate linear from nonlinear parameters in the fitting process, meaning the linear volume fractions and nonlinear other ones(e.g. diffusivities) are optimized at different stages in the process.
In the first step [1] describes using a genetic algorithm to estimate the nonlinear parameters of an MC model. For this we use scipy’s differential_evolution algorithm.
In the second step [1] describes using CVX to estimate the linear volume fractions of an MC model. For this we use scipy’s COBYLA algorithm since it allows us to impose the parameter constraints we need for volume fractions; namely that they are positive and sum up to one.
The third and last step in [1] is a refining step to find a local minimum given the solutions of step one and two. For this we use scipy’s gradientbased LBFGSB algorithm with nested volume fractions.
The final result takes a model’s parameter_ranges into account, only yielding parameters within their allowed optimization domain.
Parameters: model : MultiCompartmentModel instance,
A multicompartment model that has been instantiated using dMipy.
acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
maxiter : integer
The maximum allowed iterations for the differential evolution algorithm
References
[R44] Farooq, Hamza, et al. “Microstructure Imaging of Crossing (MIX) White Matter Fibers from diffusion MRI.” Nature Scientific reports 6 (2016). Methods

__init__
(model, acquisition_scheme, maxiter=150)¶

cobyla_cost_function
(fractions, phi, data) Objective function of linear parameter estimation using COBYLA.

objective_function
(optimized_parameter_vector, data, acquisition_scheme, x0_params) Objective function of final refining step using LBFGSB

stochastic_objective_function
(optimized_parameter_vector, data, acquisition_scheme, x0_params) Objective function for stochastic nonlinear parameter estimation using differential_evolution

cobyla_positivity_constraint¶

dmipy.optimizers.mix.
cobyla_positivity_constraint
(volume_fractions, *args) COBYLA positivity constraint on volume fractions
cobyla_unity_constraint¶

dmipy.optimizers.mix.
cobyla_unity_constraint
(volume_fractions, *args) COBYLA unity constraint on volume fractions
differential_evolution¶

dmipy.optimizers.mix.
differential_evolution
(func, bounds, args=(), strategy='best1bin', maxiter=1000, popsize=15, tol=0.01, mutation=(0.5, 1), recombination=0.7, seed=None, callback=None, disp=False, polish=True, init='latinhypercube', atol=0)¶ Finds the global minimum of a multivariate function. Differential Evolution is stochastic in nature (does not use gradient methods) to find the minimium, and can search large areas of candidate space, but often requires larger numbers of function evaluations than conventional gradient based techniques.
The algorithm is due to Storn and Price [R45].
Parameters: func : callable
The objective function to be minimized. Must be in the form
f(x, *args)
, wherex
is the argument in the form of a 1D array andargs
is a tuple of any additional fixed parameters needed to completely specify the function.bounds : sequence
Bounds for variables.
(min, max)
pairs for each element inx
, defining the lower and upper bounds for the optimizing argument of func. It is required to havelen(bounds) == len(x)
.len(bounds)
is used to determine the number of parameters inx
.args : tuple, optional
Any additional fixed parameters needed to completely specify the objective function.
strategy : str, optional
The differential evolution strategy to use. Should be one of:
 ‘best1bin’
 ‘best1exp’
 ‘rand1exp’
 ‘randtobest1exp’
 ‘best2exp’
 ‘rand2exp’
 ‘randtobest1bin’
 ‘best2bin’
 ‘rand2bin’
 ‘rand1bin’
The default is ‘best1bin’.
maxiter : int, optional
The maximum number of generations over which the entire population is evolved. The maximum number of function evaluations (with no polishing) is:
(maxiter + 1) * popsize * len(x)
popsize : int, optional
A multiplier for setting the total population size. The population has
popsize * len(x)
individuals.tol : float, optional
Relative tolerance for convergence, the solving stops when
np.std(pop) <= atol + tol * np.abs(np.mean(population_energies))
, where and atol and tol are the absolute and relative tolerance respectively.mutation : float or tuple(float, float), optional
The mutation constant. In the literature this is also known as differential weight, being denoted by F. If specified as a float it should be in the range [0, 2]. If specified as a tuple
(min, max)
dithering is employed. Dithering randomly changes the mutation constant on a generation by generation basis. The mutation constant for that generation is taken fromU[min, max)
. Dithering can help speed convergence significantly. Increasing the mutation constant increases the search radius, but will slow down convergence.recombination : float, optional
The recombination constant, should be in the range [0, 1]. In the literature this is also known as the crossover probability, being denoted by CR. Increasing this value allows a larger number of mutants to progress into the next generation, but at the risk of population stability.
seed : int or np.random.RandomState, optional
If seed is not specified the np.RandomState singleton is used. If seed is an int, a new np.random.RandomState instance is used, seeded with seed. If seed is already a np.random.RandomState instance, then that np.random.RandomState instance is used. Specify seed for repeatable minimizations.
disp : bool, optional
Display status messages
callback : callable, callback(xk, convergence=val), optional
A function to follow the progress of the minimization.
xk
is the current value ofx0
.val
represents the fractional value of the population convergence. Whenval
is greater than one the function halts. If callback returns True, then the minimization is halted (any polishing is still carried out).polish : bool, optional
If True (default), then scipy.optimize.minimize with the LBFGSB method is used to polish the best population member at the end, which can improve the minimization slightly.
init : string, optional
Specify how the population initialization is performed. Should be one of:
 ‘latinhypercube’
 ‘random’
The default is ‘latinhypercube’. Latin Hypercube sampling tries to maximize coverage of the available parameter space. ‘random’ initializes the population randomly  this has the drawback that clustering can occur, preventing the whole of parameter space being covered.
atol : float, optional
Absolute tolerance for convergence, the solving stops when
np.std(pop) <= atol + tol * np.abs(np.mean(population_energies))
, where and atol and tol are the absolute and relative tolerance respectively.Returns: res : OptimizeResult
The optimization result represented as a OptimizeResult object. Important attributes are:
x
the solution array,success
a Boolean flag indicating if the optimizer exited successfully andmessage
which describes the cause of the termination. See OptimizeResult for a description of other attributes. If polish was employed, and a lower minimum was obtained by the polishing, then OptimizeResult also contains thejac
attribute.Notes
Differential evolution is a stochastic population based method that is useful for global optimization problems. At each pass through the population the algorithm mutates each candidate solution by mixing with other candidate solutions to create a trial candidate. There are several strategies [R46] for creating trial candidates, which suit some problems more than others. The ‘best1bin’ strategy is a good starting point for many systems. In this strategy two members of the population are randomly chosen. Their difference is used to mutate the best member (the best in best1bin), \(b_0\), so far:
\[b' = b_0 + mutation * (population[rand0]  population[rand1])\]A trial vector is then constructed. Starting with a randomly chosen ‘i’th parameter the trial is sequentially filled (in modulo) with parameters from b’ or the original candidate. The choice of whether to use b’ or the original candidate is made with a binomial distribution (the ‘bin’ in ‘best1bin’)  a random number in [0, 1) is generated. If this number is less than the recombination constant then the parameter is loaded from b’, otherwise it is loaded from the original candidate. The final parameter is always loaded from b’. Once the trial candidate is built its fitness is assessed. If the trial is better than the original candidate then it takes its place. If it is also better than the best overall candidate it also replaces that. To improve your chances of finding a global minimum use higher popsize values, with higher mutation and (dithering), but lower recombination values. This has the effect of widening the search radius, but slowing convergence.
New in version 0.15.0.
References
[R45] (1, 2) Storn, R and Price, K, Differential Evolution  a Simple and Efficient Heuristic for Global Optimization over Continuous Spaces, Journal of Global Optimization, 1997, 11, 341  359. [R46] (1, 2) http://www1.icsi.berkeley.edu/~storn/code.html [R47] http://en.wikipedia.org/wiki/Differential_evolution Examples
Let us consider the problem of minimizing the Rosenbrock function. This function is implemented in rosen in scipy.optimize.
>>> from scipy.optimize import rosen, differential_evolution >>> bounds = [(0,2), (0, 2), (0, 2), (0, 2), (0, 2)] >>> result = differential_evolution(rosen, bounds) >>> result.x, result.fun (array([1., 1., 1., 1., 1.]), 1.9216496320061384e19)
Next find the minimum of the Ackley function (http://en.wikipedia.org/wiki/Test_functions_for_optimization).
>>> from scipy.optimize import differential_evolution >>> import numpy as np >>> def ackley(x): ... arg1 = 0.2 * np.sqrt(0.5 * (x[0] ** 2 + x[1] ** 2)) ... arg2 = 0.5 * (np.cos(2. * np.pi * x[0]) + np.cos(2. * np.pi * x[1])) ... return 20. * np.exp(arg1)  np.exp(arg2) + 20. + np.e >>> bounds = [(5, 5), (5, 5)] >>> result = differential_evolution(ackley, bounds) >>> result.x, result.fun (array([ 0., 0.]), 4.4408920985006262e16)
fmin_cobyla¶

dmipy.optimizers.mix.
fmin_cobyla
(func, x0, cons, args=(), consargs=None, rhobeg=1.0, rhoend=0.0001, maxfun=1000, disp=None, catol=0.0002)¶ Minimize a function using the Constrained Optimization BY Linear Approximation (COBYLA) method. This method wraps a FORTRAN implementation of the algorithm.
Parameters: func : callable
Function to minimize. In the form func(x, *args).
x0 : ndarray
Initial guess.
cons : sequence
Constraint functions; must all be
>=0
(a single function if only 1 constraint). Each function takes the parameters x as its first argument, and it can return either a single number or an array or list of numbers.args : tuple, optional
Extra arguments to pass to function.
consargs : tuple, optional
Extra arguments to pass to constraint functions (default of None means use same extra arguments as those passed to func). Use
()
for no extra arguments.rhobeg : float, optional
Reasonable initial changes to the variables.
rhoend : float, optional
Final accuracy in the optimization (not precisely guaranteed). This is a lower bound on the size of the trust region.
disp : {0, 1, 2, 3}, optional
Controls the frequency of output; 0 implies no output.
maxfun : int, optional
Maximum number of function evaluations.
catol : float, optional
Absolute tolerance for constraint violations.
Returns: x : ndarray
The argument that minimises f.
See also
minimize
 Interface to minimization algorithms for multivariate functions. See the ‘COBYLA’ method in particular.
Notes
This algorithm is based on linear approximations to the objective function and each constraint. We briefly describe the algorithm.
Suppose the function is being minimized over k variables. At the jth iteration the algorithm has k+1 points v_1, …, v_(k+1), an approximate solution x_j, and a radius RHO_j. (i.e. linear plus a constant) approximations to the objective function and constraint functions such that their function values agree with the linear approximation on the k+1 points v_1,.., v_(k+1). This gives a linear program to solve (where the linear approximations of the constraint functions are constrained to be nonnegative).
However the linear approximations are likely only good approximations near the current simplex, so the linear program is given the further requirement that the solution, which will become x_(j+1), must be within RHO_j from x_j. RHO_j only decreases, never increases. The initial RHO_j is rhobeg and the final RHO_j is rhoend. In this way COBYLA’s iterations behave like a trust region algorithm.
Additionally, the linear program may be inconsistent, or the approximation may give poor improvement. For details about how these issues are resolved, as well as how the points v_i are updated, refer to the source code or the references below.
References
Powell M.J.D. (1994), “A direct search optimization method that models the objective and constraint functions by linear interpolation.”, in Advances in Optimization and Numerical Analysis, eds. S. Gomez and JP Hennart, Kluwer Academic (Dordrecht), pp. 5167
Powell M.J.D. (1998), “Direct search algorithms for optimization calculations”, Acta Numerica 7, 287336
Powell M.J.D. (2007), “A view of algorithms for optimization without derivatives”, Cambridge University Technical Report DAMTP 2007/NA03
Examples
Minimize the objective function f(x,y) = x*y subject to the constraints x**2 + y**2 < 1 and y > 0:
>>> def objective(x): ... return x[0]*x[1] ... >>> def constr1(x): ... return 1  (x[0]**2 + x[1]**2) ... >>> def constr2(x): ... return x[1] ... >>> from scipy.optimize import fmin_cobyla >>> fmin_cobyla(objective, [0.0, 0.1], [constr1, constr2], rhoend=1e7) array([0.70710685, 0.70710671])
The exact solution is (sqrt(2)/2, sqrt(2)/2).
minimize¶

dmipy.optimizers.mix.
minimize
(fun, x0, args=(), method=None, jac=None, hess=None, hessp=None, bounds=None, constraints=(), tol=None, callback=None, options=None)¶ Minimization of scalar function of one or more variables.
In general, the optimization problems are of the form:
minimize f(x) subject to g_i(x) >= 0, i = 1,...,m h_j(x) = 0, j = 1,...,p
where x is a vector of one or more variables.
g_i(x)
are the inequality constraints.h_j(x)
are the equality constrains.Optionally, the lower and upper bounds for each element in x can also be specified using the bounds argument.
Parameters: fun : callable
The objective function to be minimized. Must be in the form
f(x, *args)
. The optimizing argument,x
, is a 1D array of points, andargs
is a tuple of any additional fixed parameters needed to completely specify the function.x0 : ndarray
Initial guess.
len(x0)
is the dimensionality of the minimization problem.args : tuple, optional
Extra arguments passed to the objective function and its derivatives (Jacobian, Hessian).
method : str or callable, optional
Type of solver. Should be one of
 ‘NelderMead’ (see here)
 ‘Powell’ (see here)
 ‘CG’ (see here)
 ‘BFGS’ (see here)
 ‘NewtonCG’ (see here)
 ‘LBFGSB’ (see here)
 ‘TNC’ (see here)
 ‘COBYLA’ (see here)
 ‘SLSQP’ (see here)
 ‘dogleg’ (see here)
 ‘trustncg’ (see here)
 ‘trustexact’ (see here)
 ‘trustkrylov’ (see here)
 custom  a callable object (added in version 0.14.0), see below for description.
If not given, chosen to be one of
BFGS
,LBFGSB
,SLSQP
, depending if the problem has constraints or bounds.jac : bool or callable, optional
Jacobian (gradient) of objective function. Only for CG, BFGS, NewtonCG, LBFGSB, TNC, SLSQP, dogleg, trustncg, trustkrylov, trustregionexact. If jac is a Boolean and is True, fun is assumed to return the gradient along with the objective function. If False, the gradient will be estimated numerically. jac can also be a callable returning the gradient of the objective. In this case, it must accept the same arguments as fun.
hess, hessp : callable, optional
Hessian (matrix of secondorder derivatives) of objective function or Hessian of objective function times an arbitrary vector p. Only for NewtonCG, dogleg, trustncg, trustkrylov, trustregionexact. Only one of hessp or hess needs to be given. If hess is provided, then hessp will be ignored. If neither hess nor hessp is provided, then the Hessian product will be approximated using finite differences on jac. hessp must compute the Hessian times an arbitrary vector.
bounds : sequence, optional
Bounds for variables (only for LBFGSB, TNC and SLSQP).
(min, max)
pairs for each element inx
, defining the bounds on that parameter. Use None for one ofmin
ormax
when there is no bound in that direction.constraints : dict or sequence of dict, optional
Constraints definition (only for COBYLA and SLSQP). Each constraint is defined in a dictionary with fields:
 type : str
Constraint type: ‘eq’ for equality, ‘ineq’ for inequality.
 fun : callable
The function defining the constraint.
 jac : callable, optional
The Jacobian of fun (only for SLSQP).
 args : sequence, optional
Extra arguments to be passed to the function and Jacobian.
Equality constraint means that the constraint function result is to be zero whereas inequality means that it is to be nonnegative. Note that COBYLA only supports inequality constraints.
tol : float, optional
Tolerance for termination. For detailed control, use solverspecific options.
options : dict, optional
A dictionary of solver options. All methods accept the following generic options:
 maxiter : int
Maximum number of iterations to perform.
 disp : bool
Set to True to print convergence messages.
For methodspecific options, see
show_options()
.callback : callable, optional
Called after each iteration, as
callback(xk)
, wherexk
is the current parameter vector.Returns: res : OptimizeResult
The optimization result represented as a
OptimizeResult
object. Important attributes are:x
the solution array,success
a Boolean flag indicating if the optimizer exited successfully andmessage
which describes the cause of the termination. See OptimizeResult for a description of other attributes.See also
minimize_scalar
 Interface to minimization algorithms for scalar univariate functions
show_options
 Additional options accepted by the solvers
Notes
This section describes the available solvers that can be selected by the ‘method’ parameter. The default method is BFGS.
Unconstrained minimization
Method NelderMead uses the Simplex algorithm [R48], [R49]. This algorithm is robust in many applications. However, if numerical computation of derivative can be trusted, other algorithms using the first and/or second derivatives information might be preferred for their better performance in general.
Method Powell is a modification of Powell’s method [R50], [R51] which is a conjugate direction method. It performs sequential onedimensional minimizations along each vector of the directions set (direc field in options and info), which is updated at each iteration of the main minimization loop. The function need not be differentiable, and no derivatives are taken.
Method CG uses a nonlinear conjugate gradient algorithm by Polak and Ribiere, a variant of the FletcherReeves method described in [R52] pp. 120122. Only the first derivatives are used.
Method BFGS uses the quasiNewton method of Broyden, Fletcher, Goldfarb, and Shanno (BFGS) [R52] pp. 136. It uses the first derivatives only. BFGS has proven good performance even for nonsmooth optimizations. This method also returns an approximation of the Hessian inverse, stored as hess_inv in the OptimizeResult object.
Method NewtonCG uses a NewtonCG algorithm [R52] pp. 168 (also known as the truncated Newton method). It uses a CG method to the compute the search direction. See also TNC method for a boxconstrained minimization with a similar algorithm. Suitable for largescale problems.
Method dogleg uses the dogleg trustregion algorithm [R52] for unconstrained minimization. This algorithm requires the gradient and Hessian; furthermore the Hessian is required to be positive definite.
Method trustncg uses the Newton conjugate gradient trustregion algorithm [R52] for unconstrained minimization. This algorithm requires the gradient and either the Hessian or a function that computes the product of the Hessian with a given vector. Suitable for largescale problems.
Method trustkrylov uses the Newton GLTR trustregion algorithm [14]_, [15]_ for unconstrained minimization. This algorithm requires the gradient and either the Hessian or a function that computes the product of the Hessian with a given vector. Suitable for largescale problems. On indefinite problems it requires usually less iterations than the trustncg method and is recommended for medium and largescale problems.
Method trustexact is a trustregion method for unconstrained minimization in which quadratic subproblems are solved almost exactly [13]_. This algorithm requires the gradient and the Hessian (which is not required to be positive definite). It is, in many situations, the Newton method to converge in fewer iteraction and the most recommended for small and mediumsize problems.
Constrained minimization
Method LBFGSB uses the LBFGSB algorithm [R53], [R54] for bound constrained minimization.
Method TNC uses a truncated Newton algorithm [R52], [R55] to minimize a function with variables subject to bounds. This algorithm uses gradient information; it is also called Newton ConjugateGradient. It differs from the NewtonCG method described above as it wraps a C implementation and allows each variable to be given upper and lower bounds.
Method COBYLA uses the Constrained Optimization BY Linear Approximation (COBYLA) method [R56], [10]_, [11]_. The algorithm is based on linear approximations to the objective function and each constraint. The method wraps a FORTRAN implementation of the algorithm. The constraints functions ‘fun’ may return either a single number or an array or list of numbers.
Method SLSQP uses Sequential Least SQuares Programming to minimize a function of several variables with any combination of bounds, equality and inequality constraints. The method wraps the SLSQP Optimization subroutine originally implemented by Dieter Kraft [12]_. Note that the wrapper handles infinite values in bounds by converting them into large floating values.
Custom minimizers
It may be useful to pass a custom minimization method, for example when using a frontend to this method such as scipy.optimize.basinhopping or a different library. You can simply pass a callable as the
method
parameter.The callable is called as
method(fun, x0, args, **kwargs, **options)
wherekwargs
corresponds to any other parameters passed to minimize (such as callback, hess, etc.), except the options dict, which has its contents also passed as method parameters pair by pair. Also, if jac has been passed as a bool type, jac and fun are mangled so that fun returns just the function values and jac is converted to a function returning the Jacobian. The method shall return anOptimizeResult
object.The provided method callable must be able to accept (and possibly ignore) arbitrary parameters; the set of parameters accepted by minimize may expand in future versions and then these parameters will be passed to the method. You can find an example in the scipy.optimize tutorial.
New in version 0.11.0.
References
[R48] (1, 2) Nelder, J A, and R Mead. 1965. A Simplex Method for Function Minimization. The Computer Journal 7: 30813. [R49] (1, 2) Wright M H. 1996. Direct search methods: Once scorned, now respectable, in Numerical Analysis 1995: Proceedings of the 1995 Dundee Biennial Conference in Numerical Analysis (Eds. D F Griffiths and G A Watson). Addison Wesley Longman, Harlow, UK. 191208. [R50] (1, 2) Powell, M J D. 1964. An efficient method for finding the minimum of a function of several variables without calculating derivatives. The Computer Journal 7: 155162. [R51] (1, 2) Press W, S A Teukolsky, W T Vetterling and B P Flannery. Numerical Recipes (any edition), Cambridge University Press. [R52] (1, 2, 3, 4, 5, 6, 7, 8) Nocedal, J, and S J Wright. 2006. Numerical Optimization. Springer New York. [R53] (1, 2) Byrd, R H and P Lu and J. Nocedal. 1995. A Limited Memory Algorithm for Bound Constrained Optimization. SIAM Journal on Scientific and Statistical Computing 16 (5): 11901208. [R54] (1, 2) Zhu, C and R H Byrd and J Nocedal. 1997. LBFGSB: Algorithm 778: LBFGSB, FORTRAN routines for large scale bound constrained optimization. ACM Transactions on Mathematical Software 23 (4): 550560. [R55] (1, 2) Nash, S G. NewtonType Minimization Via the Lanczos Method. 1984. SIAM Journal of Numerical Analysis 21: 770778. [R56] (1, 2) Powell, M J D. A direct search optimization method that models the objective and constraint functions by linear interpolation. 1994. Advances in Optimization and Numerical Analysis, eds. S. Gomez and JP Hennart, Kluwer Academic (Dordrecht), 5167. [10] Powell M J D. Direct search algorithms for optimization calculations. 1998. Acta Numerica 7: 287336. [11] Powell M J D. A view of algorithms for optimization without derivatives. 2007.Cambridge University Technical Report DAMTP 2007/NA03 [12] Kraft, D. A software package for sequential quadratic programming. 1988. Tech. Rep. DFVLRFB 8828, DLR German Aerospace Center – Institute for Flight Mechanics, Koln, Germany. [13] Conn, A. R., Gould, N. I., and Toint, P. L. Trust region methods. 2000. Siam. pp. 169200. [14] F. Lenders, C. Kirches, A. Potschka: “trlib: A vectorfree implementation of the GLTR method for iterative solution of the trust region problem”, https://arxiv.org/abs/1611.04718 [15] N. Gould, S. Lucidi, M. Roma, P. Toint: “Solving the TrustRegion Subproblem using the Lanczos Method”, SIAM J. Optim., 9(2), 504–525, (1999). Examples
Let us consider the problem of minimizing the Rosenbrock function. This function (and its respective derivatives) is implemented in rosen (resp. rosen_der, rosen_hess) in the scipy.optimize.
>>> from scipy.optimize import minimize, rosen, rosen_der
A simple application of the NelderMead method is:
>>> x0 = [1.3, 0.7, 0.8, 1.9, 1.2] >>> res = minimize(rosen, x0, method='NelderMead', tol=1e6) >>> res.x array([ 1., 1., 1., 1., 1.])
Now using the BFGS algorithm, using the first derivative and a few options:
>>> res = minimize(rosen, x0, method='BFGS', jac=rosen_der, ... options={'gtol': 1e6, 'disp': True}) Optimization terminated successfully. Current function value: 0.000000 Iterations: 26 Function evaluations: 31 Gradient evaluations: 31 >>> res.x array([ 1., 1., 1., 1., 1.]) >>> print(res.message) Optimization terminated successfully. >>> res.hess_inv array([[ 0.00749589, 0.01255155, 0.02396251, 0.04750988, 0.09495377], # may vary [ 0.01255155, 0.02510441, 0.04794055, 0.09502834, 0.18996269], [ 0.02396251, 0.04794055, 0.09631614, 0.19092151, 0.38165151], [ 0.04750988, 0.09502834, 0.19092151, 0.38341252, 0.7664427 ], [ 0.09495377, 0.18996269, 0.38165151, 0.7664427, 1.53713523]])
Next, consider a minimization problem with several constraints (namely Example 16.4 from [R52]). The objective function is:
>>> fun = lambda x: (x[0]  1)**2 + (x[1]  2.5)**2
There are three constraints defined as:
>>> cons = ({'type': 'ineq', 'fun': lambda x: x[0]  2 * x[1] + 2}, ... {'type': 'ineq', 'fun': lambda x: x[0]  2 * x[1] + 6}, ... {'type': 'ineq', 'fun': lambda x: x[0] + 2 * x[1] + 2})
And variables must be positive, hence the following bounds:
>>> bnds = ((0, None), (0, None))
The optimization problem is solved using the SLSQP method as:
>>> res = minimize(fun, (2, 0), method='SLSQP', bounds=bnds, ... constraints=cons)
It should converge to the theoretical solution (1.4 ,1.7).
nested_to_normalized_fractions¶

dmipy.optimizers.mix.
nested_to_normalized_fractions
(nested_fractions) Function to convert nested to normalized volume fractions.
optimizers_fod
¶
Module: optimizers_fod.cvxpy_fod
¶

class
dmipy.optimizers_fod.cvxpy_fod.
GeneralPurposeCSDOptimizer
(acquisition_scheme, model, sh_order=8, unity_constraint=True)¶ General purpose optimizer for multicompartment constrained spherical deconvolution (MCCSD) to estimate Fiber Orientation Distributions (FODs). It can take any number of compartment models as convolution kernels as long as all the kernel’s parameters are fixed. If more than one kernel is given, then the optimizer estimates the volume fractions of the different kernels as well as the FOD.
The optimization package CVXPY [R57] is used for this MCCSD implementation.
Limitations: It cannot estimate the FOD of multiple kernels that each have an orientation. E.g. it is possible to have a cylinder and a ball kernel as input, but not two cylinders.
IMPORTANT NOTE: This multicompartment CSD implementation is NOT the same MultiTissue CSD (MTCSD) as proposed by Jeurissen et al. [R58]. In MTCSD they input tissue response kernels that INCLUDES the differences in b0intensities between different tissue types. In this current implementation of MCCSD, the different compartment kernels are directly fitted to the signal attenuation, implicitly assuming each compartment has the same b0intensity.
Parameters: acquisition_scheme: DmipyAcquisitionScheme instance, :
acquisition scheme of the tobefitted data.
model: dmipy MultiCompartmentModel instance, :
Can be composed of any model combination.
sh_order: even integer larger or equal to zero, :
maximum spherical harmonics order to be included in the FOD estimation.
unity_constrain: bool, :
whether or not to impose that the FOD integrates to unity.
References
[R57] (1, 2) Diamond, Steven, and Stephen Boyd. “CVXPY: A Pythonembedded modeling language for convex optimization.” The Journal of Machine Learning Research 17.1 (2016): 29092913. [R58] (1, 2) Jeurissen, Ben, et al. “Multitissue constrained spherical deconvolution for improved analysis of multishell diffusion MRI data.” NeuroImage 103 (2014): 411426. Methods

prepare_rotational_harmonics
(rh_array, rh_order)¶ Function to extend rotational harmonics and prepare them for MSE.

recover_rotational_harmonics
(x0_vector)¶ Recovers list of rotational harmonics for each model.

GeneralPurposeCSDOptimizer
¶

class
dmipy.optimizers_fod.cvxpy_fod.
GeneralPurposeCSDOptimizer
(acquisition_scheme, model, sh_order=8, unity_constraint=True) General purpose optimizer for multicompartment constrained spherical deconvolution (MCCSD) to estimate Fiber Orientation Distributions (FODs). It can take any number of compartment models as convolution kernels as long as all the kernel’s parameters are fixed. If more than one kernel is given, then the optimizer estimates the volume fractions of the different kernels as well as the FOD.
The optimization package CVXPY [R59] is used for this MCCSD implementation.
Limitations: It cannot estimate the FOD of multiple kernels that each have an orientation. E.g. it is possible to have a cylinder and a ball kernel as input, but not two cylinders.
IMPORTANT NOTE: This multicompartment CSD implementation is NOT the same MultiTissue CSD (MTCSD) as proposed by Jeurissen et al. [R60]. In MTCSD they input tissue response kernels that INCLUDES the differences in b0intensities between different tissue types. In this current implementation of MCCSD, the different compartment kernels are directly fitted to the signal attenuation, implicitly assuming each compartment has the same b0intensity.
Parameters: acquisition_scheme: DmipyAcquisitionScheme instance, :
acquisition scheme of the tobefitted data.
model: dmipy MultiCompartmentModel instance, :
Can be composed of any model combination.
sh_order: even integer larger or equal to zero, :
maximum spherical harmonics order to be included in the FOD estimation.
unity_constrain: bool, :
whether or not to impose that the FOD integrates to unity.
References
[R59] (1, 2) Diamond, Steven, and Stephen Boyd. “CVXPY: A Pythonembedded modeling language for convex optimization.” The Journal of Machine Learning Research 17.1 (2016): 29092913. [R60] (1, 2) Jeurissen, Ben, et al. “Multitissue constrained spherical deconvolution for improved analysis of multishell diffusion MRI data.” NeuroImage 103 (2014): 411426. Methods

__init__
(acquisition_scheme, model, sh_order=8, unity_constraint=True)¶

prepare_rotational_harmonics
(rh_array, rh_order) Function to extend rotational harmonics and prepare them for MSE.

recover_rotational_harmonics
(x0_vector) Recovers list of rotational harmonics for each model.

HemiSphere
¶

class
dmipy.optimizers_fod.cvxpy_fod.
HemiSphere
(x=None, y=None, z=None, theta=None, phi=None, xyz=None, faces=None, edges=None, tol=1e05)¶ Bases:
dipy.core.sphere.Sphere
Points on the unit sphere.
A HemiSphere is similar to a Sphere but it takes antipodal symmetry into account. Antipodal symmetry means that point v on a HemiSphere is the same as the point v. Duplicate points are discarded when constructing a HemiSphere (including antipodal duplicates). edges and faces are remapped to the remaining points as closely as possible.
The HemiSphere can be constructed using one of three conventions:
HemiSphere(x, y, z) HemiSphere(xyz=xyz) HemiSphere(theta=theta, phi=phi)
Parameters: x, y, z : 1D array_like
Vertices as xyz coordinates.
theta, phi : 1D array_like
Vertices as spherical coordinates. Theta and phi are the inclination and azimuth angles respectively.
xyz : (N, 3) ndarray
Vertices as xyz coordinates.
faces : (N, 3) ndarray
Indices into vertices that form triangular faces. If unspecified, the faces are computed using a Delaunay triangulation.
edges : (N, 2) ndarray
Edges between vertices. If unspecified, the edges are derived from the faces.
tol : float
Angle in degrees. Vertices that are less than tol degrees apart are treated as duplicates.
See also
Sphere
Attributes
Methods

__init__
(x=None, y=None, z=None, theta=None, phi=None, xyz=None, faces=None, edges=None, tol=1e05)¶ Create a HemiSphere from points

faces
()¶

find_closest
(xyz)¶ Find the index of the vertex in the Sphere closest to the input vector, taking into account antipodal symmetry
Parameters: xyz : arraylike, 3 elements
A unit vector

classmethod
from_sphere
(klass, sphere, tol=1e05)¶ Create instance from a Sphere

mirror
()¶ Create a full Sphere from a HemiSphere

subdivide
(n=1)¶ Create a more subdivided HemiSphere
See Sphere.subdivide for full documentation.

get_sphere¶

dmipy.optimizers_fod.cvxpy_fod.
get_sphere
(name='symmetric362')¶ provide triangulated spheres
Parameters: name : str
which sphere  one of: * ‘symmetric362’ * ‘symmetric642’ * ‘symmetric724’ * ‘repulsion724’ * ‘repulsion100’ * ‘repulsion200’
Returns: sphere : a dipy.core.sphere.Sphere class instance
Examples
>>> import numpy as np >>> from dipy.data import get_sphere >>> sphere = get_sphere('symmetric362') >>> verts, faces = sphere.vertices, sphere.faces >>> verts.shape == (362, 3) True >>> faces.shape == (720, 3) True >>> verts, faces = get_sphere('not a sphere name') Traceback (most recent call last): ... DataError: No sphere called "not a sphere name"
optional_package¶

dmipy.optimizers_fod.cvxpy_fod.
optional_package
(name, trip_msg=None)¶ Return packagelike thing and module setup for package name
Parameters: name : str
package name
trip_msg : None or str
message to give when someone tries to use the return package, but we could not import it, and have returned a TripWire object instead. Default message if None.
Returns: pkg_like : module or
TripWire
instanceIf we can import the package, return it. Otherwise return an object raising an error when accessed
have_pkg : bool
True if import for package was successful, false otherwise
module_setup : function
callable usually set as
setup_module
in calling namespace, to allow skipping tests.
real_sym_sh_mrtrix¶

dmipy.optimizers_fod.cvxpy_fod.
real_sym_sh_mrtrix
(sh_order, theta, phi)¶ Compute real spherical harmonics as in mrtrix, where the real harmonic \(Y^m_n\) is defined to be:
Real(:math:`Y^m_n`) if m > 0 :math:`Y^0_n` if m = 0 Imag(:math:`Y^m_n`) if m < 0
This may take scalar or array arguments. The inputs will be broadcasted against each other.
Parameters: sh_order : int
The maximum degree or the spherical harmonic basis.
theta : float [0, pi]
The polar (colatitudinal) coordinate.
phi : float [0, 2*pi]
The azimuthal (longitudinal) coordinate.
Returns: y_mn : real float
The real harmonic \(Y^m_n\) sampled at theta and phi as implemented in mrtrix. Warning: the basis is Tournier et al 2004 and 2007 is slightly different.
m : array
The order of the harmonics.
n : array
The degree of the harmonics.
signal_models
¶
Module: signal_models.capped_cylinder_models
¶

class
dmipy.signal_models.capped_cylinder_models.
CC3CappedCylinderCallaghanApproximation
(mu=None, diameter=None, length=None, diffusion_intra=1.7e09, number_of_roots_cylinder=20, number_of_functions_cylinder=50, number_of_roots_plane=40)¶ The Callaghan model [R61]  a cylinder with finite radius  for intraaxonal diffusion. The perpendicular diffusion is modelled after Callaghan’s solution for the disk. The parallel diffusion of the capped cylinder is modelled using the same Callaghan approximation but between two parallel planes with a certain distance or ‘length’ between them.
Parameters: mu : array, shape(2),
angles [theta, phi] representing main orientation on the sphere. theta is inclination of polar angle of main angle mu [0, pi]. phi is polar angle of main angle mu [pi, pi].
diameter : float,
cylinder (axon) diameter in meters.
length : float,
cylinder length in meters.
diffusion_intra : float,
The diffusion constant of the water particles inside the cylinder. The default value is the approximate diffusivity of water inside axons as 1.7e9 m^2/s.
number_of_roots_cylinder : integer,
number of roots for the cylinder Callaghan approximation.
number_of_functions_cylinder : integer,
number of functions for the cylinder Callaghan approximation.
number_of_roots_plane : integer,
number of roots for the plane Callaghan approximation.
References
[R61] (1, 2) Callaghan, Paul T. “Pulsedgradient spinecho NMR for planar, cylindrical, and spherical pores under conditions of wall relaxation.” Journal of magnetic resonance, Series A 113.1 (1995): 5359. Attributes
Methods
Module: signal_models.cylinder_models
¶

class
dmipy.signal_models.cylinder_models.
C1Stick
(mu=None, lambda_par=None)¶ The Stick model [R62]  a cylinder with zero radius  typically used for intraaxonal diffusion.
Parameters: mu : array, shape(2),
angles [theta, phi] representing main orientation on the sphere. theta is inclination of polar angle of main angle mu [0, pi]. phi is polar angle of main angle mu [pi, pi].
lambda_par : float,
parallel diffusivity in m^2/s.
References
[R62] (1, 2) Behrens et al. “Characterization and propagation of uncertainty in
diffusionweighted MR imaging”Magnetic Resonance in Medicine (2003)
Attributes
Methods

rotational_harmonics_representation
(acquisition_scheme, **kwargs)¶ The rotational harmonics of the model, such that Y_lm = Yl0. Axis aligned with zaxis to be used as kernel for spherical convolution. Returns an array with rotational harmonics for each shell.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: rh_array : array, shape(Nshells, N_rh_coef),
Rotational harmonics coefficients for each shell.

spherical_mean
(acquisition_scheme, **kwargs)¶ Estimates spherical mean for every shell in acquisition scheme for Stick model.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: E_mean : array of size (Nshells)
spherical mean of the Stick model for every acquisition shell.


class
dmipy.signal_models.cylinder_models.
C2CylinderStejskalTannerApproximation
(mu=None, lambda_par=None, diameter=None)¶ The StejskalTanner approximation of the cylinder model with finite radius, proposed by Soderman and Jonsson [R63]. Assumes that both the short gradient pulse (SGP) approximation is met and long diffusion time limit is reached. The perpendicular cylinder diffusion therefore only depends on the qvalue of the acquisition.
Parameters: mu : array, shape(2),
angles [theta, phi] representing main orientation on the sphere. theta is inclination of polar angle of main angle mu [0, pi]. phi is polar angle of main angle mu [pi, pi].
lambda_par : float,
parallel diffusivity in m^2/s.
diameter : float,
cylinder diameter in meters.
Returns: E : array, shape (N,)
signal attenuation
References
[R63] (1, 2) Soderman, Olle, and Bengt Jonsson. “Restricted diffusion in cylindrical geometry.” Journal of Magnetic Resonance, Series A 117.1 (1995): 9497. Attributes
Methods

perpendicular_attenuation
(q, diameter)¶ Returns the cylinder’s perpendicular signal attenuation.

rotational_harmonics_representation
(acquisition_scheme, **kwargs)¶ The rotational harmonics of the model, such that Y_lm = Yl0. Axis aligned with zaxis to be used as kernel for spherical convolution. Returns an array with rotational harmonics for each shell.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: rh_array : array, shape(Nshells, N_rh_coef),
Rotational harmonics coefficients for each shell.

spherical_mean
(acquisition_scheme, **kwargs)¶ Estimates spherical mean for every shell in acquisition scheme.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: E_mean : float,
spherical mean of the model for every acquisition shell.


class
dmipy.signal_models.cylinder_models.
C3CylinderCallaghanApproximation
(mu=None, lambda_par=None, diameter=None, diffusion_perpendicular=1.7e09, number_of_roots=20, number_of_functions=50)¶ The Callaghan model [R64]  a cylinder with finite radius  typically used for intraaxonal diffusion. The perpendicular diffusion is modelled after Callaghan’s solution for the disk. Is dependent on both qvalue and diffusion time.
Parameters: mu : array, shape(2),
angles [theta, phi] representing main orientation on the sphere. theta is inclination of polar angle of main angle mu [0, pi]. phi is polar angle of main angle mu [pi, pi].
lambda_par : float,
parallel diffusivity in m^2/s.
diameter : float,
cylinder (axon) diameter in meters.
diffusion_perpendicular : float,
the intracylindrical, perpenicular diffusivity. By default it is set to a typical value for intraaxonal diffusion as 1.7e9 m^2/s.
number_of_roots : integer,
number of roots to use for the Callaghan cylinder model.
number_of_function : integer,
number of functions to use for the Callaghan cylinder model.
References
[R64] (1, 2) Callaghan, Paul T. “Pulsedgradient spinecho NMR for planar, cylindrical, and spherical pores under conditions of wall relaxation.” Journal of magnetic resonance, Series A 113.1 (1995): 5359. Attributes
Methods

perpendicular_attenuation
(q, tau, diameter)¶ Implements the finite time Callaghan model for cylinders

rotational_harmonics_representation
(acquisition_scheme, **kwargs)¶ The rotational harmonics of the model, such that Y_lm = Yl0. Axis aligned with zaxis to be used as kernel for spherical convolution. Returns an array with rotational harmonics for each shell.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: rh_array : array, shape(Nshells, N_rh_coef),
Rotational harmonics coefficients for each shell.

spherical_mean
(acquisition_scheme, **kwargs)¶ Estimates spherical mean for every shell in acquisition scheme.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: E_mean : float,
spherical mean of the model for every acquisition shell.


class
dmipy.signal_models.cylinder_models.
C4CylinderGaussianPhaseApproximation
(mu=None, lambda_par=None, diameter=None, diffusion_perpendicular=1.7e09)¶ The Gaussian phase model [R65]  a cylinder with finite radius  typically used for intraaxonal diffusion. The perpendicular diffusion is modelled after Van Gelderen’s solution for the disk. It is dependent on gradient strength, pulse separation and pulse length.
Parameters: mu : array, shape(2),
angles [theta, phi] representing main orientation on the sphere. theta is inclination of polar angle of main angle mu [0, pi]. phi is polar angle of main angle mu [pi, pi].
lambda_par : float,
parallel diffusivity in 10^9 m^2/s.
diameter : float,
cylinder (axon) diameter in meters.
References
[R65] (1, 2) Van Gelderen et al. “Evaluation of Restricted Diffusion in Cylinders. Phosphocreatine in Rabbit Leg Muscle” Journal of Magnetic Resonance Series B (1994) Attributes
Methods

perpendicular_attenuation
(gradient_strength, delta, Delta, diameter)¶ Calculates the cylinder’s perpendicular signal attenuation.

rotational_harmonics_representation
(acquisition_scheme, **kwargs)¶ The rotational harmonics of the model, such that Y_lm = Yl0. Axis aligned with zaxis to be used as kernel for spherical convolution. Returns an array with rotational harmonics for each shell.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: rh_array : array, shape(Nshells, N_rh_coef),
Rotational harmonics coefficients for each shell.

spherical_mean
(acquisition_scheme, **kwargs)¶ Estimates spherical mean for every shell in acquisition scheme.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: E_mean : float,
spherical mean of the model for every acquisition shell.

Module: signal_models.gaussian_models
¶
Document Module

class
dmipy.signal_models.gaussian_models.
G1Ball
(lambda_iso=None)¶ The Ball model [R66]  an isotropic Tensor with one diffusivity.
Parameters: lambda_iso : float,
isotropic diffusivity in m^2/s.
References
[R66] (1, 2) Behrens et al. “Characterization and propagation of uncertainty in
diffusionweighted MR imaging”Magnetic Resonance in Medicine (2003)
Attributes
Methods

rotational_harmonics_representation
(acquisition_scheme, **kwargs)¶ The rotational harmonics of the model, such that Y_lm = Yl0. Axis aligned with zaxis to be used as kernel for spherical convolution. Returns an array with rotational harmonics for each shell.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: rh_array : array, shape(Nshells, N_rh_coef),
Rotational harmonics coefficients for each shell.

spherical_mean
(acquisition_scheme, **kwargs)¶ Estimates spherical mean for every shell in acquisition scheme
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: E_mean : float,
spherical mean of the model for every acquisition shell.


class
dmipy.signal_models.gaussian_models.
G2Zeppelin
(mu=None, lambda_par=None, lambda_perp=None)¶ The Zeppelin model [R67]  an axially symmetric Tensor  typically used for extraaxonal diffusion.
Parameters: mu : array, shape(2),
angles [theta, phi] representing main orientation on the sphere. theta is inclination of polar angle of main angle mu [0, pi]. phi is polar angle of main angle mu [pi, pi].
lambda_par : float,
parallel diffusivity in m^2/s.
lambda_perp : float,
perpendicular diffusivity in m^2/s.
Returns: E_zeppelin : float or array, shape(N),
signal attenuation.
References
[R67] (1, 2) Panagiotaki et al. “Compartment models of the diffusion MR signal in brain white
matter: a taxonomy and comparison”. NeuroImage (2012)Attributes
Methods

rotational_harmonics_representation
(acquisition_scheme, **kwargs)¶ The rotational harmonics of the model, such that Y_lm = Yl0. Axis aligned with zaxis to be used as kernel for spherical convolution. Returns an array with rotational harmonics for each shell.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: rh_array : array, shape(Nshells, N_rh_coef),
Rotational harmonics coefficients for each shell.

spherical_mean
(acquisition_scheme, **kwargs)¶ Estimates spherical mean for every shell in acquisition scheme for Zeppelin model.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: E_mean : float,
spherical mean of the Zeppelin model for every acquisition shell.


class
dmipy.signal_models.gaussian_models.
G3TemporalZeppelin
(mu=None, lambda_par=None, lambda_inf=None, A=None)¶ The temporal Zeppelin model [R68]  an axially symmetric Tensor  typically used to describe extraaxonal diffusion. The G3TemporalZeppelin differs from G2Zeppelin in that it has a timedependent perpendicular parameter “A”, which describe extraaxonal diffusion hindrance due to axon packing, and that lambda_perp is instead called lambda_inf, as it describes the perpendicular diffusivity when diffusion time is infinite.
Parameters: mu : array, shape(2),
angles [theta, phi] representing main orientation on the sphere. theta is inclination of polar angle of main angle mu [0, pi]. phi is polar angle of main angle mu [pi, pi].
lambda_par : float,
parallel diffusivity in 10^9 m^2/s.
lambda_inf : float,
bulk diffusivity constant 10^9 m^2/s.
A: float, :
characteristic coefficient in 10^12 m^2
Returns: E_zeppelin : float or array, shape(N),
signal attenuation.
References
[R68] (1, 2) Burcaw, L.M., Fieremans, E., Novikov, D.S., 2015. Mesoscopic structure of neuronal tracts from timedependent diffusion. NeuroImage 114, 18. Attributes
Methods

rotational_harmonics_representation
(acquisition_scheme, **kwargs)¶ The rotational harmonics of the model, such that Y_lm = Yl0. Axis aligned with zaxis to be used as kernel for spherical convolution. Returns an array with rotational harmonics for each shell.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: rh_array : array, shape(Nshells, N_rh_coef),
Rotational harmonics coefficients for each shell.

spherical_mean
(acquisition_scheme, **kwargs)¶ Estimates spherical mean for every shell in acquisition scheme for Restricted Zeppelin model.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: E_mean : float,
spherical mean of the Restricted Zeppelin model for every acquisition shell.

Module: signal_models.plane_models
¶

class
dmipy.signal_models.plane_models.
P3PlaneCallaghanApproximation
(diameter=None, diffusion_constant=1.7e09, number_of_roots=40)¶ The Callaghan model [1]_ of diffusion between two parallel infinite plates.
Parameters: diameter : float
Distance between the two plates in meters.
diffusion_constant : float,
The diffusion constant of the water particles between the two planes. The default value is the approximate diffusivity of water inside axons as 1.7e9 m^2/s.
number_of_roots : integer,
The number of roots for the Callaghan approximation.
References
 [1] Callaghan, “PulsedGradient SpinEcho NMR for Planar, Cylindrical,
 and Spherical Pores under Conditions of Wall Relaxation”, JMR 1995
Attributes
Methods

plane_attenuation
(q, tau, diameter)¶ Implements the finite time Callaghan model for planes.
Module: signal_models.sphere_models
¶

class
dmipy.signal_models.sphere_models.
S1Dot
¶ The Dot model [R69]  an nondiffusing compartment. It has no parameters and returns 1 no matter the input.
References
[R69] (1, 2) Panagiotaki et al. “Compartment models of the diffusion MR signal in brain white
matter: a taxonomy and comparison”. NeuroImage (2012)Attributes
Methods

rotational_harmonics_representation
(acquisition_scheme, **kwargs)¶ The rotational harmonics of the model, such that Y_lm = Yl0. Axis aligned with zaxis to be used as kernel for spherical convolution. Returns an array with rotational harmonics for each shell.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: rh_array : array, shape(Nshells, N_rh_coef),
Rotational harmonics coefficients for each shell.

spherical_mean
(acquisition_scheme, **kwargs)¶ Estimates spherical mean for every shell in acquisition scheme.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: E_mean : float,
spherical mean of the model for every acquisition shell.


class
dmipy.signal_models.sphere_models.
S2SphereStejskalTannerApproximation
(diameter=None)¶ The Stejskal Tanner signal approximation of a sphere model. It assumes that pulse length is infinitessimally small and diffusion time large enough so that the diffusion is completely restricted. Only depends on qvalue.
Parameters: diameter : float,
sphere diameter in meters.
References
[R70] Balinov, Balin, et al. “The NMR selfdiffusion method applied to restricted diffusion. Simulation of echo attenuation from molecules in spheres and between planes.” Journal of Magnetic Resonance, Series A 104.1 (1993): 1725. Attributes
Methods

rotational_harmonics_representation
(acquisition_scheme, **kwargs)¶ The rotational harmonics of the model, such that Y_lm = Yl0. Axis aligned with zaxis to be used as kernel for spherical convolution. Returns an array with rotational harmonics for each shell.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: rh_array : array, shape(Nshells, N_rh_coef),
Rotational harmonics coefficients for each shell.

sphere_attenuation
(q, diameter)¶ The signal attenuation for the sphere model.

spherical_mean
(acquisition_scheme, **kwargs)¶ Estimates spherical mean for every shell in acquisition scheme.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: E_mean : float,
spherical mean of the model for every acquisition shell.

CC2CappedCylinderStejskalTannerApproximation
¶

class
dmipy.signal_models.capped_cylinder_models.
CC2CappedCylinderStejskalTannerApproximation
(mu=None, diameter=None, length=None)¶ Bases:
dmipy.core.modeling_framework.ModelProperties
The StejskalTanner model for intracylindrical diffusion inside a capped cylinder with finite radius and length. The perpendicular diffusion is modelled after Soderman’s solution for the disk [R71]. The parallel diffusion between planes has been implemented according to Balinov [R72].
Parameters: mu : array, shape(2),
angles [theta, phi] representing main orientation on the sphere. theta is inclination of polar angle of main angle mu [0, pi]. phi is polar angle of main angle mu [pi, pi].
diameter : float,
capped cylinder (axon) diameter in meters.
length : float,
capped cylinder length in meters.
References
[R71] (1, 2) Soderman, Olle, and Bengt Jonsson. “Restricted diffusion in cylindrical geometry.” Journal of Magnetic Resonance, Series A 117.1 (1995): 9497. [R72] (1, 2) Balinov, Balin, et al. “The NMR selfdiffusion method applied to restricted diffusion. Simulation of echo attenuation from molecules in spheres and between planes.” Journal of Magnetic Resonance, Series A 104.1 (1993): 1725. Attributes
Methods

__init__
(mu=None, diameter=None, length=None)¶

CC3CappedCylinderCallaghanApproximation
¶

class
dmipy.signal_models.capped_cylinder_models.
CC3CappedCylinderCallaghanApproximation
(mu=None, diameter=None, length=None, diffusion_intra=1.7e09, number_of_roots_cylinder=20, number_of_functions_cylinder=50, number_of_roots_plane=40) Bases:
dmipy.core.modeling_framework.ModelProperties
The Callaghan model [R73]  a cylinder with finite radius  for intraaxonal diffusion. The perpendicular diffusion is modelled after Callaghan’s solution for the disk. The parallel diffusion of the capped cylinder is modelled using the same Callaghan approximation but between two parallel planes with a certain distance or ‘length’ between them.
Parameters: mu : array, shape(2),
angles [theta, phi] representing main orientation on the sphere. theta is inclination of polar angle of main angle mu [0, pi]. phi is polar angle of main angle mu [pi, pi].
diameter : float,
cylinder (axon) diameter in meters.
length : float,
cylinder length in meters.
diffusion_intra : float,
The diffusion constant of the water particles inside the cylinder. The default value is the approximate diffusivity of water inside axons as 1.7e9 m^2/s.
number_of_roots_cylinder : integer,
number of roots for the cylinder Callaghan approximation.
number_of_functions_cylinder : integer,
number of functions for the cylinder Callaghan approximation.
number_of_roots_plane : integer,
number of roots for the plane Callaghan approximation.
References
[R73] (1, 2) Callaghan, Paul T. “Pulsedgradient spinecho NMR for planar, cylindrical, and spherical pores under conditions of wall relaxation.” Journal of magnetic resonance, Series A 113.1 (1995): 5359. Attributes
Methods

__init__
(mu=None, diameter=None, length=None, diffusion_intra=1.7e09, number_of_roots_cylinder=20, number_of_functions_cylinder=50, number_of_roots_plane=40)¶

ModelProperties
¶

class
dmipy.signal_models.capped_cylinder_models.
ModelProperties
¶ Contains various properties for CompartmentModels.
Attributes

parameter_cardinality
¶ Returns the cardinality of model parameters

parameter_names
¶ Returns the names of model parameters.

parameter_ranges
¶ Returns the optimization ranges of the model parameters. These ranges are given in O(1) scale so optimization algorithms don’t suffer from large scale differences in optimization parameters.

parameter_scales
¶ Returns the optimization scales for the model parameters. The scales scale the parameter_ranges to their actual size inside optimization algorithms.

parameter_types
¶ Returns the optimization scales for the model parameters. The scales scale the parameter_ranges to their actual size inside optimization algorithms.

C1Stick
¶

class
dmipy.signal_models.cylinder_models.
C1Stick
(mu=None, lambda_par=None) Bases:
dmipy.core.modeling_framework.ModelProperties
The Stick model [R74]  a cylinder with zero radius  typically used for intraaxonal diffusion.
Parameters: mu : array, shape(2),
angles [theta, phi] representing main orientation on the sphere. theta is inclination of polar angle of main angle mu [0, pi]. phi is polar angle of main angle mu [pi, pi].
lambda_par : float,
parallel diffusivity in m^2/s.
References
[R74] (1, 2) Behrens et al. “Characterization and propagation of uncertainty in
diffusionweighted MR imaging”Magnetic Resonance in Medicine (2003)
Attributes
Methods

__init__
(mu=None, lambda_par=None)¶

rotational_harmonics_representation
(acquisition_scheme, **kwargs) The rotational harmonics of the model, such that Y_lm = Yl0. Axis aligned with zaxis to be used as kernel for spherical convolution. Returns an array with rotational harmonics for each shell.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: rh_array : array, shape(Nshells, N_rh_coef),
Rotational harmonics coefficients for each shell.

spherical_mean
(acquisition_scheme, **kwargs) Estimates spherical mean for every shell in acquisition scheme for Stick model.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: E_mean : array of size (Nshells)
spherical mean of the Stick model for every acquisition shell.

C2CylinderStejskalTannerApproximation
¶

class
dmipy.signal_models.cylinder_models.
C2CylinderStejskalTannerApproximation
(mu=None, lambda_par=None, diameter=None) Bases:
dmipy.core.modeling_framework.ModelProperties
The StejskalTanner approximation of the cylinder model with finite radius, proposed by Soderman and Jonsson [R75]. Assumes that both the short gradient pulse (SGP) approximation is met and long diffusion time limit is reached. The perpendicular cylinder diffusion therefore only depends on the qvalue of the acquisition.
Parameters: mu : array, shape(2),
angles [theta, phi] representing main orientation on the sphere. theta is inclination of polar angle of main angle mu [0, pi]. phi is polar angle of main angle mu [pi, pi].
lambda_par : float,
parallel diffusivity in m^2/s.
diameter : float,
cylinder diameter in meters.
Returns: E : array, shape (N,)
signal attenuation
References
[R75] (1, 2) Soderman, Olle, and Bengt Jonsson. “Restricted diffusion in cylindrical geometry.” Journal of Magnetic Resonance, Series A 117.1 (1995): 9497. Attributes
Methods

__init__
(mu=None, lambda_par=None, diameter=None)¶

perpendicular_attenuation
(q, diameter) Returns the cylinder’s perpendicular signal attenuation.

rotational_harmonics_representation
(acquisition_scheme, **kwargs) The rotational harmonics of the model, such that Y_lm = Yl0. Axis aligned with zaxis to be used as kernel for spherical convolution. Returns an array with rotational harmonics for each shell.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: rh_array : array, shape(Nshells, N_rh_coef),
Rotational harmonics coefficients for each shell.

spherical_mean
(acquisition_scheme, **kwargs) Estimates spherical mean for every shell in acquisition scheme.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: E_mean : float,
spherical mean of the model for every acquisition shell.

C3CylinderCallaghanApproximation
¶

class
dmipy.signal_models.cylinder_models.
C3CylinderCallaghanApproximation
(mu=None, lambda_par=None, diameter=None, diffusion_perpendicular=1.7e09, number_of_roots=20, number_of_functions=50) Bases:
dmipy.core.modeling_framework.ModelProperties
The Callaghan model [R76]  a cylinder with finite radius  typically used for intraaxonal diffusion. The perpendicular diffusion is modelled after Callaghan’s solution for the disk. Is dependent on both qvalue and diffusion time.
Parameters: mu : array, shape(2),
angles [theta, phi] representing main orientation on the sphere. theta is inclination of polar angle of main angle mu [0, pi]. phi is polar angle of main angle mu [pi, pi].
lambda_par : float,
parallel diffusivity in m^2/s.
diameter : float,
cylinder (axon) diameter in meters.
diffusion_perpendicular : float,
the intracylindrical, perpenicular diffusivity. By default it is set to a typical value for intraaxonal diffusion as 1.7e9 m^2/s.
number_of_roots : integer,
number of roots to use for the Callaghan cylinder model.
number_of_function : integer,
number of functions to use for the Callaghan cylinder model.
References
[R76] (1, 2) Callaghan, Paul T. “Pulsedgradient spinecho NMR for planar, cylindrical, and spherical pores under conditions of wall relaxation.” Journal of magnetic resonance, Series A 113.1 (1995): 5359. Attributes
Methods

__init__
(mu=None, lambda_par=None, diameter=None, diffusion_perpendicular=1.7e09, number_of_roots=20, number_of_functions=50)¶

perpendicular_attenuation
(q, tau, diameter) Implements the finite time Callaghan model for cylinders

rotational_harmonics_representation
(acquisition_scheme, **kwargs) The rotational harmonics of the model, such that Y_lm = Yl0. Axis aligned with zaxis to be used as kernel for spherical convolution. Returns an array with rotational harmonics for each shell.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: rh_array : array, shape(Nshells, N_rh_coef),
Rotational harmonics coefficients for each shell.

spherical_mean
(acquisition_scheme, **kwargs) Estimates spherical mean for every shell in acquisition scheme.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: E_mean : float,
spherical mean of the model for every acquisition shell.

C4CylinderGaussianPhaseApproximation
¶

class
dmipy.signal_models.cylinder_models.
C4CylinderGaussianPhaseApproximation
(mu=None, lambda_par=None, diameter=None, diffusion_perpendicular=1.7e09) Bases:
dmipy.core.modeling_framework.ModelProperties
The Gaussian phase model [R77]  a cylinder with finite radius  typically used for intraaxonal diffusion. The perpendicular diffusion is modelled after Van Gelderen’s solution for the disk. It is dependent on gradient strength, pulse separation and pulse length.
Parameters: mu : array, shape(2),
angles [theta, phi] representing main orientation on the sphere. theta is inclination of polar angle of main angle mu [0, pi]. phi is polar angle of main angle mu [pi, pi].
lambda_par : float,
parallel diffusivity in 10^9 m^2/s.
diameter : float,
cylinder (axon) diameter in meters.
References
[R77] (1, 2) Van Gelderen et al. “Evaluation of Restricted Diffusion in Cylinders. Phosphocreatine in Rabbit Leg Muscle” Journal of Magnetic Resonance Series B (1994) Attributes
Methods

__init__
(mu=None, lambda_par=None, diameter=None, diffusion_perpendicular=1.7e09)¶

perpendicular_attenuation
(gradient_strength, delta, Delta, diameter) Calculates the cylinder’s perpendicular signal attenuation.

rotational_harmonics_representation
(acquisition_scheme, **kwargs) The rotational harmonics of the model, such that Y_lm = Yl0. Axis aligned with zaxis to be used as kernel for spherical convolution. Returns an array with rotational harmonics for each shell.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: rh_array : array, shape(Nshells, N_rh_coef),
Rotational harmonics coefficients for each shell.

spherical_mean
(acquisition_scheme, **kwargs) Estimates spherical mean for every shell in acquisition scheme.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: E_mean : float,
spherical mean of the model for every acquisition shell.

ModelProperties
¶

class
dmipy.signal_models.cylinder_models.
ModelProperties
¶ Contains various properties for CompartmentModels.
Attributes

parameter_cardinality
¶ Returns the cardinality of model parameters

parameter_names
¶ Returns the names of model parameters.

parameter_ranges
¶ Returns the optimization ranges of the model parameters. These ranges are given in O(1) scale so optimization algorithms don’t suffer from large scale differences in optimization parameters.

parameter_scales
¶ Returns the optimization scales for the model parameters. The scales scale the parameter_ranges to their actual size inside optimization algorithms.

parameter_types
¶ Returns the optimization scales for the model parameters. The scales scale the parameter_ranges to their actual size inside optimization algorithms.

optional_package¶

dmipy.signal_models.cylinder_models.
optional_package
(name, trip_msg=None)¶ Return packagelike thing and module setup for package name
Parameters: name : str
package name
trip_msg : None or str
message to give when someone tries to use the return package, but we could not import it, and have returned a TripWire object instead. Default message if None.
Returns: pkg_like : module or
TripWire
instanceIf we can import the package, return it. Otherwise return an object raising an error when accessed
have_pkg : bool
True if import for package was successful, false otherwise
module_setup : function
callable usually set as
setup_module
in calling namespace, to allow skipping tests.
G1Ball
¶

class
dmipy.signal_models.gaussian_models.
G1Ball
(lambda_iso=None) Bases:
dmipy.core.modeling_framework.ModelProperties
The Ball model [R78]  an isotropic Tensor with one diffusivity.
Parameters: lambda_iso : float,
isotropic diffusivity in m^2/s.
References
[R78] (1, 2) Behrens et al. “Characterization and propagation of uncertainty in
diffusionweighted MR imaging”Magnetic Resonance in Medicine (2003)
Attributes
Methods

__init__
(lambda_iso=None)¶

rotational_harmonics_representation
(acquisition_scheme, **kwargs) The rotational harmonics of the model, such that Y_lm = Yl0. Axis aligned with zaxis to be used as kernel for spherical convolution. Returns an array with rotational harmonics for each shell.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: rh_array : array, shape(Nshells, N_rh_coef),
Rotational harmonics coefficients for each shell.

spherical_mean
(acquisition_scheme, **kwargs) Estimates spherical mean for every shell in acquisition scheme
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: E_mean : float,
spherical mean of the model for every acquisition shell.

G2Zeppelin
¶

class
dmipy.signal_models.gaussian_models.
G2Zeppelin
(mu=None, lambda_par=None, lambda_perp=None) Bases:
dmipy.core.modeling_framework.ModelProperties
The Zeppelin model [R79]  an axially symmetric Tensor  typically used for extraaxonal diffusion.
Parameters: mu : array, shape(2),
angles [theta, phi] representing main orientation on the sphere. theta is inclination of polar angle of main angle mu [0, pi]. phi is polar angle of main angle mu [pi, pi].
lambda_par : float,
parallel diffusivity in m^2/s.
lambda_perp : float,
perpendicular diffusivity in m^2/s.
Returns: E_zeppelin : float or array, shape(N),
signal attenuation.
References
[R79] (1, 2) Panagiotaki et al. “Compartment models of the diffusion MR signal in brain white
matter: a taxonomy and comparison”. NeuroImage (2012)Attributes
Methods

__init__
(mu=None, lambda_par=None, lambda_perp=None)¶

rotational_harmonics_representation
(acquisition_scheme, **kwargs) The rotational harmonics of the model, such that Y_lm = Yl0. Axis aligned with zaxis to be used as kernel for spherical convolution. Returns an array with rotational harmonics for each shell.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: rh_array : array, shape(Nshells, N_rh_coef),
Rotational harmonics coefficients for each shell.

spherical_mean
(acquisition_scheme, **kwargs) Estimates spherical mean for every shell in acquisition scheme for Zeppelin model.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: E_mean : float,
spherical mean of the Zeppelin model for every acquisition shell.

G3TemporalZeppelin
¶

class
dmipy.signal_models.gaussian_models.
G3TemporalZeppelin
(mu=None, lambda_par=None, lambda_inf=None, A=None) Bases:
dmipy.core.modeling_framework.ModelProperties
The temporal Zeppelin model [R80]  an axially symmetric Tensor  typically used to describe extraaxonal diffusion. The G3TemporalZeppelin differs from G2Zeppelin in that it has a timedependent perpendicular parameter “A”, which describe extraaxonal diffusion hindrance due to axon packing, and that lambda_perp is instead called lambda_inf, as it describes the perpendicular diffusivity when diffusion time is infinite.
Parameters: mu : array, shape(2),
angles [theta, phi] representing main orientation on the sphere. theta is inclination of polar angle of main angle mu [0, pi]. phi is polar angle of main angle mu [pi, pi].
lambda_par : float,
parallel diffusivity in 10^9 m^2/s.
lambda_inf : float,
bulk diffusivity constant 10^9 m^2/s.
A: float, :
characteristic coefficient in 10^12 m^2
Returns: E_zeppelin : float or array, shape(N),
signal attenuation.
References
[R80] (1, 2) Burcaw, L.M., Fieremans, E., Novikov, D.S., 2015. Mesoscopic structure of neuronal tracts from timedependent diffusion. NeuroImage 114, 18. Attributes
Methods

__init__
(mu=None, lambda_par=None, lambda_inf=None, A=None)¶

rotational_harmonics_representation
(acquisition_scheme, **kwargs) The rotational harmonics of the model, such that Y_lm = Yl0. Axis aligned with zaxis to be used as kernel for spherical convolution. Returns an array with rotational harmonics for each shell.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: rh_array : array, shape(Nshells, N_rh_coef),
Rotational harmonics coefficients for each shell.

spherical_mean
(acquisition_scheme, **kwargs) Estimates spherical mean for every shell in acquisition scheme for Restricted Zeppelin model.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: E_mean : float,
spherical mean of the Restricted Zeppelin model for every acquisition shell.

ModelProperties
¶

class
dmipy.signal_models.gaussian_models.
ModelProperties
¶ Contains various properties for CompartmentModels.
Attributes

parameter_cardinality
¶ Returns the cardinality of model parameters

parameter_names
¶ Returns the names of model parameters.

parameter_ranges
¶ Returns the optimization ranges of the model parameters. These ranges are given in O(1) scale so optimization algorithms don’t suffer from large scale differences in optimization parameters.

parameter_scales
¶ Returns the optimization scales for the model parameters. The scales scale the parameter_ranges to their actual size inside optimization algorithms.

parameter_types
¶ Returns the optimization scales for the model parameters. The scales scale the parameter_ranges to their actual size inside optimization algorithms.

optional_package¶

dmipy.signal_models.gaussian_models.
optional_package
(name, trip_msg=None)¶ Return packagelike thing and module setup for package name
Parameters: name : str
package name
trip_msg : None or str
message to give when someone tries to use the return package, but we could not import it, and have returned a TripWire object instead. Default message if None.
Returns: pkg_like : module or
TripWire
instanceIf we can import the package, return it. Otherwise return an object raising an error when accessed
have_pkg : bool
True if import for package was successful, false otherwise
module_setup : function
callable usually set as
setup_module
in calling namespace, to allow skipping tests.
ModelProperties
¶

class
dmipy.signal_models.plane_models.
ModelProperties
¶ Contains various properties for CompartmentModels.
Attributes

parameter_cardinality
¶ Returns the cardinality of model parameters

parameter_names
¶ Returns the names of model parameters.

parameter_ranges
¶ Returns the optimization ranges of the model parameters. These ranges are given in O(1) scale so optimization algorithms don’t suffer from large scale differences in optimization parameters.

parameter_scales
¶ Returns the optimization scales for the model parameters. The scales scale the parameter_ranges to their actual size inside optimization algorithms.

parameter_types
¶ Returns the optimization scales for the model parameters. The scales scale the parameter_ranges to their actual size inside optimization algorithms.

P2PlaneStejskalTannerApproximation
¶

class
dmipy.signal_models.plane_models.
P2PlaneStejskalTannerApproximation
(diameter=None)¶ Bases:
dmipy.core.modeling_framework.ModelProperties
StejskalTanner approximation of diffusion between two infinitely large parallel planes. Assumes shortgradient pulse (SGP) approximation (pulse length towards zero) and the long diffusion time limit (pulse separation towards infinity). We follow the notation of Balinov [R81].
References
[R81] (1, 2) Balinov, Balin, et al. “The NMR selfdiffusion method applied to restricted diffusion. Simulation of echo attenuation from molecules in spheres and between planes.” Journal of Magnetic Resonance, Series A 104.1 (1993): 1725. Attributes
Methods

__init__
(diameter=None)¶

plane_attenuation
(q, diameter)¶ Equation 6 in Balinov et al. (1993).

P3PlaneCallaghanApproximation
¶

class
dmipy.signal_models.plane_models.
P3PlaneCallaghanApproximation
(diameter=None, diffusion_constant=1.7e09, number_of_roots=40) Bases:
dmipy.core.modeling_framework.ModelProperties
The Callaghan model [1]_ of diffusion between two parallel infinite plates.
Parameters: diameter : float
Distance between the two plates in meters.
diffusion_constant : float,
The diffusion constant of the water particles between the two planes. The default value is the approximate diffusivity of water inside axons as 1.7e9 m^2/s.
number_of_roots : integer,
The number of roots for the Callaghan approximation.
References
 [1] Callaghan, “PulsedGradient SpinEcho NMR for Planar, Cylindrical,
 and Spherical Pores under Conditions of Wall Relaxation”, JMR 1995
Attributes
Methods

__init__
(diameter=None, diffusion_constant=1.7e09, number_of_roots=40)¶

plane_attenuation
(q, tau, diameter) Implements the finite time Callaghan model for planes.
ModelProperties
¶

class
dmipy.signal_models.sphere_models.
ModelProperties
¶ Contains various properties for CompartmentModels.
Attributes

parameter_cardinality
¶ Returns the cardinality of model parameters

parameter_names
¶ Returns the names of model parameters.

parameter_ranges
¶ Returns the optimization ranges of the model parameters. These ranges are given in O(1) scale so optimization algorithms don’t suffer from large scale differences in optimization parameters.

parameter_scales
¶ Returns the optimization scales for the model parameters. The scales scale the parameter_ranges to their actual size inside optimization algorithms.

parameter_types
¶ Returns the optimization scales for the model parameters. The scales scale the parameter_ranges to their actual size inside optimization algorithms.

S1Dot
¶

class
dmipy.signal_models.sphere_models.
S1Dot
Bases:
dmipy.core.modeling_framework.ModelProperties
The Dot model [R82]  an nondiffusing compartment. It has no parameters and returns 1 no matter the input.
References
[R82] (1, 2) Panagiotaki et al. “Compartment models of the diffusion MR signal in brain white
matter: a taxonomy and comparison”. NeuroImage (2012)Attributes
Methods

rotational_harmonics_representation
(acquisition_scheme, **kwargs) The rotational harmonics of the model, such that Y_lm = Yl0. Axis aligned with zaxis to be used as kernel for spherical convolution. Returns an array with rotational harmonics for each shell.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: rh_array : array, shape(Nshells, N_rh_coef),
Rotational harmonics coefficients for each shell.

spherical_mean
(acquisition_scheme, **kwargs) Estimates spherical mean for every shell in acquisition scheme.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: E_mean : float,
spherical mean of the model for every acquisition shell.

S2SphereStejskalTannerApproximation
¶

class
dmipy.signal_models.sphere_models.
S2SphereStejskalTannerApproximation
(diameter=None) Bases:
dmipy.core.modeling_framework.ModelProperties
The Stejskal Tanner signal approximation of a sphere model. It assumes that pulse length is infinitessimally small and diffusion time large enough so that the diffusion is completely restricted. Only depends on qvalue.
Parameters: diameter : float,
sphere diameter in meters.
References
[R83] Balinov, Balin, et al. “The NMR selfdiffusion method applied to restricted diffusion. Simulation of echo attenuation from molecules in spheres and between planes.” Journal of Magnetic Resonance, Series A 104.1 (1993): 1725. Attributes
Methods

__init__
(diameter=None)¶

rotational_harmonics_representation
(acquisition_scheme, **kwargs) The rotational harmonics of the model, such that Y_lm = Yl0. Axis aligned with zaxis to be used as kernel for spherical convolution. Returns an array with rotational harmonics for each shell.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: rh_array : array, shape(Nshells, N_rh_coef),
Rotational harmonics coefficients for each shell.

sphere_attenuation
(q, diameter) The signal attenuation for the sphere model.

spherical_mean
(acquisition_scheme, **kwargs) Estimates spherical mean for every shell in acquisition scheme.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: E_mean : float,
spherical mean of the model for every acquisition shell.

S4SphereGaussianPhaseApproximation
¶

class
dmipy.signal_models.sphere_models.
S4SphereGaussianPhaseApproximation
(diameter=None, diffusion_constant=1.7e09)¶ Bases:
dmipy.core.modeling_framework.ModelProperties
The gaussian phase approximation for diffusion inside a sphere according to [R84]. It is dependent on gradient strength, pulse separation and pulse length.
References
[R84] (1, 2) Balinov, Balin, et al. “The NMR selfdiffusion method applied to restricted diffusion. Simulation of echo attenuation from molecules in spheres and between planes.” Journal of Magnetic Resonance, Series A 104.1 (1993): 1725. Attributes
Methods

__init__
(diameter=None, diffusion_constant=1.7e09)¶

SPHERE_TRASCENDENTAL_ROOTS
= array([ 2.08157598, 5.94036999, 9.20584014, 12.40444502, 15.57923641, 18.74264558, 21.89969648, 25.05282528, 28.203361 , 31.35209173, 34.49951492, 37.64596032, 40.79165523, 43.93676147, 47.08139741, 50.22565165, 53.3695918 , 56.51327045, 59.656729 , 62.80000055, 65.9431119 , 69.08608495, 72.22893775, 75.3716854 , 78.51434055, 81.6569138 , 84.7994144 , 87.94185005, 91.0842275 , 94.22655255, 97.36883035, 100.5110653 , 103.6532613 , 106.7954217 , 109.9375497 , 113.079648 , 116.2217188 , 119.3637645 , 122.505787 , 125.647788 , 128.789769 , 131.9317315 , 135.0736768 , 138.2156061 , 141.3575204 , 144.4994207 , 147.641308 , 150.7831829 , 153.9250463 , 157.0668989 , 160.2087413 , 163.3505741 , 166.4923978 , 169.6342129 , 172.77602 , 175.9178194 , 179.0596116 , 182.2013968 , 185.3431756 , 188.4849481 , 191.6267147 , 194.7684757 , 197.9102314 , 201.051982 , 204.1937277 , 207.3354688 , 210.4772054 , 213.6189378 , 216.7606662 , 219.9023907 , 223.0441114 , 226.1858287 , 229.3275425 , 232.469253 , 235.6109603 , 238.7526647 , 241.8943662 , 245.0360648 , 248.1777608 , 251.3194542 , 254.4611451 , 257.6028336 , 260.7445198 , 263.8862038 , 267.0278856 , 270.1695654 , 273.3112431 , 276.4529189 , 279.5945929 , 282.736265 , 285.8779354 , 289.0196041 , 292.1612712 , 295.3029367 , 298.4446006 , 301.5862631 , 304.7279241 , 307.8695837 , 311.011242 , 314.152899 ])¶

rotational_harmonics_representation
(acquisition_scheme, **kwargs)¶ The rotational harmonics of the model, such that Y_lm = Yl0. Axis aligned with zaxis to be used as kernel for spherical convolution. Returns an array with rotational harmonics for each shell.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: rh_array : array, shape(Nshells, N_rh_coef),
Rotational harmonics coefficients for each shell.

sphere_attenuation
(gradient_strength, delta, Delta, diameter)¶ Calculates the sphere signal attenuation.

spherical_mean
(acquisition_scheme, **kwargs)¶ Estimates spherical mean for every shell in acquisition scheme.
Parameters: acquisition_scheme : DmipyAcquisitionScheme instance,
An acquisition scheme that has been instantiated using dMipy.
kwargs: keyword arguments to the model parameter values, :
Is internally given as **parameter_dictionary.
Returns: E_mean : float,
spherical mean of the model for every acquisition shell.

utils
¶
Module: utils.spherical_convolution
¶

dmipy.utils.spherical_convolution.
real_sym_rh_basis
(sh_order, theta, phi)¶ Samples a real symmetric rotational harmonic basis at point on the sphere
Samples the basis functions up to order sh_order at points on the sphere given by theta and phi. The basis functions are defined here the same way as in fibernavigator, where the real harmonic \(Y^m_n\) is defined to be:
\(Y^0_n\) if m = 0Parameters: sh_order : int
even int > 0, max spherical harmonic degree
theta : float [0, 2*pi]
The azimuthal (longitudinal) coordinate.
phi : float [0, pi]
The polar (colatitudinal) coordinate.
Returns: real_rh_matrix : array of shape ()
The real harmonic \(Y^0_n\) sampled at theta and phi

dmipy.utils.spherical_convolution.
sh_convolution
(f_distribution_sh, kernel_rh)¶ Spherical convolution between a fiber distribution (f) in spherical harmonics and a kernel in terms of rotational harmonics (oriented along the zaxis).
Parameters: f_distribution_sh : array, shape (sh_coef)
spherical harmonic coefficients of a fiber distribution.
kernel_rh : array, shape (sh_coef),
rotational harmonic coefficients of the convolution kernel. In our case this is the spherical signal of one microenvironment at one bvalue.
Returns: f_kernel_convolved : array, shape (sh_coef)
spherical harmonic coefficients of the convolved kernel and distribution.
Module: utils.spherical_mean
¶

dmipy.utils.spherical_mean.
estimate_spherical_mean_multi_shell
(E_attenuation, acquisition_scheme, sh_order=6)¶ Estimates the spherical mean per shell of multishell acquisition. Uses spherical harmonics to do the estimation.
Parameters: E_attenuation : array, shape (N),
signal attenuation.
bvecs : array, shape (N x 3),
x, y, z components of cartesian unit bvectors.
b_shell_indices : array, shape (N)
array of integers indicating which measurement belongs to which shell. 0 should be used for b0 measurements, 1 for the lowest bvalue shell, 2 for the second lowest etc.
Returns: E_mean : array, shape (number of bshells)
spherical means of the signal attenuation per shell of the. For example, if there are three shells in the acquisition then the array is of length 3.

dmipy.utils.spherical_mean.
estimate_spherical_mean_shell
(E_shell, bvecs_shell, sh_order=6, sh_mat=None)¶ Estimates spherical mean of a shell of measurements using spherical harmonics. The spherical mean is contained only in the Y00 spherical harmonic, as long as the basis expansion order is sufficient to capture the spherical signal.
Parameters: E_shell : array, shape(N),
signal attenuation values.
bvecs_shell : array, shape (N x 3),
Cartesian unit vectors describing the orientation of the signal attenuation values.
sh_order : integer,
maximum spherical harmonics order. It needs to be high enough to describe the spherical profile of the signal attenuation. The order 6 is sufficient to describe a stick at bvalues up to 10,000 s/mm^2.
sh_mat : array of size (N_bvecs, N_coefficients),
possibly precomputed spherical harmonics transform matrix.
Returns: E_mean : float,
spherical mean of the signal attenuation.
Module: utils.utils
¶

dmipy.utils.utils.
perpendicular_vector
(v)¶ Returns a perpendicular vector to vector “v”.
Parameters: v : array, shape (3)
normally Cartesian unit vector, but can also be any vector.
Returns: v_perp : array, shape (3)
If v is unit vector, v_perp is a Cartesian unit vector perpendicular to v.

dmipy.utils.utils.
rotation_matrix_around_100
(psi)¶ Generates a rotation matrix that rotates around the xaxis (1, 0, 0).
Parameters: psi : float,
euler angle [0, pi].
Returns: R : array, shape (3 x 3)
Rotation matrix.

dmipy.utils.utils.
rotation_matrix_100_to_theta_phi
(theta, phi)¶ Generates a rotation matrix that rotates from the xaxis (1, 0, 0) to an other position on the unit sphere.
Parameters: theta : float,
inclination of polar angle of main angle mu [0, pi].
phi : float,
polar angle of main angle mu [pi, pi].
Returns: R : array, shape (3 x 3)
Rotation matrix.

dmipy.utils.utils.
rotation_matrix_100_to_xyz
(x, y, z)¶ Generates a rotation matrix that rotates from the xaxis (1, 0, 0) to an other position in Cartesian space.
Parameters: x, y, z : floats,
position in Cartesian space.
Returns: R : array, shape (3 x 3)
Rotation matrix.

dmipy.utils.utils.
rotation_matrix_001_to_xyz
(x, y, z)¶ Generates a rotation matrix that rotates from the zaxis (0, 0, 1) to an other position in Cartesian space.
Parameters: x, y, z : floats,
position in Cartesian space.
Returns: R : array, shape (3 x 3)
Rotation matrix.

dmipy.utils.utils.
rotation_matrix_100_to_theta_phi_psi
(theta, phi, psi)¶ Generates a rotation matrix that rotates from the xaxis (1, 0, 0) to an other position in Cartesian space, and rotates about its axis.
Parameters: theta : float,
inclination of polar angle of main angle mu [0, pi].
phi : float,
polar angle of main angle mu [pi, pi].
psi : float,
angle in radians of the bingham distribution around mu [0, pi].
Returns: R : array, shape (3 x 3)
Rotation matrix.

dmipy.utils.utils.
T1_tortuosity
(lambda_par, vf_intra, vf_extra=None)¶ Tortuosity model for perpendicular extraaxonal diffusivity [1, 2, 3]. If vf_extra=None, then vf_intra must be a nested volume fraction, in the sense that E_bundle = vf_intra * E_intra + (1  vf_intra) * E_extra, with vf_intra + (1  vf_intra) = 1. If both vf_intra and vf_extra are given, then they have be be normalized fractions, in the sense that vf_intra + vf_extra <= 1.
Parameters: lambda_par : float,
parallel diffusivity.
vf_intra : float,
intraaxonal volume fraction [0, 1].
vf_extra : float, (optional)
extraaxonal volume fraction [0, 1].
Returns: lambda_perp : float,
Rotation matrix.
References :
—— :
.. [1] Bruggeman, Von DAG. “Berechnung verschiedener physikalischer :
Konstanten von heterogenen Substanzen. I. Dielektrizitätskonstanten und Leitfähigkeiten der Mischkörper aus isotropen Substanzen.” Annalen der physik 416.7 (1935): 636664.
.. [2] Sen et al. “A selfsimilar model for sedimentary rocks with :
application to the dielectric constant of fused glass beads.” Geophysics 46.5 (1981): 781795.
.. [3] Szafer et al. “Theoretical model for water diffusion in tissues.” :
Magnetic resonance in medicine 33.5 (1995): 697712.

dmipy.utils.utils.
parameter_equality
(param)¶ Function to force two model parameters to be equal in the optimization

dmipy.utils.utils.
define_shell_indices
(bvals, b_value_ranges)¶ Function to facilitate defining shell indices given some manual ranges in bvalues. This function is useful as in practice the actual bvalues may fluctuate slightly around the planned bvalue. This information is needed by some models doing spherical convolutions or spherical means. CAUTION: If a data set has variations in pulse duration delta and/or pulse separation Delta, then different shells can have similar bvalues. This means these shells may not be separable in bvalue, and you’ll have to do it manually.
Parameters: bvals : 1D array of size (N_data),
The bvalues corresponding to the measured DWIs.
b_value_ranges : 2D array of size (N_shells, 2)
A list indicating for every shell the lower and upper bvalue range.
Returns: shell_indices : 1D integer array of size (N_data),
The shell indices corresponding to each DWI measurement. The index 0 corresponds with the b0 measurements, while higher numbers indicate other shells. The numbers are ordered in the same order they are given in b_value_ranges.
mean_shell_bvals : 1D array of size (N_shells),
The mean bvalue in each shell.

dmipy.utils.utils.
cart2sphere
(cartesian_coordinates)¶ “Function to estimate spherical coordinates from cartesian coordinates according to wikipedia. Conforms with the dipy notation.
Parameters: cartesian_coordinates : array of size (3) or (N x 3),
array of cartesian coordinate vectors [x, y, z].
Returns: spherical_coordinates : array of size (3) or (N x 3),
array of spherical coordinate vectors [r, theta, phi]. range of theta [0, pi]. range of phi [pi, pi].

dmipy.utils.utils.
cart2mu
(xyz)¶ Function to estimate spherical coordinates from cartesian coordinates according to wikipedia. Conforms with the dipy notation.
Parameters: cartesian_coordinates : array of size (3) or (N x 3),
array of cartesian coordinate vectors [x, y, z].
Returns: spherical_coordinates : array of size (2) or (N x 2),
array of spherical coordinate vectors [theta, phi]. range of theta [0, pi]. range of phi [pi, pi].

dmipy.utils.utils.
R2mu_psi
(R)¶ Function to estimate orientation mu and secondary orientation angle psi from a 3x3 rotation matrix. Can be given array of rotation matrices.
Parameters: R : Array of size (N, 3, 3)
rotation matrices that possibly can be estimated by DTI.
Returns: mu : array of size (N, 2),
orientations in [theta, phi] angles
psi : array of size (N),
secondary orientation psi (for Bingham for example).

dmipy.utils.utils.
sphere2cart
(spherical_coordinates)¶ “Function to estimate cartesian coordinates from spherical coordinates according to wikipedia. Conforms with the dipy notation.
Parameters: spherical_coordinates : array of size (3) or (N x 3),
array of spherical coordinate vectors [r, theta, phi]. range of theta [0, pi]. range of phi [pi, pi].
Returns: cartesian_coordinates : array of size (3) or (N x 3),
array of cartesian coordinate vectors [x, y, z].

dmipy.utils.utils.
unitsphere2cart_1d
(mu)¶ Optimized function dedicated to convert 1D unit sphere coordinates to cartesian coordinates.
Parameters: mu : array of size (2)
unit sphere coordinates, as theta, phi = mu
Returns: mu_cart, array of size (3) :
mu in cartesian coordinates, as x, y, z = mu_cart

dmipy.utils.utils.
unitsphere2cart_Nd
(mu)¶ Optimized function deicated to convert 1D unit sphere coordinates to cartesian coordinates.
Parameters: mu : Nd array of size (…, 2)
unit sphere coordinates, as theta, phi = mu
Returns: mu_cart, Nd array of size (…, 3) :
mu in cartesian coordinates, as x, y, z = mu_cart
optional_package¶

dmipy.utils.spherical_convolution.
optional_package
(name, trip_msg=None)¶ Return packagelike thing and module setup for package name
Parameters: name : str
package name
trip_msg : None or str
message to give when someone tries to use the return package, but we could not import it, and have returned a TripWire object instead. Default message if None.
Returns: pkg_like : module or
TripWire
instanceIf we can import the package, return it. Otherwise return an object raising an error when accessed
have_pkg : bool
True if import for package was successful, false otherwise
module_setup : function
callable usually set as
setup_module
in calling namespace, to allow skipping tests.
real_sph_harm¶

dmipy.utils.spherical_convolution.
real_sph_harm
(m, n, theta, phi)¶ Compute real spherical harmonics.
Where the real harmonic \(Y^m_n\) is defined to be:
Imag(\(Y^m_n\)) * sqrt(2) if m > 0 \(Y^0_n\) if m = 0 Real(\(Y^m_n\)) * sqrt(2) if m < 0This may take scalar or array arguments. The inputs will be broadcasted against each other.
Parameters: m : int
m <= n
The order of the harmonic.
n : int
>= 0
The degree of the harmonic.
theta : float [0, 2*pi]
The azimuthal (longitudinal) coordinate.
phi : float [0, pi]
The polar (colatitudinal) coordinate.
Returns: y_mn : real float
The real harmonic \(Y^m_n\) sampled at theta and phi.
See also
scipy.special.sph_harm
real_sym_rh_basis¶

dmipy.utils.spherical_convolution.
real_sym_rh_basis
(sh_order, theta, phi) Samples a real symmetric rotational harmonic basis at point on the sphere
Samples the basis functions up to order sh_order at points on the sphere given by theta and phi. The basis functions are defined here the same way as in fibernavigator, where the real harmonic \(Y^m_n\) is defined to be:
\(Y^0_n\) if m = 0Parameters: sh_order : int
even int > 0, max spherical harmonic degree
theta : float [0, 2*pi]
The azimuthal (longitudinal) coordinate.
phi : float [0, pi]
The polar (colatitudinal) coordinate.
Returns: real_rh_matrix : array of shape ()
The real harmonic \(Y^0_n\) sampled at theta and phi
sh_convolution¶

dmipy.utils.spherical_convolution.
sh_convolution
(f_distribution_sh, kernel_rh) Spherical convolution between a fiber distribution (f) in spherical harmonics and a kernel in terms of rotational harmonics (oriented along the zaxis).
Parameters: f_distribution_sh : array, shape (sh_coef)
spherical harmonic coefficients of a fiber distribution.
kernel_rh : array, shape (sh_coef),
rotational harmonic coefficients of the convolution kernel. In our case this is the spherical signal of one microenvironment at one bvalue.
Returns: f_kernel_convolved : array, shape (sh_coef)
spherical harmonic coefficients of the convolved kernel and distribution.
estimate_spherical_mean_multi_shell¶

dmipy.utils.spherical_mean.
estimate_spherical_mean_multi_shell
(E_attenuation, acquisition_scheme, sh_order=6) Estimates the spherical mean per shell of multishell acquisition. Uses spherical harmonics to do the estimation.
Parameters: E_attenuation : array, shape (N),
signal attenuation.
bvecs : array, shape (N x 3),
x, y, z components of cartesian unit bvectors.
b_shell_indices : array, shape (N)
array of integers indicating which measurement belongs to which shell. 0 should be used for b0 measurements, 1 for the lowest bvalue shell, 2 for the second lowest etc.
Returns: E_mean : array, shape (number of bshells)
spherical means of the signal attenuation per shell of the. For example, if there are three shells in the acquisition then the array is of length 3.
estimate_spherical_mean_shell¶

dmipy.utils.spherical_mean.
estimate_spherical_mean_shell
(E_shell, bvecs_shell, sh_order=6, sh_mat=None) Estimates spherical mean of a shell of measurements using spherical harmonics. The spherical mean is contained only in the Y00 spherical harmonic, as long as the basis expansion order is sufficient to capture the spherical signal.
Parameters: E_shell : array, shape(N),
signal attenuation values.
bvecs_shell : array, shape (N x 3),
Cartesian unit vectors describing the orientation of the signal attenuation values.
sh_order : integer,
maximum spherical harmonics order. It needs to be high enough to describe the spherical profile of the signal attenuation. The order 6 is sufficient to describe a stick at bvalues up to 10,000 s/mm^2.
sh_mat : array of size (N_bvecs, N_coefficients),
possibly precomputed spherical harmonics transform matrix.
Returns: E_mean : float,
spherical mean of the signal attenuation.
real_sym_sh_mrtrix¶

dmipy.utils.spherical_mean.
real_sym_sh_mrtrix
(sh_order, theta, phi)¶ Compute real spherical harmonics as in mrtrix, where the real harmonic \(Y^m_n\) is defined to be:
Real(:math:`Y^m_n`) if m > 0 :math:`Y^0_n` if m = 0 Imag(:math:`Y^m_n`) if m < 0
This may take scalar or array arguments. The inputs will be broadcasted against each other.
Parameters: sh_order : int
The maximum degree or the spherical harmonic basis.
theta : float [0, pi]
The polar (colatitudinal) coordinate.
phi : float [0, 2*pi]
The azimuthal (longitudinal) coordinate.
Returns: y_mn : real float
The real harmonic \(Y^m_n\) sampled at theta and phi as implemented in mrtrix. Warning: the basis is Tournier et al 2004 and 2007 is slightly different.
m : array
The order of the harmonics.
n : array
The degree of the harmonics.
R2mu_psi¶

dmipy.utils.utils.
R2mu_psi
(R) Function to estimate orientation mu and secondary orientation angle psi from a 3x3 rotation matrix. Can be given array of rotation matrices.
Parameters: R : Array of size (N, 3, 3)
rotation matrices that possibly can be estimated by DTI.
Returns: mu : array of size (N, 2),
orientations in [theta, phi] angles
psi : array of size (N),
secondary orientation psi (for Bingham for example).
T1_tortuosity¶

dmipy.utils.utils.
T1_tortuosity
(lambda_par, vf_intra, vf_extra=None) Tortuosity model for perpendicular extraaxonal diffusivity [1, 2, 3]. If vf_extra=None, then vf_intra must be a nested volume fraction, in the sense that E_bundle = vf_intra * E_intra + (1  vf_intra) * E_extra, with vf_intra + (1  vf_intra) = 1. If both vf_intra and vf_extra are given, then they have be be normalized fractions, in the sense that vf_intra + vf_extra <= 1.
Parameters: lambda_par : float,
parallel diffusivity.
vf_intra : float,
intraaxonal volume fraction [0, 1].
vf_extra : float, (optional)
extraaxonal volume fraction [0, 1].
Returns: lambda_perp : float,
Rotation matrix.
References :
—— :
.. [1] Bruggeman, Von DAG. “Berechnung verschiedener physikalischer :
Konstanten von heterogenen Substanzen. I. Dielektrizitätskonstanten und Leitfähigkeiten der Mischkörper aus isotropen Substanzen.” Annalen der physik 416.7 (1935): 636664.
.. [2] Sen et al. “A selfsimilar model for sedimentary rocks with :
application to the dielectric constant of fused glass beads.” Geophysics 46.5 (1981): 781795.
.. [3] Szafer et al. “Theoretical model for water diffusion in tissues.” :
Magnetic resonance in medicine 33.5 (1995): 697712.
cart2mu¶

dmipy.utils.utils.
cart2mu
(xyz) Function to estimate spherical coordinates from cartesian coordinates according to wikipedia. Conforms with the dipy notation.
Parameters: cartesian_coordinates : array of size (3) or (N x 3),
array of cartesian coordinate vectors [x, y, z].
Returns: spherical_coordinates : array of size (2) or (N x 2),
array of spherical coordinate vectors [theta, phi]. range of theta [0, pi]. range of phi [pi, pi].
cart2sphere¶

dmipy.utils.utils.
cart2sphere
(cartesian_coordinates) “Function to estimate spherical coordinates from cartesian coordinates according to wikipedia. Conforms with the dipy notation.
Parameters: cartesian_coordinates : array of size (3) or (N x 3),
array of cartesian coordinate vectors [x, y, z].
Returns: spherical_coordinates : array of size (3) or (N x 3),
array of spherical coordinate vectors [r, theta, phi]. range of theta [0, pi]. range of phi [pi, pi].
define_shell_indices¶

dmipy.utils.utils.
define_shell_indices
(bvals, b_value_ranges) Function to facilitate defining shell indices given some manual ranges in bvalues. This function is useful as in practice the actual bvalues may fluctuate slightly around the planned bvalue. This information is needed by some models doing spherical convolutions or spherical means. CAUTION: If a data set has variations in pulse duration delta and/or pulse separation Delta, then different shells can have similar bvalues. This means these shells may not be separable in bvalue, and you’ll have to do it manually.
Parameters: bvals : 1D array of size (N_data),
The bvalues corresponding to the measured DWIs.
b_value_ranges : 2D array of size (N_shells, 2)
A list indicating for every shell the lower and upper bvalue range.
Returns: shell_indices : 1D integer array of size (N_data),
The shell indices corresponding to each DWI measurement. The index 0 corresponds with the b0 measurements, while higher numbers indicate other shells. The numbers are ordered in the same order they are given in b_value_ranges.
mean_shell_bvals : 1D array of size (N_shells),
The mean bvalue in each shell.
fractional_parameter¶

dmipy.utils.utils.
fractional_parameter
(fractional_parameter, parameter2)¶ Defines fractional parameter link where the original parameter ranges between 01 of parameter2.
Parameters: fractional_parameter : string
new parameter that ranges between 0 and 1.
parameter2 : string
parameter that is larger or equal than the original parameter
get_sphere¶

dmipy.utils.utils.
get_sphere
(name='symmetric362')¶ provide triangulated spheres
Parameters: name : str
which sphere  one of: * ‘symmetric362’ * ‘symmetric642’ * ‘symmetric724’ * ‘repulsion724’ * ‘repulsion100’ * ‘repulsion200’
Returns: sphere : a dipy.core.sphere.Sphere class instance
Examples
>>> import numpy as np >>> from dipy.data import get_sphere >>> sphere = get_sphere('symmetric362') >>> verts, faces = sphere.vertices, sphere.faces >>> verts.shape == (362, 3) True >>> faces.shape == (720, 3) True >>> verts, faces = get_sphere('not a sphere name') Traceback (most recent call last): ... DataError: No sphere called "not a sphere name"
optional_package¶

dmipy.utils.utils.
optional_package
(name, trip_msg=None)¶ Return packagelike thing and module setup for package name
Parameters: name : str
package name
trip_msg : None or str
message to give when someone tries to use the return package, but we could not import it, and have returned a TripWire object instead. Default message if None.
Returns: pkg_like : module or
TripWire
instanceIf we can import the package, return it. Otherwise return an object raising an error when accessed
have_pkg : bool
True if import for package was successful, false otherwise
module_setup : function
callable usually set as
setup_module
in calling namespace, to allow skipping tests.
parameter_equality¶

dmipy.utils.utils.
parameter_equality
(param) Function to force two model parameters to be equal in the optimization
perpendicular_vector¶

dmipy.utils.utils.
perpendicular_vector
(v) Returns a perpendicular vector to vector “v”.
Parameters: v : array, shape (3)
normally Cartesian unit vector, but can also be any vector.
Returns: v_perp : array, shape (3)
If v is unit vector, v_perp is a Cartesian unit vector perpendicular to v.
rotation_matrix_001_to_xyz¶

dmipy.utils.utils.
rotation_matrix_001_to_xyz
(x, y, z) Generates a rotation matrix that rotates from the zaxis (0, 0, 1) to an other position in Cartesian space.
Parameters: x, y, z : floats,
position in Cartesian space.
Returns: R : array, shape (3 x 3)
Rotation matrix.
rotation_matrix_100_to_theta_phi¶

dmipy.utils.utils.
rotation_matrix_100_to_theta_phi
(theta, phi) Generates a rotation matrix that rotates from the xaxis (1, 0, 0) to an other position on the unit sphere.
Parameters: theta : float,
inclination of polar angle of main angle mu [0, pi].
phi : float,
polar angle of main angle mu [pi, pi].
Returns: R : array, shape (3 x 3)
Rotation matrix.
rotation_matrix_100_to_theta_phi_psi¶

dmipy.utils.utils.
rotation_matrix_100_to_theta_phi_psi
(theta, phi, psi) Generates a rotation matrix that rotates from the xaxis (1, 0, 0) to an other position in Cartesian space, and rotates about its axis.
Parameters: theta : float,
inclination of polar angle of main angle mu [0, pi].
phi : float,
polar angle of main angle mu [pi, pi].
psi : float,
angle in radians of the bingham distribution around mu [0, pi].
Returns: R : array, shape (3 x 3)
Rotation matrix.
rotation_matrix_100_to_xyz¶

dmipy.utils.utils.
rotation_matrix_100_to_xyz
(x, y, z) Generates a rotation matrix that rotates from the xaxis (1, 0, 0) to an other position in Cartesian space.
Parameters: x, y, z : floats,
position in Cartesian space.
Returns: R : array, shape (3 x 3)
Rotation matrix.
rotation_matrix_around_100¶

dmipy.utils.utils.
rotation_matrix_around_100
(psi) Generates a rotation matrix that rotates around the xaxis (1, 0, 0).
Parameters: psi : float,
euler angle [0, pi].
Returns: R : array, shape (3 x 3)
Rotation matrix.
sphere2cart¶

dmipy.utils.utils.
sphere2cart
(spherical_coordinates) “Function to estimate cartesian coordinates from spherical coordinates according to wikipedia. Conforms with the dipy notation.
Parameters: spherical_coordinates : array of size (3) or (N x 3),
array of spherical coordinate vectors [r, theta, phi]. range of theta [0, pi]. range of phi [pi, pi].
Returns: cartesian_coordinates : array of size (3) or (N x 3),
array of cartesian coordinate vectors [x, y, z].
unitsphere2cart_1d¶

dmipy.utils.utils.
unitsphere2cart_1d
(mu) Optimized function dedicated to convert 1D unit sphere coordinates to cartesian coordinates.
Parameters: mu : array of size (2)
unit sphere coordinates, as theta, phi = mu
Returns: mu_cart, array of size (3) :
mu in cartesian coordinates, as x, y, z = mu_cart
unitsphere2cart_Nd¶

dmipy.utils.utils.
unitsphere2cart_Nd
(mu) Optimized function deicated to convert 1D unit sphere coordinates to cartesian coordinates.
Parameters: mu : Nd array of size (…, 2)
unit sphere coordinates, as theta, phi = mu
Returns: mu_cart, Nd array of size (…, 3) :
mu in cartesian coordinates, as x, y, z = mu_cart