Simulators API¶
Exact signatures for acquisition schemes, compartments, mixtures, priors, and noise models. Read the simulator guide first, or open the component example.
Acquisition schemes¶
acquisition_scheme
dataclass
¶
acquisition_scheme(bvals: Array, bvecs: Array, delta: ArrayLike = (lambda: 0.0106)(), Delta: ArrayLike = (lambda: 0.0431)())
Bases: AcquisitionScheme
A class representing a diffusion MRI acquisition scheme.
This class encapsulates the parameters needed to define a diffusion MRI acquisition, including b-values, gradient directions, and timing parameters.
Attributes:
| Name | Type | Description |
|---|---|---|
bvals |
ArrayLike
|
Array of b-values in s/mm^2, representing the diffusion weighting. |
bvecs |
ArrayLike
|
Array of 3D unit vectors representing gradient directions. |
delta |
ArrayLike
|
Time between the start of the diffusion encoding and the first gradient pulse in seconds. |
Delta |
ArrayLike
|
Time between the start of the diffusion encoding and the second gradient pulse in seconds. |
qvals
property
¶
Calculate the q-values for the acquisition scheme.
Returns:
| Name | Type | Description |
|---|---|---|
ArrayLike |
ArrayLike
|
Array of q-values in 1/mm, calculated from b-values and Delta. |
tau
property
¶
Calculate the effective diffusion time tau.
Returns:
| Name | Type | Description |
|---|---|---|
ArrayLike |
ArrayLike
|
Array of effective diffusion times in seconds. |
gradient_strengths
property
¶
Calculate the gradient strengths required for the acquisition scheme.
Returns:
| Name | Type | Description |
|---|---|---|
ArrayLike |
ArrayLike
|
Array of gradient strengths in T/m. |
from_gradient_strengths
classmethod
¶
from_gradient_strengths(gradient_strengths: ArrayLike, gradient_directions: ArrayLike, delta: ArrayLike, Delta: ArrayLike) -> acquisition_scheme
Create an acquisition scheme from gradient parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gradient_strengths
|
ArrayLike
|
Gradient strengths in T/m (typically 0.003-0.008 T/m, can reach 0.03-0.1 T/m in animal scanners). |
required |
gradient_directions
|
ArrayLike
|
Gradient directions as 3D unit vectors. |
required |
delta
|
ArrayLike
|
Time between the start of the diffusion encoding and the first gradient pulse. |
required |
Delta
|
ArrayLike
|
Time between the start of the diffusion encoding and the second gradient pulse. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
acquisition_scheme |
acquisition_scheme
|
A new acquisition scheme instance. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If Delta is not greater than delta, or if gradient strengths and directions have mismatched shapes, or if gradient directions are not 3D unit vectors. |
ssfp_acquisition_scheme
dataclass
¶
ssfp_acquisition_scheme(bvecs: Array, T1_raw: ArrayLike, T2_raw: ArrayLike, B1: ArrayLike, diffGradAmps_raw: ArrayLike, flipAngles_raw: ArrayLike = (lambda: 14.0)(), TRs: ArrayLike = (lambda: 0.021)(), diffGradDur: ArrayLike = (lambda: 0.01016)(), delta: ArrayLike = (lambda: 0.0106)(), Delta: ArrayLike = (lambda: 0.008)(), gyromag_ratio: ArrayLike = (lambda: 4258 * 2 * pi)())
Bases: AcquisitionScheme
Steady-State Free Precession (SSFP) acquisition description.
Parameters are stored in common MR units and converted as properties:
bvecs: diffusion gradient unit vectors.TRs: repetition times [s].flipAngles_raw: flip angles [deg] (propertyflipAnglesyields radians).diffGradAmps_raw: diffusion gradient amplitudes [T/m] (propertydiffGradAmpsyields G/mm).diffGradDur: diffusion gradient durations [s].B1: transmit field scaling, unitless.T1_raw/T2_raw: relaxation times [ms] (propertiesT1/T2yield seconds).delta/Delta: diffusion pulse duration and separation [s].
Derived quantities:
sa,ca: \(\sin(\alpha B_1)\), \(\cos(\alpha B_1)\) with \(\alpha\) in radians.E1,E2: relaxation terms \(\exp(-\mathrm{TR}/T_1)\), \(\exp(-\mathrm{TR}/T_2)\).qvals: \(q = \gamma \, G \, \delta\) [1/mm] usinggyromag_ratioin rad/ms/mT.bvals: \(b = q^2 \, 4\pi^2 \, \Delta\).
Abstract simulator classes¶
Compartment
¶
Bases: ABC
to_theta
abstractmethod
classmethod
¶
Transforms the natural parameters to the optimization parameters which are assumed to be normally distributed.
to_params
abstractmethod
classmethod
¶
Transforms the optimization parameters to the natural parameters.
from_theta
classmethod
¶
from_theta(theta: ArrayLike, **kwargs) -> Compartment
Creates a compartment from the optimization parameters.
tree_flatten
¶
Flattens the compartment into a list of children and auxiliary data.
tree_unflatten
classmethod
¶
tree_unflatten(aux_data: Any, children: list) -> Compartment
Reconstructs the compartment from the list of children and auxiliary data.
SignalCompartment
¶
Bases: Compartment
signal_fn
classmethod
¶
signal_fn(acq: acquisition_scheme, *args, **kwargs) -> ArrayLike
Computes the signal for the compartment.
log_signal_fn
abstractmethod
classmethod
¶
log_signal_fn(acq: acquisition_scheme, *args, **kwargs) -> ArrayLike
Computes the log-signal for the compartment.
signal
¶
signal(acq: acquisition_scheme, rng=None) -> ArrayLike
Simulates the signal for the compartment.
log_signal
¶
log_signal(acq: acquisition_scheme, rng=None) -> ArrayLike
Simulates the log-signal for the compartment.
fit
¶
Fits the compartment to the signal deterministically.
NoiseCompartment
¶
Bases: Compartment
signal_response_kernels
¶
StickKernel
¶
Bases: SignalKernel
kernel_fn
classmethod
¶
kernel_fn(acq: acquisition_scheme, mu: ArrayLike, lam_par: float, rng=None) -> ArrayLike
Compute the log signal for given b-values and b-vectors.
to_params
classmethod
¶
Convert the parameter space theta to the lambda value.
to_theta
classmethod
¶
Convert the lambda value to the parameter space theta.
ZeppelinKernel
¶
Bases: SignalKernel
kernel_fn
classmethod
¶
kernel_fn(acq: acquisition_scheme, mu: ArrayLike, lam_perp: float, lam_par: float, rng=None) -> ArrayLike
Signal for the given b-values and b-vectors.
to_params
classmethod
¶
Convert the parameter space theta to the lambda value.
to_theta
classmethod
¶
Convert the lambda value to the parameter space theta.
NODDIKernel
¶
Bases: SignalKernel
kernel_fn
classmethod
¶
kernel_fn(acq: acquisition_scheme, mu: ArrayLike, fraction, lam_perp, lam_par, rng=None) -> ArrayLike
Compute the log signal for given b-values and b-vectors.
to_params
classmethod
¶
Convert the parameter space theta to the lambda value.
to_theta
classmethod
¶
Convert the lambda value to the parameter space theta.
SimpleSANDIKernel
¶
Bases: SignalKernel
kernel_fn
classmethod
¶
kernel_fn(acq: acquisition_scheme, mu: ArrayLike, fraction_in, fraction_ec, lam_par_in, lam_perp_ex, lam_par_ex, rng=None) -> ArrayLike
Compute the log signal for given b-values and b-vectors.
to_theta
classmethod
¶
MultiCompartment
¶
MultiCompartment(model_fractions: ArrayLike, model_compartments: list, noise_compartments: list, model_mask: ArrayLike | None = None, shared_parameter: SharedParameterState | None = None)
Bases: SignalCompartment
Composable mixture of signal compartments with optional shared parameters.
A MultiCompartment turns a set of signal compartments :math:S_k(b, \mathbf{g})
and fractions :math:f_k into a single signal
.. math::
S(b, \mathbf{g}) = \sum_k f_k \; S_k(b, \mathbf{g})
Noise compartments can be added on top through noise_types. The class exposes
to_theta / from_theta so priors over fractions, shared diffusivities and
per-compartment parameters stay Gaussian in optimization space.
References¶
- Stejskal & Tanner, 1965. Spin diffusion measurements: spin echoes in the presence of a time‐dependent field gradient.
- Behrens et al., 2003. Characterization and propagation of uncertainty in diffusion-weighted MR imaging.
signal_fn
classmethod
¶
signal_fn(acq: acquisition_scheme, model_compartments, noise_compartments, model_fractions, model_mask, shared_parameter, rng=None)
to_theta
classmethod
¶
to_theta(model_fractions: ArrayLike, model_compartments: list, noise_compartments: list, model_mask: ArrayLike | None = None, shared_parameter: SharedParameterState | None = None)
Local signal models¶
A selection of voxel-wise dMRI signal compartments is implemented below.
Isotropic compartments¶
Ball
¶
Bases: SignalCompartment
Isotropic Gaussian diffusion (free water).
Signal follows the Stejskal–Tanner form
.. math:: S(b) = \exp(-b\,\lambda),
with scalar diffusivity :math:\lambda \in [0, 10^{-2}]\,\mathrm{mm}^2/\mathrm{s}
(Stejskal & Tanner, 1965).
Initialize the Ball model with a lambda value.
log_signal_fn
classmethod
¶
log_signal_fn(acq: acquisition_scheme, lam: float, rng=None) -> ArrayLike
Computes the log-signal for the ball compartment.
to_params
classmethod
¶
Convert the parameter space theta to the lambda value.
to_theta
classmethod
¶
Convert the lambda value to the parameter space theta.
fit
¶
Fit the Ball model to the log signal and b-values.
StaticBall
¶
Bases: Ball
The StaticBall model is a Ball with a fixed lambda value. The lam parameter is shared from a global parameter state as a class attribute.
Initialize the StaticBall model. The lam parameter is a class attribute and not passed to the constructor.
to_theta
classmethod
¶
Convert to the parameter space theta. Since there are no learnable parameters, return an empty array.
to_params
classmethod
¶
Convert the parameter space theta to parameters. Since there are no learnable parameters, return an empty tuple.
from_global_params
classmethod
¶
from_global_params(params: ArrayLike, idx: list[int]) -> StaticBall
log_signal_fn
classmethod
¶
log_signal_fn(acq: acquisition_scheme, rng=None) -> ArrayLike
Computes the log-signal for the ball compartment.
MultiShellBall
¶
Bases: Ball
The MultiShellBall model is a Ball with multiple lambda values. The lam parameter is shared from a global parameter state as a class attribute.
Initialize the MultiShellBall model. The lam parameter is a class attribute and not passed to the constructor.
log_signal_fn
classmethod
¶
log_signal_fn(acq: acquisition_scheme, lam: float, lam_std: float, rng=None) -> ArrayLike
Computes the log-signal for the ball compartment with uncertainty.
to_theta
classmethod
¶
Convert to the parameter space theta. Since there are no learnable parameters, return an empty array.
to_params
classmethod
¶
Convert the parameter space theta to parameters. Since there are no learnable parameters, return an empty tuple.
MultiShellStaticBall
¶
Bases: MultiShellBall
The MultiShellBall model is a Ball with multiple lambda values. The lam parameter is shared from a global parameter state as a class attribute.
from_global_params
classmethod
¶
from_global_params(params: ArrayLike, idx: list[int]) -> StaticBall
to_theta
classmethod
¶
Convert to the parameter space theta. Since there are no learnable parameters, return an empty array.
to_params
classmethod
¶
Convert the parameter space theta to parameters. Since there are no learnable parameters, return an empty tuple.
log_signal_fn
classmethod
¶
log_signal_fn(acq: acquisition_scheme, rng=None) -> ArrayLike
Computes the log-signal for the ball compartment.
SSFPBall
¶
Bases: SignalCompartment
The SSFPBall model is a Ball with a fixed lambda value. The lam parameter is shared from a global parameter state as a class attribute.
signal_fn
classmethod
¶
signal_fn(acq: ssfp_acquisition_scheme, lam: float, rng=None) -> ArrayLike
Computes the signal for the ball compartment.
log_signal_fn
classmethod
¶
log_signal_fn(acq: ssfp_acquisition_scheme, lam: float, rng=None) -> ArrayLike
Computes the log-signal for the ball compartment.
to_theta
classmethod
¶
Convert to the parameter space theta. Since there are no learnable parameters, return an empty array.
to_params
classmethod
¶
Convert the parameter space theta to parameters. Since there are no learnable parameters, return an empty tuple.
SSFPStaticBall
¶
Bases: SSFPBall
The SSFPStaticBall model is a SSFPBall with a fixed lambda value. The lam parameter is shared from a global parameter state as a class attribute.
from_global_params
classmethod
¶
from_global_params(params: ArrayLike, idx: list[int]) -> StaticBall
Create a StaticBall from a global theta value.
to_theta
classmethod
¶
Convert to the parameter space theta. Since there are no learnable parameters, return an empty array.
to_params
classmethod
¶
Convert the parameter space theta to parameters. Since there are no learnable parameters, return an empty tuple.
signal_fn
classmethod
¶
signal_fn(acq: ssfp_acquisition_scheme, rng=None) -> ArrayLike
Computes the signal for the ball compartment.
log_signal_fn
classmethod
¶
log_signal_fn(acq: ssfp_acquisition_scheme, rng=None) -> ArrayLike
Computes the log-signal for the ball compartment.
Sphere
¶
Bases: SignalCompartment
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 q-value.
Parameters¶
diameter : float, sphere diameter in meters.
References¶
.. [1] Balinov, Balin, et al. "The NMR self-diffusion 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): 17-25.
Anisotropic compartments¶
Zeppelin
¶
Bases: SignalCompartment
Axially symmetric Gaussian tensor (:math:\lambda_{\parallel}, \lambda_{\perp}).
Signal:
.. math:: S(b, \mathbf{g}) = \exp\Big(-b \big[\lambda_{\perp} + (\lambda_{\parallel}-\lambda_{\perp})(\mathbf{g}\cdot\boldsymbol{\mu})^2\big]\Big),
often used for extra-axonal water (Basser et al., 1994).
Initialize the Zeppelin model with orientation and diffusivity parameters.
log_signal_fn
classmethod
¶
log_signal_fn(acq: acquisition_scheme, mu: ArrayLike, lambda_par: float, lambda_perp: float, rng=None) -> ArrayLike
Compute the log signal for given b-values and b-vectors.
to_theta
classmethod
¶
Convert the parameters to the parameter space theta.
to_params
classmethod
¶
Convert the parameter space theta to the model parameters.
fit
¶
Fit the Zeppelin model to the log signal, b-values, and b-vectors.
StaticZeppelin
¶
Cylinder
¶
Bases: SignalCompartment
The Stejskal-Tanner approximation of a finite-radius cylinder (Callaghan, 1991).
Assumes rectangular pulses and :math:\Delta \gg \delta.
NOTE: This model assumes that the gradient pulses are rectangular and that the diffusion time is much larger than the pulse duration and available in the acquisition scheme.
WatsonZeppelin
¶
BinghamZeppelin
¶
Stick
¶
Bases: SignalCompartment
Zero-radius cylinder aligned with unit vector :math:\boldsymbol{\mu}.
Signal:
.. math:: S(b, \mathbf{g}) = \exp\big(-b\,\lambda_{\parallel} (\mathbf{g}\cdot\boldsymbol{\mu})^2\big),
capturing fully anisotropic diffusion along the fiber (Behrens et al., 2003).
Initialize the Stick model with a lambda value and eigenvector.
log_signal_fn
classmethod
¶
Compute the log signal for given b-values and b-vectors.
to_theta
classmethod
¶
Convert the parameters to the parameter space theta.
to_params
classmethod
¶
Convert the parameter space theta to the lambda value and eigenvector.
fit
¶
Fit the Stick model to the log signal, b-values, and b-vectors.
StaticStick
¶
Bases: Stick
The StaticStick model is a Stick with a fixed lambda value. The lam_par parameter is shared from a global parameter state as a class attribute, while the mu parameter remains learnable.
Initialize the StaticStick model with a mu value. The lam_par parameter is a class attribute and not passed to the constructor.
to_theta
classmethod
¶
Convert only the mu parameter to the parameter space theta. The lam_par parameter is a class attribute and not included in theta.
to_params
classmethod
¶
Convert the parameter space theta to the mu value. The lam_par parameter is a class attribute and not included in theta.
from_global_params
classmethod
¶
log_signal_fn
classmethod
¶
Compute the log signal for given b-values and b-vectors.
Parameters¶
acq : acquisition_scheme The acquisition scheme containing b-values and b-vectors mu : ArrayLike The orientation of the stick in spherical coordinates rng : jax.random.key, optional Random number generator key, by default None
Returns¶
ArrayLike The log signal
MultiShellStick
¶
Bases: Stick
The MultiShellStick model is a Stick with a fixed lambda value. The lam_par parameter is shared from a global parameter state as a class attribute, while the mu parameter remains learnable.
Initialize the MultiShellStick model with a mu value, lam_par, and lam_par_std.
log_signal_fn
classmethod
¶
log_signal_fn(acq: acquisition_scheme, mu: ArrayLike, lam_par: float, lam_par_std: float, rng=None) -> ArrayLike
Compute the log signal for given b-values and b-vectors.
Parameters¶
acq : acquisition_scheme The acquisition scheme containing b-values and b-vectors
to_theta
classmethod
¶
Convert the parameters to the parameter space theta.
to_params
classmethod
¶
Convert the parameter space theta to the lambda value and eigenvector.
MultiShellStaticStick
¶
Bases: MultiShellStick
The MultiShellStaticStick model is a Stick with a fixed lambda value. The lam_par parameter is shared from a global parameter state as a class attribute, while the mu parameter remains learnable.
Initialize the MultiShellStaticStick model with a mu value.
to_theta
classmethod
¶
Convert only the mu parameter to the parameter space theta. The lam_par parameter is a class attribute and not included in theta.
to_params
classmethod
¶
Convert the parameter space theta to the mu value. The lam_par parameter is a class attribute and not included in theta.
from_global_params
classmethod
¶
Create a MultiShellStaticStick from a global theta value.
Parameters¶
theta : ArrayLike The global parameter array idx : list[int] Indices in the global parameter array that correspond to this model's parameters
Returns¶
MultiShellStaticStick A MultiShellStaticStick instance with parameters extracted from the global theta
log_signal_fn
classmethod
¶
Compute the log signal for given b-values and b-vectors.
Parameters¶
acq : acquisition_scheme The acquisition scheme containing b-values and b-vectors mu : ArrayLike The orientation of the stick in spherical coordinates rng : jax.random.key, optional Random number generator key, by default None
Returns¶
ArrayLike The log signal
SSFPStick
¶
Bases: Stick
The SSFPStick model is a Stick with a fixed lambda value. The lam_par parameter is shared from a global parameter state as a class attribute, while the mu parameter remains learnable.
SSFPStaticStick
¶
Bases: SSFPStick
The SSFPStaticStick model is a SSFPStick with a fixed lambda value. The lam_par parameter is shared from a global parameter state as a class attribute.
from_global_params
classmethod
¶
Create a SSFPStaticStick from a global theta value.
to_theta
classmethod
¶
Convert only the mu parameter to the parameter space theta. The lam_par parameter is a class attribute and not included in theta.
to_params
classmethod
¶
Convert the parameter space theta to the mu value. The lam_par parameter is a class attribute and not included in theta.
signal_fn
classmethod
¶
Compute the signal for given b-values and b-vectors.
log_signal_fn
classmethod
¶
Compute the log signal for given b-values and b-vectors.
WatsonStick
¶
BinghamStick
¶
Dot
¶
Bases: SignalCompartment
The Dot model is a simple model that represents a single point in space. It has no parameters and the signal is constant across all b-values and b-vectors. It represent trapped water molecules in the tissue.
Dti
¶
Bases: SignalCompartment
The Diffusion Tensor Imaging (DTI) model represents the diffusion of water molecules in the brain. It is a simple model that assumes Gaussian diffusion.
Initialize the DTI model with a diffusion tensor D.
log_signal_fn
classmethod
¶
Compute the log signal for given b-values and b-vectors.
to_theta
classmethod
¶
Convert the diffusion tensor D to the parameter space theta.
to_params
classmethod
¶
Convert the parameter space theta to the diffusion tensor D.
fit
¶
Fit the DTI model to the log signal, b-values, and b-vectors.
Spherical convolution based simulators¶
These compartments convolve a kernel with a fiber orientation distribution (FOD)
on the sphere. The shared base classes live in dmri.simulators.convolved_models.
convolved_models
¶
SignalKernel
¶
Bases: Compartment
kernel_fn
abstractmethod
classmethod
¶
kernel_fn(mu: ArrayLike, acq: acquisition_scheme, **kwargs) -> Array
ConvolvedSignalCompartment
¶
Bases: SignalCompartment
signal_fn
classmethod
¶
signal_fn(acq: acquisition_scheme, fod, signal_kernel, rng=None) -> ArrayLike
Compute the log signal for given b-values and b-vectors.
NoddiW
¶
NoddiB
¶
SandiW
¶
SandiB
¶
Spherical distributions¶
Orientation distributions (FODs, Watson, Bingham, ...) used by convolved compartments and as orientation priors.
sphereical_distributions
¶
hemisphere_default
module-attribute
¶
hemisphere_default = HemiSphere(phi=sphere_default.phi, theta=sphere_default.theta)
bigger_hemisphere
module-attribute
¶
bigger_hemisphere = HemiSphere(phi=big_sphere.phi, theta=big_sphere.theta)
SphericalDistribution
¶
Bases: Compartment
sh_coeff
¶
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.
viz
¶
viz(plot_type='fod', sphere=None, n_samples=1000, ax=None, color=None, cmap=None, levels=3, alpha=None)
Visualize the spherical distribution model on the sphere.
Parameters¶
plot_type : str, optional Type of plot to generate. Options are: - "polar": Plot in polar coordinates (theta, phi) - "cartesian": Plot in Cartesian coordinates (x, y, z) - "fod": Plot as a fiber orientation distribution sphere : object, optional Sphere object for vertices (used in cartesian plot) n_samples : int, optional Number of samples to generate ax : matplotlib.axes.Axes, optional Matplotlib axis to plot on color : str, optional Colormap to use levels : int, optional Number of contour levels for polar plot alpha : float, optional Transparency of the surface for FOD plot
Returns¶
matplotlib.axes.Axes The matplotlib axis containing the plot
to_pmf
¶
Convert the continuous distribution to a discrete probability mass function.
Parameters¶
sphere : object, optional Sphere object for vertices n_samples : int, optional Number of samples to generate
Returns¶
tuple (vertices, probabilities) where vertices are the sphere points and probabilities are the corresponding PMF values
Uniform
¶
SymmetricDirac
¶
TensorFOD
¶
Tensor2dFOD
¶
MixtureOfFODs
¶
Bases: SphericalDistribution
Watson
¶
Bases: SphericalDistribution
The Watson spherical distribution model [1]_ [2]_.
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¶
.. [1] Kaden et al. "Parametric spherical deconvolution: inferring anatomical connectivity using diffusion MR imaging". NeuroImage (2007) .. [2] Zhang et al. "NODDI: practical in vivo neurite orientation dispersion and density imaging of the human brain". NeuroImage (2012)
Bingham
¶
Bases: SphericalDistribution
sample_watson_ar_1
¶
Draw a single sample from Watson(mu, kappa) on the unit sphere using acceptance-rejection from the uniform distribution on S^{d-1}.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
a jax.random.PRNGKey |
required | |
mu
|
a jnp.ndarray of shape (d,) — will be normalized internally |
required | |
kappa
|
a nonnegative float (concentration parameter) |
required |
Returns: A jnp.ndarray of shape (d,) lying on the unit sphere, distributed ~ Watson(mu,kappa).
diffusion_tensor2d_odf
¶
Compute the ODF for a single diffusion tensor at directions dirs.
Handles the degenerate case, where the last eigenvalue is 0, by
restricting the evaluation to the plane spanned by the first two eigenvectors.
For directions falling outside the plane, returns 0.
sample_single_from_odf_jax
¶
Sample a single unit direction from the ODF defined by the diffusion tensor using naive rejection sampling in JAX, implemented with jax.lax.while_loop. Parameters
evals : array-like, shape (3,) Eigenvalues of the diffusion tensor (assumed positive). evecs : array-like, shape (3, 3) Eigenvectors of the diffusion tensor (columns = eigenvectors). rng : jax.random.PRNGKey Random key for JAX. max_iter : int, optional Maximum proposals for rejection sampling. Returns
direction : jnp.ndarray, shape (3,) A single sampled unit direction, or None (a Python object) if rejected in all attempts.
sample_single_from_odf_jax_degenerate
¶
Sample a direction from the ODF of a 'degenerate' diffusion tensor with eigenvalues [lambda1, lambda2, 0] using naive rejection sampling in the plane of nonzero diffusion. Parameters
evals : array-like of shape (3,) Eigenvalues of the diffusion tensor. We assume evals[2] == 0 and evals[0], evals[1] > 0 (ordered or not). evecs : array-like of shape (3,3) Eigenvectors (columns) of the diffusion tensor. evecs[:,2] is the direction corresponding to the zero eigenvalue. rng : jax.random.PRNGKey Random key for JAX. max_iter : int, optional Maximum proposals for rejection sampling in the plane. Returns
direction : jnp.ndarray of shape (3,) A sampled unit direction in the plane spanned by the two nonzero eigenvalues, or None (Python object) if rejected in all attempts.
diffusion_tensor_odf
¶
Compute the ODF for a single diffusion tensor at directions dirs.
odi2kappa
¶
Calculates concentration (kappa) from orientation dispersion index (odi).
get_sh_order_from_odi
¶
Returns minimum sh_order to estimate spherical harmonics for given odi.
inverse_sh_matrix
cached
¶
Returns the inverse of the spherical harmonics basis matrix.
deterministic_sphere_integration
¶
Use a 2D trapezoidal rule in spherical coords to approximate ∫ exp(kappa (n·mu)^2 + beta (n·mu_beta)^2 ) dΩ(n).
sample_sphere
¶
Generate n_samples random unit vectors on S^2 by sampling Normal(0,1) in 3D and normalizing. Returns shape (n_samples, 3).
Predefined model collections¶
Ready-made MultiCompartment families mirroring common literature mixtures
(Ball–Stick, Ball–3-Stick, multi-shell variants, ...).
models
¶
Predefined multi-compartment model collections.
These convenience classes mirror common mixtures from the literature such as
Ball–Stick (Behrens et al., 2003), Ball–Stick–Zeppelin, and multi-shell variants
with shared diffusivity priors. Each class specifies the underlying
MultiCompartment ingredients: signal compartments, noise compartments, and
Dirichlet priors over fractions.
BallStickSharedDiffusivity
¶
BallStickSharedDiffusivity(model_fractions: ArrayLike, model_compartments: list, noise_compartments: list, model_mask: ArrayLike | None = None, shared_parameter: SharedParameterState | None = None)
Bases: MultiCompartment
shared_parameter_type
class-attribute
instance-attribute
¶
BallStickSharedDiffusivity2
¶
BallStickSharedDiffusivity2(model_fractions: ArrayLike, model_compartments: list, noise_compartments: list, model_mask: ArrayLike | None = None, shared_parameter: SharedParameterState | None = None)
Bases: MultiCompartment
shared_parameter_type
class-attribute
instance-attribute
¶
Ball3StickSharedDiffusivity
¶
Ball3StickSharedDiffusivity(model_fractions: ArrayLike, model_compartments: list, noise_compartments: list, model_mask: ArrayLike | None = None, shared_parameter: SharedParameterState | None = None)
Bases: MultiCompartment
model_types
class-attribute
instance-attribute
¶
model_types = [StaticBall, StaticStick, StaticStick, StaticStick]
fraction_prior
class-attribute
instance-attribute
¶
shared_parameter_type
class-attribute
instance-attribute
¶
Ball3StickSharedDiffusivityTotalParamPenalizedPrior
¶
Ball3StickSharedDiffusivityTotalParamPenalizedPrior(model_fractions: ArrayLike, model_compartments: list, noise_compartments: list, model_mask: ArrayLike | None = None, shared_parameter: SharedParameterState | None = None)
Bases: MultiCompartment
model_types
class-attribute
instance-attribute
¶
model_types = [StaticBall, StaticStick, StaticStick, StaticStick]
fraction_prior
class-attribute
instance-attribute
¶
shared_parameter_type
class-attribute
instance-attribute
¶
SSFPBall3StickSharedDiffusivity
¶
SSFPBall3StickSharedDiffusivity(model_fractions: ArrayLike, model_compartments: list, noise_compartments: list, model_mask: ArrayLike | None = None, shared_parameter: SharedParameterState | None = None)
Bases: MultiCompartment
model_types
class-attribute
instance-attribute
¶
model_types = [SSFPStaticBall, SSFPStaticStick, SSFPStaticStick, SSFPStaticStick]
fraction_prior
class-attribute
instance-attribute
¶
shared_parameter_type
class-attribute
instance-attribute
¶
SSFPBall3StickSharedDiffusivityBetterNorm
¶
SSFPBall3StickSharedDiffusivityBetterNorm(model_fractions: ArrayLike, model_compartments: list, noise_compartments: list, model_mask: ArrayLike | None = None, shared_parameter: SharedParameterState | None = None)
Bases: MultiCompartment
model_types
class-attribute
instance-attribute
¶
model_types = [SSFPStaticBall, SSFPStaticStick, SSFPStaticStick, SSFPStaticStick]
fraction_prior
class-attribute
instance-attribute
¶
shared_parameter_type
class-attribute
instance-attribute
¶
Ball3StickSharedDiffusivityUniformFraction
¶
Ball3StickSharedDiffusivityUniformFraction(model_fractions: ArrayLike, model_compartments: list, noise_compartments: list, model_mask: ArrayLike | None = None, shared_parameter: SharedParameterState | None = None)
Bases: MultiCompartment
model_types
class-attribute
instance-attribute
¶
model_types = [StaticBall, StaticStick, StaticStick, StaticStick]
shared_parameter_type
class-attribute
instance-attribute
¶
MultiShellBall3StickSharedDiffusivity
¶
MultiShellBall3StickSharedDiffusivity(model_fractions: ArrayLike, model_compartments: list, noise_compartments: list, model_mask: ArrayLike | None = None, shared_parameter: SharedParameterState | None = None)
Bases: MultiCompartment
model_types
class-attribute
instance-attribute
¶
model_types = [MultiShellStaticBall, MultiShellStaticStick, MultiShellStaticStick, MultiShellStaticStick]
fraction_prior
class-attribute
instance-attribute
¶
shared_parameter_type
class-attribute
instance-attribute
¶
MultiShellBall3StickSharedDiffusivityUniformFraction
¶
MultiShellBall3StickSharedDiffusivityUniformFraction(model_fractions: ArrayLike, model_compartments: list, noise_compartments: list, model_mask: ArrayLike | None = None, shared_parameter: SharedParameterState | None = None)
Bases: MultiCompartment
model_types
class-attribute
instance-attribute
¶
model_types = [MultiShellStaticBall, MultiShellStaticStick, MultiShellStaticStick, MultiShellStaticStick]
shared_parameter_type
class-attribute
instance-attribute
¶
MultiShellBall3StickSharedDiffusivityGammaPrior
¶
MultiShellBall3StickSharedDiffusivityGammaPrior(model_fractions: ArrayLike, model_compartments: list, noise_compartments: list, model_mask: ArrayLike | None = None, shared_parameter: SharedParameterState | None = None)
Bases: MultiCompartment
model_types
class-attribute
instance-attribute
¶
model_types = [MultiShellStaticBall, MultiShellStaticStick, MultiShellStaticStick, MultiShellStaticStick]
fraction_prior
class-attribute
instance-attribute
¶
shared_parameter_type
class-attribute
instance-attribute
¶
BallStick
¶
Ball2Stick
¶
Ball3Stick
¶
Ball3StickNoise
¶
Ball3StickNoise(model_fractions: ArrayLike, model_compartments: list, noise_compartments: list, model_mask: ArrayLike | None = None, shared_parameter: SharedParameterState | None = None)
Bases: MultiCompartment
noise_types
class-attribute
instance-attribute
¶
noise_types = [RicianNoiseSNR310, RicianNoiseSNR1020]
BallStickZeppelinNoise
¶
BallStickZeppelinNoise(model_fractions: ArrayLike, model_compartments: list, noise_compartments: list, model_mask: ArrayLike | None = None, shared_parameter: SharedParameterState | None = None)
Bases: MultiCompartment
noise_types
class-attribute
instance-attribute
¶
noise_types = [RicianNoiseSNR310, RicianNoiseSNR1020]
Ball2Stick2Zeppelin2Dti
¶
Ball3Stick3ZeppelinNoise
¶
Ball3Stick3ZeppelinNoise(model_fractions: ArrayLike, model_compartments: list, noise_compartments: list, model_mask: ArrayLike | None = None, shared_parameter: SharedParameterState | None = None)
Bases: MultiCompartment
model_types
class-attribute
instance-attribute
¶
noise_types
class-attribute
instance-attribute
¶
noise_types = [RicianNoiseSNR310, RicianNoiseSNR1020]
AllGaussianModels
¶
AllGaussianModels(model_fractions: ArrayLike, model_compartments: list, noise_compartments: list, model_mask: ArrayLike | None = None, shared_parameter: SharedParameterState | None = None)
Bases: MultiCompartment
model_types
class-attribute
instance-attribute
¶
noise_types
class-attribute
instance-attribute
¶
noise_types = [BoundedGaussianNoise, BoundedRicianNoise]
AllGaussianModelsParamCountPrior
¶
AllGaussianModelsParamCountPrior(model_fractions: ArrayLike, model_compartments: list, noise_compartments: list, model_mask: ArrayLike | None = None, shared_parameter: SharedParameterState | None = None)
Bases: MultiCompartment
model_types
class-attribute
instance-attribute
¶
noise_types
class-attribute
instance-attribute
¶
noise_types = [BoundedGaussianNoise, BoundedRicianNoise]
AllGaussianAndConvolvedModels
¶
AllGaussianAndConvolvedModels(model_fractions: ArrayLike, model_compartments: list, noise_compartments: list, model_mask: ArrayLike | None = None, shared_parameter: SharedParameterState | None = None)
Bases: MultiCompartment
model_types
class-attribute
instance-attribute
¶
model_types = [Ball] + 3 * [Stick] + 3 * [Zeppelin] + 3 * [Dti] + [Dot] + [WatsonStick] + [WatsonZeppelin] + [BinghamStick] + [BinghamZeppelin] + [NoddiB] + [NoddiW] + [SandiB] + [SandiW]
noise_types
class-attribute
instance-attribute
¶
noise_types = [BoundedGaussianNoise] + [BoundedRicianNoise]
Noise models¶
noise_compartments
¶
Noise models for diffusion MRI signals.
Implements bounded Rician and Gaussian noise commonly observed in magnitude MR images. The likelihoods follow:
.. math:: p(z \mid \nu, \sigma) = \frac{z}{\sigma^2} \exp\Big(-\tfrac{z^2+\nu^2}{2\sigma^2}\Big) I_0\Big(\tfrac{z\nu}{\sigma^2}\Big)
with :math:I_0 the modified Bessel function (Gudbjartsson & Patz, 1995). SNR
priors are kept in bounded ranges for numerical stability.
RicianNoise
¶
Bases: NoiseCompartment
GaussianNoise
¶
Bases: NoiseCompartment
BoundedRicianNoise
¶
Bases: RicianNoise
BoundedGaussianNoise
¶
Bases: GaussianNoise
RicianNoiseSNR7080
¶
Bases: BoundedRicianNoise
RicianNoiseSNR6070
¶
Bases: BoundedRicianNoise
RicianNoiseSNR5060
¶
Bases: BoundedRicianNoise
RicianNoiseSNR4050
¶
Bases: BoundedRicianNoise
RicianNoiseSNR3040
¶
Bases: BoundedRicianNoise
RicianNoiseSNR2030
¶
Bases: BoundedRicianNoise
RicianNoiseSNR1020
¶
Bases: BoundedRicianNoise
RicianNoiseSNR310
¶
Bases: BoundedRicianNoise
GaussianNoiseSNR7080
¶
Bases: BoundedGaussianNoise
GaussianNoiseSNR6070
¶
Bases: BoundedGaussianNoise
GaussianNoiseSNR5060
¶
Bases: BoundedGaussianNoise
GaussianNoiseSNR4050
¶
Bases: BoundedGaussianNoise
GaussianNoiseSNR3040
¶
Bases: BoundedGaussianNoise
GaussianNoiseSNR2030
¶
Bases: BoundedGaussianNoise
GaussianNoiseSNR1020
¶
Bases: BoundedGaussianNoise
GaussianNoiseSNR310
¶
Bases: BoundedGaussianNoise
add_rician_noise
¶
Adds Rician noise to an MRI signal.
NOTE: The noise follows a Rician distribution when the signal-to-noise ratio (SNR) is moderate to high
Parameters: - signal: ndarray of the true signal magnitude (η) - sigma_g: standard deviation of the Gaussian noise (σ_g)
Returns: - noisy_signal: ndarray of the signal with added Rician noise
add_gaussian_noise
¶
Adds Gaussian noise to an MRI signal.
NOTE: Often used for simplicity, especially when modeling raw complex data or when SNR is high.
Parameters: - signal: ndarray of the true signal magnitude (η) - sigma_g: standard deviation of the Gaussian noise (σ_g)
Returns: - noisy_signal: ndarray of the signal with added Gaussian noise
add_noncentral_chi_noise
¶
Adds Non-Central Chi noise to an MRI signal.
Nature: Arises in multi-coil acquisition systems due to the combination of multiple complex signals.Characteristics: The noise distribution in the magnitude image follows a non-central Chi distribution. Degree of freedom depends on the number of coils used in parallel imaging. Implications: More complex than the Rician model and can complicate bias correction.
Parameters: - signal: ndarray of the true signal magnitude (η) - sigma_g: standard deviation of the Gaussian noise (σ_g) - num_coils: number of coils used in parallel imaging
Returns: - noisy_signal: ndarray of the signal with added Non-Central Chi noise
Mask priors¶
mask_prior
¶
Priors over which compartments are active in a multi-compartment model.
Implements Beta–Bernoulli style mask priors with utilities to sample masks and convert them into boolean vectors that gate compartments during simulation.
MaskPriorSample
dataclass
¶
MaskPrior
¶
Base class for hierarchical priors over simulator model masks.
sample
¶
sample(rng: KeyArray) -> MaskPriorSample
Sample hyperparameters and a mask conditioned on them.
log_prob
¶
Return log probability of a binary mask conditioned on hyperparameters.
prob
¶
Return probability of a binary mask conditioned on hyperparameters.
sample_model_mask
¶
Sample masks for model and noise components and concatenate them.
sample_noise_components
¶
Default noise prior: exactly one active component (if any exist).
log_prob_noise_components
¶
sample_model_components
¶
Override to draw model-component masks.
sample_hyperparameters
¶
Override to sample hyperparameters for the prior.
log_prob_model_components
¶
Override to evaluate log probability under the prior.
BetaBernoulliMaskPrior
¶
BetaBernoulliMaskPrior(num_model_components: int, num_noise_components: int, alpha: float = 1.0, beta: float = 1.0, min_active_models: int = 1)
BetaBernoulliParamCountScaledPrior
¶
BetaBernoulliParamCountScaledPrior(num_model_components: int, num_noise_components: int, num_model_parameters: list[int], *, gamma: float = 1.0, kappa: float = 2.0, p_alpha: float = 1.0, p_beta: float = 1.0, eps: float = 0.001)
TotalParamPenalizedPrior
¶
TotalParamPenalizedPrior(num_model_components: int, num_noise_components: int, num_model_parameters: list[int], *, p0: float = 0.5, u_alpha: float = 1.0, u_beta: float = 1.0, penalty_min: float = 0.0, penalty_max: float = 5.0, penalty_mode: str = 'linear', eps: float = 0.001)
Bases: MaskPrior
Global-complexity prior (scan) with fixed p0 and u∈[0,1] controlling penalty.
Conditionals
-
quadratic mode (default): logit P(z_i=1 | T) = logit(p0) - λ * (2*T*s_i + s_i**2) (global coupling via T; stricter as the model grows)
-
linear mode (AIC/BIC-like): logit P(z_i=1) = logit(p0) - λ * s_i (independent across components; fixed linear size penalty)
Hyperparameter
- u ~ Beta(u_alpha, u_beta), or pass a fixed u in [0,1] when calling.
- u=1 → no penalty (reverts to p0). u=0 → strongest penalty.
- We map u to a desired worst-case logit drop delta* and set
λ = delta* / scale_max,
where scale_max depends on the mode:
- quadratic: scale_max = max_i (2*S*s_i - s_i**2), S = sum_j s_j
- linear: scale_max = max_i s_i
MarkovMaskPrior
¶
MarkovMaskPrior(num_model_components: int, num_noise_components: int, transition_matrix: ArrayLike, start_prob: ArrayLike | None = None, walk_length: int | None = None)