synthbold.models¶
Physics signal modeling from synthesized geometries.
- class synthbold.models.BackgroundModel(mu_range: tuple[float, float], std_range: tuple[float, float], transforms: list[Transform] | None = None, transform_prob: float = 1.0, device: str = 'cpu', seed: int | None = None)¶
Bases:
ModelA model for generating synthetic background data from integer-labeled volume data.
This class allows creating randomized intensity maps based on a 4D label volume
(B, X, Y, Z). Each unique label in the input data is assigned a random mean mu and standard deviation std drawn from specified ranges. Voxel-wise values are sampled from a normal distribution. Background voxels (label 0; if exist) are ignored.- Parameters:
mu_range – Range of values to sample the mean intensity from.
std_range – Range of values to sample the standard deviation from.
transforms – List of transformations to apply.
transform_prob – Probability of applying each transform, evaluated independently per transform and per batch element.
device – Target compute device (“cuda” or “cpu”).
seed – Random seed for reproducibility.
- Raises:
ValueError – If std_range contains a negative value.
Notes
The generated background maps can be returned as a PyTorch tensor and saved to disk in ZARR or NIfTI format, with metadata automatically stored when using ZARR.
Examples
>>> data_tensor = torch.randint(1, 21, (10, 10, 10, 10)) >>> background_model = BackgroundModel( >>> mu_range=(0.0, 1.0), std_range=(0.0, 0.5) >>> ) >>> sample_map = background_model(data_tensor)
- forward(data: Tensor, **kwargs: Any) Tensor¶
Generate random background map.
- Parameters:
data – Integer-labeled 4D tensor of shape
(B, X, Y, Z). Label 0 is treated as background, if present, and left at zero intensity.**kwargs – Unused; accepted for interface compatibility with Model.
- Returns:
Synthesized background tensor of the same shape as the input tensor.
- class synthbold.models.DistractorModel(transforms: list[Transform] | None = None, transform_prob: float = 1.0, device: str = 'cpu', seed: int | None = None)¶
Bases:
ForegroundModelA model for generating distractor data, e.g. spheres, cubes, tetrahedra, or toroids.
Distractors are non-vessel objects added alongside the vasculature so that downstream models must learn to distinguish real vessel-like structures from other shapes rather than merely detecting “any foreground object”. This class shares
ForegroundModel’s pipeline mechanics (it turns an integer-labeled 4D volume(B, X, Y, Z)into a transformed label map) but overridesfrom_config()to skip the elastic and caliber deformations used for vessels, since distractor shapes should keep their characteristic geometry and only be randomly flipped.- Parameters:
transforms – List of transformations to apply, in order.
transform_prob – Probability of applying each transform, evaluated independently per transform and per batch element.
device – Target compute device (“cuda” or “cpu”).
seed – Random seed for reproducibility.
Notes
The generated distractor maps can be returned as a PyTorch tensor and saved to disk in ZARR or NIfTI format, with metadata automatically stored when using ZARR.
Examples
>>> data_tensor = torch.randint(1, 21, (10, 10, 10, 10)) >>> distractor_model = DistractorModel(transforms=[]) >>> sample_map = distractor_model(data_tensor)
- class synthbold.models.ForegroundModel(transforms: list[Transform] | None = None, transform_prob: float = 1.0, device: str = 'cpu', seed: int | None = None)¶
Bases:
ModelA model for generating foreground data, i.e. synthetic cylinders from label maps, to synthesize vessel-like networks.
This class turns an integer-labeled 4D volume
(B, X, Y, Z)into randomized vessel-like structures by passing it through a pipeline of transforms. UnlikeBackgroundModel, no intensity sampling is performed here; the label map itself is spatially warped (e.g. bent, flipped, pinched) to look like plausible vasculature. The default alternative constructor,from_config(), chainsRandomFlip,ElasticDeformation(for smooth curving), andCaliberDeformation(for varying vessel diameter).- Parameters:
transforms – List of transformations to apply, in order.
transform_prob – Probability of applying each transform, evaluated independently per transform and per batch element.
device – Target compute device (“cuda” or “cpu”).
seed – Random seed for reproducibility.
Notes
The generated foreground maps can be returned as a PyTorch tensor and saved to disk in ZARR or NIfTI format, with metadata automatically stored when using ZARR.
Examples
>>> data_tensor = torch.randint(1, 21, (10, 10, 10, 10)) >>> foreground_model = ForegroundModel(transforms=[]) >>> sample_map = foreground_model(data_tensor)
- forward(data: Tensor, **kwargs: Any) Tensor¶
Generate random vessel map.
- Parameters:
data – Integer-labeled 4D tensor of shape
(B, X, Y, Z)representing vessels as binary long straight cylinders. Label 0 is treated as background, if present.**kwargs – Unused; accepted for interface compatibility with Model.
- Returns:
Synthesized tensor of the same shape as the input tensor.
- class synthbold.models.PerturbationModel(chi_range: tuple[float, float], b0: float, theta_range: tuple[float, float], phi_range: tuple[float, float], padding: int | tuple[int, int, int], device: str = 'cpu', seed: int | None = None)¶
Bases:
ModelPhysics-based transform that converts geometry label maps into magnetic field perturbation maps (ΔBz).
Each vessel (or other geometric objects) is assigned a random susceptibility value and each sample is given a random B0 field orientation, from which the resulting magnetic field perturbation is computed using FFT convolution with a dipole kernel.
- Parameters:
chi_range – Minimum and maximum susceptibility differences in ppm.
b0 – Static magnetic field strength in Tesla.
theta_range – Minimum and maximum polar angles in radians for B0 orientations.
phi_range – Minimum and maximum azimuthal angles in radians for B0 orientations.
padding – Zero-padding width applied before FFT convolution. Can be either an integer or a tuple
(px, py, pz).device – Target compute device (“cuda” or “cpu”).
seed – Random seed for reproducibility.
- forward(data: Tensor, dchi: Tensor | None = None, theta: Tensor | None = None, phi: Tensor | None = None) Tensor¶
Compute ΔBz perturbation maps from vessel or other perturber objects.
- Parameters:
data – Tensor of shape
(B, X, Y, Z)containing integer vessel labels or labels from other perturber objects.dchi – Optional per-batch, per-label susceptibility differences of shape
(n_perturber,), wheren_perturberis the sum, over batch elements, of each element’s largest label value. Values are laid out flat, ordered by batch element and then by label id within each element (the same scheme as merge_labels’s offsets). Sampled uniformly fromchi_rangeif not given.theta – Optional per-batch B0 polar angles of shape
(B,). Sampled uniformly fromtheta_rangeif not given.phi – Optional per-batch B0 azimuthal angles of shape
(B,). Sampled uniformly fromphi_rangeif not given.
- Returns:
Tensor of shape
(B, X, Y, Z)containing the computed ΔBz perturbation maps.- Raises:
ValueError – If
dchi,theta, orphiis given and is not a 1D tensor of the expected length (the summed per-batch perturber counts indatafordchi, orBfortheta/phi).
- class synthbold.models.SignalModel(shape: tuple[int, int, int], t2_range: tuple[float, float], te_range: tuple[float, float], spin_echo: float | None, b0: float, gamma: float, device: str = 'cpu', seed: int | None = None)¶
Bases:
RandomGeneratorMixinSignal estimation based on static dephasing.
Based on tissue, label (vessel) and estimated field perturbation maps, the resulting complex-valued MRI signal is generated, under the assumption of static dephasing. More precisely, each voxel is assigned a complex signal value, based on tissue data (S0), T2, and field offset. The signal is computed at a finer resolution than the target output, so that each output voxel is composed of multiple sub-voxels with distinct field offsets; downsampling then coherently sums these sub-voxel signals, thereby simulating the intra-voxel dephasing caused by field inhomogeneities (e.g., from nearby vessels) that a real, coarser-resolution voxel would experience. The resulting magnitude image is obtained by downsampling to the target spatial dimension.
This model only considers static dephasing and susceptibility-induced field perturbations from macrovascular compartments, e.g., no gradient fields, etc. No additional tissue relaxation effects are applied. No chemical shift is considered. Constant T2 values are assigned per vessel, sampled from a uniform distribution within the specified range. Variations within the same vessel should be small.
- Parameters:
shape – Target shape of the output signal after downsampling.
t2_range – Minimum and maximum T2s values of vascular compartments in ms.
te_range – Minimum and maximum echo times in ms.
spin_echo – Spin echo time in ms. If set to None, no spin echo is applied.
b0 – Static magnetic field strength in Tesla.
gamma – Gyromagnetic ratio of the proton in ms-1T-1.
device – Target compute device (“cuda” or “cpu”).
seed – Random seed for reproducibility.
- property attrs: dict[str, Any]¶
Common metadata for ZARR/NIfTI storage.
- forward(tissue: Tensor, vessel: Tensor, dbz: Tensor, t2: Tensor | None = None, te: Tensor | None = None) SignalOutput¶
Computation of MRI signal after static dephasing.
- Parameters:
tissue – Tissue data of shape
(B, X, Y, Z).vessel – Integer vessel labels of shape
(B, X, Y, Z).dbz – ΔBz maps in Tesla of shape
(B, X, Y, Z).t2 – Optional per-batch, per-label T2 values of shape
(n_perturber,), wheren_perturberis the sum, over batch elements, of each element’s largest label value. Values are laid out flat, ordered by batch element and then by label id within each element (the same scheme as merge_labels’s offsets). Sampled uniformly fromt2_rangeif not given.te – Optional per-batch echo times in ms of shape
(B,). Sampled uniformly fromte_rangeif not given.
- Returns:
The computed signal output.
- Return type:
SignalOutput
Notes
Note that we are estimating an integer downsampling factor here. If input and output shapes are not divisible, this can lead to undesired behavior.
Call the instance (
model(tissue, vessel, dbz)) instead ofmodel.forward(tissue, vessel, dbz). In this implementation,__call__transfers inputs toself.devicebefore invokingforward.
synthbold.models.functional¶
Helper functions for signal modeling.
- synthbold.models.functional.dchi_to_dbz(chi: Tensor, padding: int | tuple[int, ...], b0: float, theta: Tensor, phi: Tensor) Tensor¶
Compute magnetic field perturbations from a susceptibility using FFT convolution with a dipole kernel for a batch of volumes.
- Parameters:
chi – Susceptibility distribution in ppm of shape
(B, X, Y, Z).padding – Zero padding width applied before FFT convolution.
b0 – Static magnetic field strength in Tesla.
theta – Polar angle of B0 direction in radians of shape
(B).phi – Azimuthal angle of B0 direction in radians of shape
(B).
- Returns:
Magnetic field perturbation map with same shape as chi in Tesla.
Notes
The implementation closely follows the implementation in boldswimsuite.BOLDgeometry.DiscreteVoxel3D.from_vessel_index_grid_FFT.
- synthbold.models.functional.labels_to_values(labels: Tensor, value: Tensor | None, name: str, low: float, high: float, device: device, generator: Generator, fill: float = 0.0) Tensor¶
Sample (or accept) one value per (batch, label) pair and scatter it into a volume matching labels.
Values are drawn from one flat array shared across the batch, so each batch element’s labels are offset by the cumulative maximum label of preceding batch elements (the same scheme as merge_labels’s offsets); this lets label ids repeat across batch elements without colliding.
- Parameters:
labels – Integer-labeled tensor of shape
(B, ...). Background voxels are assumed to be 0.value – Optional externally supplied flat values of shape
(n_label,), wheren_labelis the sum, over batch elements, of each element’s largest label value. Sampled uniformly from[low, high)if not given.name – Name of the parameter, used in the raised error message.
low – Lower bound of the sampling range.
high – Upper bound of the sampling range.
device – Target compute device.
generator – Random number generator for reproducibility.
fill – Value assigned to background (unlabeled) voxels.
- Returns:
Float32 tensor of the same shape as labels, with each labeled voxel set to its sampled/given value and background voxels set to fill.
- Raises:
ValueError – If value is given and is not a 1D tensor of length n_label.
- synthbold.models.functional.merge_labels(*labels: Tensor) Tensor¶
Merge two or more integer-labeled volumes into a single label map with disjoint indices.
Tensors are merged in the given order: earlier tensors take precedence over later ones wherever they overlap. Each tensor’s labels are offset by the cumulative maximum label of all previously merged tensors, so label indices remain unique across all inputs.
- Parameters:
*labels – Two or more integer-labeled tensors of identical shape
(B, X, Y, Z). Background voxels are assumed to be 0.- Returns:
Combined integer-labeled tensor with the same shape and dtype as the first input tensor.
- Raises:
ValueError – If fewer than two tensors are given, or if their shapes differ.
- synthbold.models.functional.spherical_to_cartesian(theta: Tensor, phi: Tensor) Tensor¶
Convert spherical coordinates (theta, phi) to Cartesian unit vectors.
- Parameters:
theta – Polar angle in radians of shape
(B).phi – Azimuthal angles in radians of shape
(B).
- Returns:
Normalized Cartesian vectors of shape
(B, 3). Each row corresponds to the unit vector(x, y, z)for the given(theta, phi).
Notes
- Assumes right-handed coordinate system:
x = sin(theta) * cos(phi) y = sin(theta) * sin(phi) z = cos(theta)
The returned vectors are normalized to unit length.