Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,20 @@ CI is `.github/workflows/workflow.yml` (currently duplicated jobs on Python
vector.
- `t_drain` is a drain *time scale* (exponential decay), not a start time; it
may be a scalar or an array of length Nx.
- **`t_drain` vs `t_lifetime`** (added in 2.1.0): easy to confuse, and they
coexist and multiply. `t_drain` is a *one-sided* exponential decay from
`t_init` (it grows without bound backwards in time); `t_lifetime` is a
Gaussian envelope *symmetric about* `t_init`, `exp(-((t - t_init)/tau_d)^2)`,
scalar only, `None` by default. `None` means the blob is multiplied by the
Python float `1.0` — bit-for-bit unchanged — which `tests/test_lifetime.py`
asserts against reference values computed on the pre-2.1.0 `main`.
- **`DefaultBlobFactory` seeds blobs at `pos_x0 = 0`** unless the `posx`
sampler is reconfigured (added in 2.1.0, default `DistributionEnum.zeros`,
which draws nothing and so leaves the RNG stream untouched). The factory
cannot see `Lx` (issue #140), so seeding blobs across the domain means
passing a callable: `set_sampler("posx", lambda rng, n: rng.uniform(...))`.
With a finite `t_lifetime` this is a prerequisite, not a nicety — otherwise
every pulse peaks at the inflow edge.
- Version is the static `version` in pyproject.toml (bumped manually per
release, see recent "Up version number" commits); setuptools-scm in
build-system is vestigial (item 14).
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,8 @@ bm = Model(
```
Alternatively, you can specify all blob parameters exactly as you want by writing your own class which inherits from BlobFactory. See `examples/custom_blobfactory.py` as an example or take a look at the [blobmodel documentation](https://blobmodel.readthedocs.io/en/latest/?badge=latest).

Blobs can decay exponentially from their initial time with a drainage time `t_drain`, and/or be given a finite pulse lifetime `t_lifetime`, a Gaussian envelope symmetric about the blob's `t_init` so that the blob grows, peaks and decays. Both are arguments of `DefaultBlobFactory` and are applied to every sampled blob; see the [drainage time](https://blobmodel.readthedocs.io/en/latest/drainage_time.html) and [pulse lifetime](https://blobmodel.readthedocs.io/en/latest/pulse_lifetime.html) sections of the documentation.

## Contributing

Feel free to raise issues about anything. Contributions through pull requests are also very welcome. Please take a look at our [Contributor guide](https://blobmodel.readthedocs.io/en/latest/contributor_guide.html) for further details.
100 changes: 93 additions & 7 deletions blobmodel/blobs.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class Blob:
the function `discretize_blob`. The contribution of a single blob to a grid defined by `x`, `y` and `t` is given by:

.. math::
a e^{-(t-t_k)/\\tau_\\shortparallel}\\varphi\\left( \\frac{(x-x_k)-v(t-t_k)}{\ell_x}, \\frac{(y-y_k)-w(t-t_k)}{\ell_y} \\right)
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:
- :math:`a` is the blob amplitude, `amplitude`.
Expand All @@ -26,11 +26,23 @@ class Blob:
- :math:`t_k` is the time at which the blob is seeded at
:math:`(x_k, y_k)`, `t_init`.
- :math:`\\tau_\\shortparallel` is the drainage time, `t_drain`.
- :math:`\\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.
- :math:`\\varphi` is the blob pulse shape, `blob_shape`.

The two temporal factors are different: `t_drain` is a one-sided
exponential decay *from* :math:`t_k`, growing without bound backwards in
time, while `t_lifetime` is a Gaussian envelope *symmetric about*
:math:`t_k`. They are independent and multiply. When a lifetime is set and
`t_drain` is infinite, :math:`t_k` is the time of maximum amplitude.

Additionally, a tilt angle can be provided through `theta`, in which case
the two arguments of :math:`\\varphi` are rotated by `theta` around the
blob center.

.. versionadded:: 2.1.0
The `t_lifetime` envelope.
"""

def __init__(
Expand All @@ -50,6 +62,7 @@ def __init__(
shape_parameters_s: Union[dict, None] = None,
blob_alignment: bool = False,
theta: Optional[float] = None,
t_lifetime: Optional[float] = None,
) -> None:
"""
Initialize a single blob.
Expand Down Expand Up @@ -97,14 +110,24 @@ def __init__(
vector). If not None, this angle is used directly and ``blob_alignment``
is ignored. If None (the default), the angle is determined by
``blob_alignment``: the velocity phase when it is True, or 0 when False.
t_lifetime : float, optional
Pulse lifetime: the blob is multiplied by the Gaussian envelope
``exp(-((t - t_init) / t_lifetime)**2)``, symmetric about
``t_init``. Scalar only — unlike ``t_drain`` there is no per-x
array form. Default None = no envelope; ``np.inf`` is accepted and
is equivalent to None. Keyword-only in practice: it is last in the
signature so that positional callers are unaffected.

.. versionadded:: 2.1.0

Raises
------
TypeError
If ``blob_shape`` is not an ``AbstractBlobShape`` instance.
ValueError
If ``width_p`` or ``width_s`` is not positive, or if ``t_drain``
is not positive (every element, when it is an array).
If ``width_p`` or ``width_s`` is not positive, if ``t_drain``
is not positive (every element, when it is an array), or if
``t_lifetime`` is given and is not positive.

"""
if blob_shape is None:
Expand All @@ -119,6 +142,10 @@ def __init__(
)
if np.any(np.asarray(t_drain) <= 0):
raise ValueError(f"t_drain must be positive, got t_drain = {t_drain}.")
if t_lifetime is not None and not t_lifetime > 0:
raise ValueError(
f"t_lifetime must be positive, got t_lifetime = {t_lifetime}."
)

self.blob_id = blob_id
self.blob_shape = blob_shape
Expand All @@ -138,6 +165,9 @@ def __init__(
if np.ndim(t_drain) == 0
else np.asarray(t_drain, dtype=np.float64)
)
self.t_lifetime: Optional[float] = (
None if t_lifetime is None else float(t_lifetime)
)
self.shape_parameters_p = (
{} if shape_parameters_p is None else shape_parameters_p
)
Expand Down Expand Up @@ -318,9 +348,46 @@ def _single_blob(
)

return (
self.amplitude * self._drain(t) * primary_axis_shape * secondary_axis_shape
self.amplitude
* self._temporal_factor(t)
* primary_axis_shape
* secondary_axis_shape
)

def _temporal_factor(self, t: Union[int, NDArray]) -> NDArray:
"""
Combined drain and lifetime factor.

Without a lifetime this is exactly `_drain`. With one, the drain and
envelope exponents are summed before exponentiating: evaluated
separately, far from `t_init` the drain overflows while the envelope
underflows, giving ``inf * 0 = nan`` instead of a negligible value.

Parameters
----------
t : NDArray
Time coordinates.

Returns
-------
temporal_factor : NDArray
``exp(-(t - t_init)/t_drain - ((t - t_init)/t_lifetime)**2)``.

"""
if self.t_lifetime is None:
return self._drain(t)
return np.exp(
self._drain_exponent(t) - ((t - self.t_init) / self.t_lifetime) ** 2
)

def _drain_exponent(self, t: Union[int, NDArray]) -> Any:
"""
Exponent of the drain factor, ``-(t - t_init) / t_drain``.
"""
if isinstance(self.t_drain, np.ndarray):
return -(t - self.t_init) / self.t_drain[np.newaxis, :, np.newaxis]
return -(t - self.t_init) / self.t_drain

def _drain(self, t: Union[int, NDArray]) -> NDArray:
"""
Calculate the drain factor for the blob.
Expand All @@ -336,9 +403,28 @@ def _drain(self, t: Union[int, NDArray]) -> NDArray:
Drain factor.

"""
if isinstance(self.t_drain, np.ndarray):
return np.exp(-(t - self.t_init) / self.t_drain[np.newaxis, :, np.newaxis])
return np.exp(-(t - self.t_init) / self.t_drain)
return np.exp(self._drain_exponent(t))

def _envelope(self, t: Union[int, NDArray]) -> Any:
"""
Gaussian pulse-lifetime envelope, symmetric about `t_init`.

Parameters
----------
t : NDArray
Time coordinates.

Returns
-------
envelope_factor : float or NDArray
``exp(-((t - t_init) / t_lifetime)**2)``, or the float 1.0 when
`t_lifetime` is None. Multiplying by 1.0 is exact in IEEE754, so
a blob without a lifetime is bit-for-bit unaffected.

"""
if self.t_lifetime is None:
return 1.0
return np.exp(-(((t - self.t_init) / self.t_lifetime) ** 2))

def _blob_trajectory_x(self, t: Union[int, NDArray]) -> Any:
"""
Expand Down
108 changes: 90 additions & 18 deletions blobmodel/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -474,29 +474,101 @@ def _compute_start_stop(self, blob: Blob, speed_up: bool, truncation_error: floa
-------
Tuple[int, int]
Start and stop indices.

Notes
-----
- Two independent windows are intersected: the one derived from the
blob crossing the domain (only available when ``v_x != 0``) and,
for a blob with a finite `t_lifetime`, the one derived from the
support of its temporal envelope. Either may be absent, in which
case the other is used alone; with neither the whole time axis is
returned.
"""
if not speed_up or blob.v_x == 0:
if not speed_up:
return 0, self._geometry.t.size

n_t = self._geometry.t.size
start, stop = 0, n_t
dt, t0 = self._geometry.dt, self._geometry.t[0]
idx_x0 = (blob.t_init - t0) / dt + (self._geometry.x[0] - blob.pos_x0) / (
blob.v_x * dt
)
idx_Lx = idx_x0 + self._geometry.Lx / (blob.v_x * dt)
# Decay length of the blob along the x-axis: the blob-frame widths
# projected onto x through the tilt angle (width_p for an untilted
# blob, width_s at theta = pi/2).
width_x = (
np.abs(np.cos(blob.theta)) * blob.width_p
+ np.abs(np.sin(blob.theta)) * blob.width_s
)
margin = (
-width_x * np.log(truncation_error * np.sqrt(np.pi)) / np.abs(blob.v_x * dt)
)
start = int(np.clip(min(idx_x0, idx_Lx) - margin, 0, self._geometry.t.size))
stop = int(np.clip(max(idx_x0, idx_Lx) + margin, 0, self._geometry.t.size))

return start, stop
if blob.t_lifetime is not None:
Comment thread
Sosnowsky marked this conversation as resolved.
Resolved
# The envelope is symmetric about t_init, so the window is too.
half_width = self._lifetime_half_width(blob, truncation_error)
Comment thread
Sosnowsky marked this conversation as resolved.
Resolved
idx_peak = (blob.t_init - t0) / dt
margin = half_width / dt
start = max(start, int(np.clip(np.floor(idx_peak - margin), 0, n_t)))
stop = min(stop, int(np.clip(np.ceil(idx_peak + margin), 0, n_t)))

if blob.v_x != 0:
idx_x0 = (blob.t_init - t0) / dt + (self._geometry.x[0] - blob.pos_x0) / (
blob.v_x * dt
)
idx_Lx = idx_x0 + self._geometry.Lx / (blob.v_x * dt)
# Decay length of the blob along the x-axis: the blob-frame widths
# projected onto x through the tilt angle (width_p for an untilted
# blob, width_s at theta = pi/2).
width_x = (
np.abs(np.cos(blob.theta)) * blob.width_p
+ np.abs(np.sin(blob.theta)) * blob.width_s
)
margin = (
-width_x
* np.log(truncation_error * np.sqrt(np.pi))
/ np.abs(blob.v_x * dt)
)
Comment thread
Sosnowsky marked this conversation as resolved.
Resolved
start = max(start, int(np.clip(min(idx_x0, idx_Lx) - margin, 0, n_t)))
stop = min(stop, int(np.clip(max(idx_x0, idx_Lx) + margin, 0, n_t)))

# The two windows may not overlap at all: collapse rather than invert.
return start, max(start, stop)

@staticmethod
def _lifetime_half_width(blob: Blob, truncation_error: float) -> float:
r"""
Half-width in time of the support of a blob's lifetime envelope.

The envelope ``exp(-(dt / tau_d)**2)`` alone drops below
`truncation_error` for ``|dt| >= tau_d * sqrt(-log(error))``. A finite
`t_drain` makes the drain factor *grow* backwards in time, so the
product ``exp(-(dt / tau_d)**2 + dt / t_drain)`` is the binding
constraint; it falls below `truncation_error` for

.. math::
\Delta \geq b + \sqrt{b^2 - \tau_d^2 \log \varepsilon},
\quad b = \tau_d^2 / (2 \tau_\text{drain}),

which reduces to the envelope-only bound at ``t_drain = inf``. The
smallest element is used for an array-valued `t_drain` (smallest drain
time = widest window = the conservative choice).

`truncation_error` bounds the field itself, so ``epsilon`` is
``truncation_error / |amplitude|``: every blob shape peaks at or below
1 in magnitude, hence ``|amplitude| * envelope * drain`` bounds the
blob's contribution.

Parameters
----------
blob : Blob
Blob with a non-None `t_lifetime`.
truncation_error : float
Amplitude below which the blob is truncated.

Returns
-------
float
Half-width in time units; `np.inf` for an infinite `t_lifetime`.
"""
tau_d = blob.t_lifetime
if tau_d is None or not np.isfinite(tau_d):
return np.inf
amplitude = abs(blob.amplitude)
if amplitude == 0:
return 0.0
# Clamped so that an error >= 1 (nothing to keep) cannot produce a nan.
neg_log_error = max(-np.log(truncation_error / amplitude), 0.0)
t_drain = np.min(blob.t_drain)
b = 0.0 if np.isinf(t_drain) else tau_d**2 / (2 * t_drain)
return float(b + np.sqrt(b**2 + tau_d**2 * neg_log_error))

def _reset_fields(self):
"""Reset the density and labels fields."""
Expand Down
Loading
Loading