blobmodel package
Submodules
blobmodel.blob_shape module
This module defines classes for blob pulse shapes used in two-dimensional simulations.
- class blobmodel.blob_shape.AbstractBlobShape
Bases:
ABCAbstract class containing the blob pulse shapes. Two-dimensional blob pulse shapes are written in the form:
phi(theta_p, theta_s) = phi_p(theta_p) * phi_s(theta_s)Where the p and s subindexes stand for primary and secondary directions.
- abstractmethod get_blob_shape_p(theta: ndarray, **kwargs) ndarray
- abstractmethod get_blob_shape_s(theta: ndarray, **kwargs) ndarray
- class blobmodel.blob_shape.BlobShapeEnum(value)
Bases:
EnumEnum class representing blob shapes.
- dipole = 7
- double_exp = 3
- exp = 1
- gaussian = 4
- lorentz = 2
- rect = 5
- secant = 6
- class blobmodel.blob_shape.BlobShapeImpl(pulse_shape_p: BlobShapeEnum = BlobShapeEnum.gaussian, pulse_shape_s: BlobShapeEnum = BlobShapeEnum.gaussian)
Bases:
AbstractBlobShapeImplementation of the AbstractBlobShape class.
- get_blob_shape_p(theta: ndarray, **kwargs) ndarray
Compute the pulse shape in the principal direction.
- Parameters:
theta (np.ndarray) – Array of theta values.
kwargs – Additional keyword arguments passed to the shape function.
- Returns:
Array representing the pulse shape in the principal direction.
- Return type:
np.ndarray
- get_blob_shape_s(theta: ndarray, **kwargs) ndarray
Compute the pulse shape in the secondary direction.
- Parameters:
theta (np.ndarray) – Array of theta values.
kwargs – Additional keyword arguments passed to the shape function.
- Returns:
Array representing the pulse shape in the secondary direction.
- Return type:
np.ndarray
blobmodel.blobs module
This module defines a Blob class and related functions for discretizing and manipulating blobs.
- class blobmodel.blobs.Blob(blob_id: int = 0, blob_shape: AbstractBlobShape | None = None, amplitude: float = 1.0, width_p: float = 1.0, width_s: float = 1.0, v_x: float = 1.0, v_y: float = 0.0, pos_x0: float = 0.0, pos_y0: float = 0.0, t_init: float = 0.0, t_drain: float | NDArray[Any, Any] = inf, shape_parameters_p: dict | None = None, shape_parameters_s: dict | None = None, blob_alignment: bool = False, theta: float | None = None, t_lifetime: float | None = None)
Bases:
objectClass representing a single blob. It stores all blob parameters and discretizes the blob on a grid through the function discretize_blob. The contribution of a single blob to a grid defined by x, y and t is given by:
\[a e^{-(t-t_k)/\tau_\shortparallel} e^{-\left((t-t_k)/\tau_\mathrm{d}\right)^2}\varphi\left( \frac{(x-x_k)-v(t-t_k)}{\ell_x}, \frac{(y-y_k)-w(t-t_k)}{\ell_y} \right)\]- Where:
\(a\) is the blob amplitude, amplitude.
\(\ell_x\) is the blob width in the principal direction, width_p.
\(\ell_y\) is the blob width in the secondary direction, width_s.
\(v\) is the horizontal blob velocity.
\(w\) is the vertical blob velocity.
\(x_k\) and \(y_k\) are the blob position at time \(t_k\), pos_x0 and pos_y0.
\(t_k\) is the time at which the blob is seeded at \((x_k, y_k)\), t_init.
\(\tau_\shortparallel\) is the drainage time, t_drain.
\(\tau_\mathrm{d}\) is the pulse lifetime, t_lifetime. The corresponding factor is absent (equal to 1) when t_lifetime is None, which is the default.
\(\varphi\) is the blob pulse shape, blob_shape.
The two temporal factors are different: t_drain is a one-sided exponential decay from \(t_k\), growing without bound backwards in time, while t_lifetime is a Gaussian envelope symmetric about \(t_k\). They are independent and multiply. When a lifetime is set and t_drain is infinite, \(t_k\) is the time of maximum amplitude.
Additionally, a tilt angle can be provided through theta, in which case the two arguments of \(\varphi\) are rotated by theta around the blob center.
Added in version 2.1.0: The t_lifetime envelope.
- discretize_blob(x: NDArray[Any, Any], y: NDArray[Any, Any], t: NDArray[Any, Any], Ly: float, periodic_y: bool = False, one_dimensional: bool = False, y0: float = 0) NDArray[Any, Any]
Discretize blob on grid. If one_dimensional the secondary pulse shape is ignored.
- Parameters:
x (NDArray) – Grid coordinates in the x-direction, as an array broadcastable to shape (Ny, Nx, Nt): either a full meshgrid array or a 1D coordinate array reshaped as
x[np.newaxis, :, np.newaxis].y (NDArray) – Grid coordinates in the y-direction, as an array broadcastable to shape (Ny, Nx, Nt): either a full meshgrid array or a 1D coordinate array reshaped as
y[:, np.newaxis, np.newaxis].t (NDArray) – Time coordinates, as an array broadcastable to shape (Ny, Nx, Nt): either a full meshgrid array or a 1D coordinate array reshaped as
t[np.newaxis, np.newaxis, :]. A scalar t (single time point) is also accepted.Ly (float) – Length of domain in the y-direction.
periodic_y (bool, optional) – Flag indicating periodicity in the y-direction (default: False).
one_dimensional (bool, optional) – Flag indicating a one-dimensional blob (default: False).
y0 (float, optional) – Origin of the domain in the y-direction (default: 0). Only used when
periodic_yis True, where the blob position is wrapped into the domain[y0, y0 + Ly).
Notes
The periodicity in the y direction is implemented by first substracting the number of full domain Ly propagations made by the blob and by summing mirror blobs at vertical positions +-Ly.
- Returns:
discretized_blob – Discretized blob on a 3D array with dimensions (y, x, t), i.e. shape (Ny, Nx, Nt).
- Return type:
NDArray
- Raises:
ValueError – If
one_dimensionalis True andLyis not 0.
- property theta: float
Tilt angle used when discretizing the blob, measured from the x-axis (read-only). Resolved at construction from the explicit
thetaargument or, when that is None, fromblob_alignment.- Type:
float
blobmodel.geometry module
This module defines the Geometry class for creating a grid for the Model.
- class blobmodel.geometry.Geometry(Nx: int = 100, Ny: int = 100, Lx: float = 10, Ly: float = 10, dt: float = 0.1, T: float = 10, t_init: float = 0, periodic_y: bool = False, x0: float = 0, y0: float = 0)
Bases:
objectRepresents the space and time grid used by the Model class to discretize the blob evolution. It stores one 1D coordinate array per dimension (x, y and t) based on the desired resolution and length in each coordinate; the Model broadcasts them against each other instead of materializing full (Ny, Nx, Nt) meshgrids.
- classmethod from_arrays(x: ndarray, y: ndarray, t: ndarray, periodic_y: bool = False) Geometry
Build a Geometry from explicit coordinate arrays.
The grid invariants (Nx, Lx, x0, dt, …) are derived from the arrays instead of being provided by the caller. All arrays must be uniformly spaced — the Model’s speed_up truncation and the blob discretization assume it.
- Parameters:
x (np.ndarray) – 1D array of x coordinates, uniformly spaced.
y (np.ndarray) – 1D array of y coordinates, uniformly spaced. A single-element array yields a one-dimensional (Ly = 0) geometry.
t (np.ndarray) – 1D array of time coordinates, uniformly spaced.
periodic_y (bool, optional) – Flag indicating whether periodicity is allowed in the y-direction.
- Returns:
Geometry whose coordinate arrays match the inputs. The domain lengths follow the
endpoint=Falseconvention used by Geometry.__init__, i.e.Lx = dx * Nx.- Return type:
- Raises:
ValueError – If any array is not 1D, is empty, is not uniformly spaced, or is not strictly increasing.
blobmodel.model module
This module defines a 2D model of propagating blobs.
- class blobmodel.model.Model(geometry: Geometry | None = None, blob_shape: AbstractBlobShape | None = None, num_blobs: int = 1000, blob_factory: BlobFactory | None = None, labels: str = 'off', label_border: float = 0.75, one_dimensional: bool = False, verbose: bool = True, seed: int | Generator | None = None)
Bases:
objectClass storing all parameters relevant for the realization of a random process of a superposition of uncorrelated pulses propagating in two dimensions. The realization is performed by calling make_realization which:
uses a BlobFactory to make a list of blobs following the specified blob parameter distribution functions,
each ‘Blob’ is discretized by calling its discretize_blob function and
the discretization is performed on a grid given by the Geometry.
- classmethod from_blobs(blobs: List[Blob], geometry: Geometry | None = None, labels: str = 'off', label_border: float = 0.75, one_dimensional: bool = False, verbose: bool = True) Model
Create a Model that realizes a pre-built list of blobs.
Shortcut for the hand-built-blobs workflow: wraps blobs in a BlobListFactory, so the sampling parameters of Model.__init__ (num_blobs, blob_shape) need not be supplied — each Blob already carries its own parameters.
- Parameters:
blobs (List[Blob]) – Blobs to sum in make_realization.
geometry (Geometry, optional) – Grid on which the blobs are discretized, as in Model.__init__.
labels (str, optional) – Blob label setting, as in Model.__init__.
label_border (float, optional) – Defines region of blob, as in Model.__init__.
one_dimensional (bool, optional) – If True, the perpendicular shape of the blobs is discarded, as in Model.__init__.
verbose (bool, optional) – If True, print a loading bar.
- Returns:
Model whose realizations sum exactly the given blobs.
- Return type:
- get_blobs() List[Blob]
Return the list of blobs summed up in the last realization.
- Returns:
List of Blob objects.
- Return type:
List[Blob]
- Raises:
RuntimeError – If no blobs have been sampled yet. Blobs are sampled by
make_realization; call it first.
- make_realization(file_name: str | None = None, speed_up: bool = True, truncation_error: float = 1e-10, layout: str = 'default') Dataset
Integrate the Model over time and write out data as an xarray dataset.
- Parameters:
file_name (str, optional) – File name for the .nc file containing data as an xarray dataset.
speed_up (bool, optional) – Speed up the code by summing up each blob only over the time window where its amplitude on the grid exceeds
truncation_error; the rest of the blob is discarded. Enabled by default; set to False for blob shapes with slowly-decaying tails (see Notes).truncation_error (float, optional) – Amplitude below which a blob is truncated when
speed_upis enabled.layout (str, optional) – Layout of the returned (and saved) dataset. Possible values: “default”: density n(y, x, t) with 1D coordinates x, y, t. “imaging”: the GPI/APD imaging format frames(y, x, time) with 2D coordinates R(y, x), Z(y, x), as returned by to_imaging_dataset. Requires a two-dimensional geometry.
- Returns:
xarray dataset with the data resulting from a realization of the process described by the model and evaluated in a three-dimensional grid with dimensions: - x: Horizontal coordinate - y: Vertical coordinate - t: Time coordinate The resulting blob density, evaluated in the grid, is given by the DataArray, n, with dimension order (y, x, t), i.e. shape (Ny, Nx, Nt). For a grid with Ly = 0 (one-dimensional model), the y dimension is dropped and n has dimensions (x, t). With
layout="imaging"the density is instead the DataArray frames with dimensions (y, x, time), see to_imaging_dataset.- Return type:
xr.Dataset
- Raises:
ValueError – If
layoutis not one of the values listed above, iflayout="imaging"is requested for a one-dimensional model, or if a sampled blob has an array-valued t_drain whose length does not match the geometry’s Nx.- Warns:
UserWarning – If periodic_y is set and a sampled blob width is large compared to the domain size Ly, in which case the mirror blobs used to implement the periodicity may become apparent.
Notes
The truncation window used by speed_up assumes an exponentially decaying pulse shape (blob_shape=”exp”). For shapes with more slowly decaying tails (e.g. lorentz) pass
speed_up=False.
- blobmodel.model.to_imaging_dataset(dataset: Dataset) Dataset
Convert a blobmodel output dataset to the GPI/APD imaging format.
Downstream analysis tooling for experimental gas-puff-imaging (GPI) and avalanche-photodiode (APD) data standardizes on a dataset with the density stored as
frames(y, x, time)and the grid stored as two-dimensional coordinate arraysR(y, x),Z(y, x). This helper converts the default blobmodel outputn(y, x, t)(1D coordinatesx,y,t) into that format. It is also available directly from the model viamake_realization(..., layout="imaging").- Parameters:
dataset (xr.Dataset) – Dataset as returned by Model.make_realization with the default layout. Must be two-dimensional, i.e. contain a y coordinate. A blob_labels variable, if present, is carried over.
- Returns:
Dataset with the density as frames with dimension order (y, x, time), coordinates R and Z of shape (Ny, Nx) holding the meshgrid of the x and y coordinates, and the coordinate time.
- Return type:
xr.Dataset
- Raises:
ValueError – If the dataset has no y coordinate (one-dimensional model output).
blobmodel.plotting module
This module provides functions to create and display animations of model output.
- blobmodel.plotting.show_model(dataset: Dataset, variable: str = 'n', interval: int = 100, gif_name: str | None = None, fps: int = 10, show: bool = True) animation.FuncAnimation
Creates an animation that shows the evolution of a specific variable over time.
- Parameters:
dataset (xr.Dataset) – Model data.
variable (str, optional) – Variable to be animated (default: “n”).
interval (int, optional) – Time interval between frames in milliseconds (default: 100).
gif_name (str, optional) – If not None, save the animation as a GIF and name it accordingly.
fps (int, optional) – Set the frames per second for the saved GIF (default: 10).
show (bool, optional) – If True (the default), display the animation in an interactive window with
plt.show(), which blocks until the window is closed. Set to False in scripts and CI, e.g. when only saving a GIF.
- Returns:
The animation object. Keep a reference to it as long as the animation should stay alive.
- Return type:
matplotlib.animation.FuncAnimation
- Raises:
ValueError – If the dataset has no t coordinate, e.g. because it was produced with
layout="imaging"(frames/time); only the default layout is supported for plotting.
Notes
This function chooses between a 1D and 2D visualizations based on the dimensionality of the dataset.
The color scale is fixed to the global minimum and maximum of variable over the whole dataset.
blobmodel.stochasticality module
This module defines a class for generating blob parameters.
- class blobmodel.stochasticality.BlobFactory
Bases:
ABCAbstract class used by 2d propagating blob model to specify blob parameters.
- abstractmethod is_one_dimensional() bool
returns True if the BlobFactory is compatible with a one_dimensional model.
- abstractmethod sample_blobs(Ly: float, T: float, num_blobs: int, blob_shape: AbstractBlobShape) List[Blob]
Creates a list of Blobs used in Model.
Notes
Blob draining is owned by the factory, not the Model: each Blob carries its own t_drain (DefaultBlobFactory takes it as a constructor argument, np.inf — no draining — by default).
- set_rng(rng: Generator) None
Set the random number generator used when sampling blob parameters.
Called by Model when it is given a seed. The default implementation stores the generator as self.rng; custom factories that want to be seedable through Model should draw their random numbers from self.rng.
- Parameters:
rng (np.random.Generator) – Random number generator to use for sampling.
- class blobmodel.stochasticality.BlobListFactory(blobs: List[Blob])
Bases:
BlobFactoryBlobFactory that returns a pre-built list of blobs.
Use this (typically through Model.from_blobs) when the blobs are constructed by hand instead of sampled from distributions. All sample_blobs arguments (Ly, T, num_blobs, blob_shape) are ignored: each Blob already carries its own parameters.
- is_one_dimensional() bool
Returns True if all stored blobs have zero perpendicular velocity.
- Returns:
True if v_y == 0 for every blob, False otherwise.
- Return type:
bool
- sample_blobs(Ly: float, T: float, num_blobs: int, blob_shape: AbstractBlobShape) List[Blob]
Return the stored blob list. All arguments are ignored.
- class blobmodel.stochasticality.CallableBlobFactory(blob_getter: Callable[[Generator], Blob], one_dimensional: bool = False, seed: int | Generator | None = None)
Bases:
BlobFactoryBlobFactory that builds each blob by calling a user-provided getter.
The getter receives the factory’s random number generator, so blobs sampled through this factory are reproducible via CallableBlobFactory(seed=…) or Model(seed=…) — provided the getter draws its random numbers from the generator it is given instead of the global np.random state.
- is_one_dimensional() bool
Return the one_dimensional flag declared at construction.
- sample_blobs(Ly: float, T: float, num_blobs: int, blob_shape: AbstractBlobShape) List[Blob]
Create num_blobs blobs by calling the getter with self.rng.
Ly, T and blob_shape are ignored: the getter is expected to fully specify each blob.
- class blobmodel.stochasticality.DefaultBlobFactory(t_drain: float | NDArray[Any, Any] | int = inf, blob_alignment: bool = False, seed: int | Generator | None = None, t_lifetime: float | None = None)
Bases:
BlobFactoryDefault implementation of BlobFactory.
Samples each blob parameter independently. Every parameter defaults to a degenerate (constant) distribution except the amplitude, which is exponential with mean 1 (the canonical FPP choice), and the perpendicular velocity
vy, which is zero (matching the Blob defaultv_y=0, and making the default factory compatible with one-dimensional models). Individual parameters are reconfigured with set_sampler, which accepts either a DistributionEnum or an arbitrary sampling callable.- is_one_dimensional() bool
Returns True if the BlobFactory is compatible with a one-dimensional model.
- Returns:
True if the BlobFactory is compatible with a one-dimensional model, False otherwise.
- Return type:
bool
Notes
Perpendicular width parameters are irrelevant since perp shape should be ignored by the Bolb class.
Only the built-in DistributionEnum.zeros distribution for “vy” is recognized as one-dimensional; a custom callable sampler is assumed two-dimensional even if it always returns zeros.
- sample_blobs(Ly: float, T: float, num_blobs: int, blob_shape: AbstractBlobShape) List[Blob]
Creates a list of Blobs used in the Model.
Every blob is given the factory’s t_drain (a constructor argument, np.inf — no draining — by default) and its t_lifetime (also a constructor argument, None — no envelope — by default).
- Parameters:
Ly (float) – Size of the domain in the y-direction.
T (float) – End time of the simulation. Blob arrival times are sampled uniformly in [0, T).
num_blobs (int) – Number of blobs to generate.
blob_shape (AbstractBlobShape) – Object representing the shape of the blobs.
- Returns:
List of Blob objects generated for the Model.
- Return type:
List[Blob]
- Raises:
TypeError – If blob_shape is not an AbstractBlobShape instance.
- set_sampler(parameter: str, sampler: DistributionEnum | Callable[[Generator, int], ndarray], free_parameter: float | None = None) DefaultBlobFactory
Configure how one blob parameter is sampled.
- Parameters:
parameter (str) –
Which blob parameter to configure. One of: - “amplitude”: blob amplitude - “wp”: width in the principal (propagation) blob direction - “ws”: width in the secondary (perpendicular) blob direction - “vx”: velocity in the x-direction - “vy”: velocity in the y-direction - “posx”: blob position in the x-direction at
t_init(DistributionEnum.zeros by default, i.e. every blob is seeded at x = 0; the factory does not know the domain, so seeding blobs across it means supplying a callable, e.g.
lambda rng, n: rng.uniform(-pad, Lx + pad, n))”spp”: pulse shape parameter in the principal direction
”sps”: pulse shape parameter in the secondary direction
sampler (DistributionEnum or Callable[[np.random.Generator, int], np.ndarray]) – Either one of the built-in distributions (see Notes), or a callable drawing the values itself: it is called with the factory’s random number generator and the number of blobs and must return one value per blob. Draw from the generator you are given (not the global np.random state) so realizations stay reproducible through DefaultBlobFactory(seed=…) or Model(seed=…).
free_parameter (float, optional) – Free parameter of the built-in distribution (see Notes), by default 1.0. Only valid together with a DistributionEnum.
- Returns:
The factory itself, so calls can be chained:
DefaultBlobFactory().set_sampler("vy", DistributionEnum.zeros).- Return type:
Notes
- The following distributions are implemented:
exp: exponential distribution with mean free_parameter
gamma: gamma distribution with free_parameter as shape parameter and mean 1
normal: normal distribution with zero mean and free_parameter as scale parameter
uniform: uniform distribution with mean 1 and free_parameter as width, i.e. support [1 - free_parameter / 2, 1 + free_parameter / 2]. free_parameter > 2 produces negative samples and is therefore rejected with a ValueError for the width distributions.
rayleigh: rayleigh distribution with mean 1. free_parameter is intentionally ignored: the scale is fixed to sqrt(2 / pi).
deg: degenerate distribution at free_parameter
zeros: array of zeros
- Raises:
TypeError – If sampler is neither a DistributionEnum member nor a callable.
ValueError – If parameter is not one of the names listed above, if a width (wp or ws) is uniform with free_parameter > 2 (which would produce negative blob widths), or if free_parameter is combined with a callable sampler.
- set_theta_setter(theta_setter)
Set a lambda function to set the value of theta (blob tilting) for each blob. Once set, the returned angle takes precedence and blob_alignment is ignored. Important: the blob angle is measured with respect to the x axis, not with respect to the velocity vector.
- theta_setter: Callable[[], float] | None
- blobmodel.stochasticality.ParameterSampler
called with the factory’s random number generator and the number of blobs, returns one sampled value per blob.
- Type:
Signature of a custom sampler for DefaultBlobFactory.set_sampler
alias of
Callable[[Generator,int],ndarray]