Note
Go to the end to download the full example code.
Gray-Scott: equations from a corrupted movie¶
Note
Uses the experimental SPDE toolbox — see SPDE (spatial fields) — experimental.
A few drops of an autocatalyst \(V\) in a bath of feed \(U\) grow into a colony of self-replicating spots: each spot swells, splits in two, and the daughters push apart until they tile the dish. The dynamics is the stochastic Gray-Scott model
with conserved (divergence-form) noise \(\nabla\cdot\boldsymbol\eta\), which only moves material around. This page films the colony with an imperfect camera — pixel noise and dead pixels — hands SFI the movie and a generic library of 34 candidate terms, and asks for the equations:
although every pixel is noisy and 2% of them are dead in every frame, PASTIS keeps exactly the seven Gray-Scott terms, with error bars;
the recovered equations, restarted from the initial drops, regrow the colony: same growth curve, same spot spacing;
a corruption ladder shows where it breaks: dead pixels only cost data, while pixel noise of a few percent of the spot contrast biases the nonlinear terms until PASTIS keeps spurious ones.
Tags
synthetic · overdamped · SPDE · reaction-diffusion · 2D · sparsity
stamp_output()
[Generated: 2026-10-18 10:08]
A generic candidate library¶
Two named ScalarSector fields U and V live on one periodic
GridLayout; differential operators
(layout.lap, layout.grad, layout.biharmonic) and pointwise
algebra compose freely, and layout.embed compiles the expression
tree into an inference-ready Basis.
We do not hand-code the Gray-Scott structure. Each field gets the same generic library: every monomial of \((U, V)\) up to order 3, both Laplacians, the three gradient products and both biharmonics — 17 candidates per equation, 34 in total. Labels are generated from the expression tree.
from SFI.statefunc.layout import GridLayout, ScalarSector
layout = GridLayout(U=ScalarSector([0]), V=ScalarSector([1]), dim=2, ndim=2, bc="pbc")
U, V = layout.U, layout.V
gU, gV = layout.grad(U), layout.grad(V)
terms = [
layout.const(1), U, V, # "1", "U", "V"
U**2, U * V, V**2, # quadratic
U**3, U**2 * V, U * V**2, V**3, # cubic
layout.lap(U), layout.lap(V), # "∇²U", "∇²V"
gU.dot(gU), gV.dot(gV), gU.dot(gV), # gradient products
layout.biharmonic(U), layout.biharmonic(V), # "∇⁴U", "∇⁴V"
]
library = terms[0]
for t in terms[1:]:
library = library & t
BASIS = layout.embed(rank=1, U=library, V=library) # same candidates for U̇ and V̇
n_per = len(library.labels) # 17
labels = [f"{lbl}→U̇" for lbl in library.labels] + [f"{lbl}→V̇" for lbl in library.labels]
def restrict(support):
"""The library restricted to a support, compiled on its own (fast to simulate)."""
picked = {}
for name, offset in (("U", 0), ("V", n_per)):
sel = [terms[i - offset] for i in sorted(support) if offset <= i < offset + n_per]
picked[name] = sel[0]
for t in sel[1:]:
picked[name] = picked[name] & t
return layout.embed(rank=1, **picked)
The experiment¶
The true model is the library restricted to its seven Gray-Scott terms,
with the classic diffusion ratio \(D_U/D_V = 2\) and \((F, K)\)
in the self-replicating-spot regime. A periodic 128×128 dish
(dx = 1) starts from four square drops of \(V\).
Pattern formation is slow — the colony needs about 3000 time units to
fill the dish — while the inference needs frames closer together than
the fastest relaxation, grid-scale diffusion at rate
\(8 D_U/\Delta x^2 \approx 1.3\). So, like a microscope alternating
high-speed bursts with a slow time-lapse, each quarter of the run opens
with an analysis clip of 100 frames at \(\Delta t = 0.125\),
then keeps one frame every 12.5 time units for viewing. Successive
simulate calls continue the same trajectory.
from SFI.bases.spde import conserved_noise_pbc, square_grid_extras
from SFI.langevin import OverdampedProcess
from SFI.trajectory import TrajectoryCollection
GRID = (128, 128)
DX = 1.0
DU, DV = 0.16, 0.08
F_gs, K_gs = 0.0367, 0.0649 # self-replicating spots
SIGMA = 0.01 # conserved-noise amplitude (both fields)
gray_scott = { # the seven true terms and their coefficients
"1→U̇": F_gs, "U→U̇": -F_gs, "UV²→U̇": -1.0, "∇²U→U̇": DU,
"V→V̇": -(F_gs + K_gs), "UV²→V̇": 1.0, "∇²V→V̇": DV,
}
support_true = np.sort([labels.index(name) for name in gray_scott])
theta_true = np.zeros(len(labels))
theta_true[[labels.index(name) for name in gray_scott]] = list(gray_scott.values())
DT = 0.125 # frame interval of the analysis clips
DT_SHOW = 12.5 # = one 100-frame clip: viewing frames stay evenly spaced
N_CLIP, N_QUARTER = 100, 59
T_QUARTER = DT_SHOW * (N_QUARTER + 1) # 750 time units
box_extras = square_grid_extras(grid_shape=GRID, dx=DX)
def drops(key, n=4, size=10):
"""Uniform bath U=1, V=0 with n square drops (U=1/2, V=1/4) and 2% noise."""
Nx, Ny = GRID
k_pos, k_u, k_v = random.split(key, 3)
ii, jj = np.meshgrid(np.arange(Nx), np.arange(Ny), indexing="ij")
in_drop = np.zeros(GRID, dtype=bool)
for i0, j0 in np.asarray(random.randint(k_pos, (n, 2), 0, Nx)):
in_drop |= ((ii - i0) % Nx < size) & ((jj - j0) % Ny < size)
U0 = np.where(in_drop, 0.5, 1.0) + 0.02 * np.asarray(random.normal(k_u, GRID))
V0 = np.where(in_drop, 0.25, 0.0) + 0.02 * np.asarray(random.normal(k_v, GRID))
return jnp.asarray(np.stack([U0, V0], axis=-1).reshape(Nx * Ny, 2))
proc = OverdampedProcess(restrict(support_true),
D=conserved_noise_pbc(sigma=SIGMA, grid_shape=GRID, dx=DX, n_fields=2))
proc.set_params(theta_F=jnp.asarray(theta_true[support_true], dtype=jnp.float32))
proc.set_extras(extras_global=box_extras)
key = random.PRNGKey(0)
key, k_ic = random.split(key)
x0 = drops(k_ic)
proc.initialize(x0)
show_frames, clips = [np.asarray(x0)[None]], []
for quarter in range(4):
key, k_clip, k_show = random.split(key, 3)
clip = proc.simulate(dt=DT, Nsteps=N_CLIP, key=k_clip,
oversampling=2, # integrator step Δt/2
compute_observables=False)
seg = proc.simulate(dt=DT_SHOW, Nsteps=N_QUARTER, key=k_show,
oversampling=100, # integrator step 0.125 between viewing frames
compute_observables=False)
clips.append(clip)
show_frames += [clip.to_array()[-1:], seg.to_array()]
truth = TrajectoryCollection.from_arrays(X=np.concatenate(show_frames), dt=DT_SHOW,
extras_global=box_extras)
clean = clips[0].concat(clips[1:])
t_show = DT_SHOW * np.arange(truth.T)
t_clips = [T_QUARTER * q for q in range(4)] # each clip starts there
print(f"{truth.T} viewing frames + {len(clips)} clips of {N_CLIP} frames "
f"on {GRID[0]}×{GRID[1]} cells")
241 viewing frames + 4 clips of 100 frames on 128×128 cells
\(U\) (top) and \(V\) (bottom) at five times; the first four are the moments the analysis clips begin.
The recording¶
Now the camera. degrade_spatial_data()
adds pixel noise — independent from pixel to pixel and from frame to
frame — and kills a random 2% of the pixels in every frame. A
missing pixel hides more than its own value: every finite-difference
stencil that reads it is corrupted. stencil_radius=2 — the reach of
\(\nabla^4\), the widest operator in the library — excludes from the
fit every cell whose stencil touches a missing pixel in any of the five
frames an estimator row reads, while the remaining cells keep all their
neighbours. That is a heavy toll: only about a quarter of the cells
survive it.
from SFI.trajectory.degrade import degrade_spatial_data
PIXEL_NOISE = 0.005 # standard deviation, in concentration units
DEAD_PIXELS = 0.02 # fraction of pixels missing in each frame
recording = degrade_spatial_data(clean, downscale=1, noise=PIXEL_NOISE,
data_loss_fraction=DEAD_PIXELS, stencil_radius=2,
bc="pbc", seed=1)
kept = np.mean([np.mean(ds.dynamic_mask) for ds in recording.datasets])
v_peak = truth.to_array()[-1, :, 1].max() # spots at the end of the run
print(f"pixel noise {PIXEL_NOISE} = {100 * PIXEL_NOISE / v_peak:.1f}% of the spot peak V = {v_peak:.2f}")
print(f"{len(recording.datasets)} clips × {N_CLIP} frames × {GRID[0] * GRID[1]} cells; "
f"{100 * kept:.0f}% of the cells enter the fit")
pixel noise 0.005 = 1.0% of the spot peak V = 0.52
4 clips × 100 frames × 16384 cells; 28% of the cells enter the fit
One frame of the last clip: what the camera recorded (dead pixels in cyan); a zoom on the clean field and on the recording; and their difference — the pixel noise, small next to the field’s own grid-scale roughness, which is real (the conserved noise).
Infer and select¶
Default settings throughout. The diffusion estimator also measures the variance \(\hat\Lambda\) of the measurement noise — its square root lands near the camera’s 0.005, plus a small floor that is there even without pixel noise (see the ladder at the end) — and the force estimator, seeing noise, switches to its noise-robust variant, which pairs frames whose pixel noise is independent. The dense 34-term fit is badly conditioned: on a spot pattern several monomials nearly coincide — \(V \approx 0\) between the spots, \(U\) and \(V\) locked together inside them — and the Gram matrix is close to singular. PASTIS resolves this by pruning, and the error bars come from the selected model.
from SFI import OverdampedLangevinInference
from SFI.utils.formatting import model_summary
inf = OverdampedLangevinInference(recording)
inf.compute_diffusion_constant()
inf.infer_force_linear(BASIS)
print(f"measurement noise seen by SFI: sqrt(Λ) = {np.sqrt(np.diag(np.asarray(inf.Lambda))).round(4)} "
f"for (U, V); force estimator: '{inf.metadata['force_preset']}'")
print(f"dense 34-term fit: Gram condition number {inf.metadata['force_gram_cond']:.1e}")
inf.sparsify_force(criterion="PASTIS")
inf.compute_force_error()
order = np.argsort(inf.force_support) # candidate order
support = np.asarray(inf.force_support)[order]
coeffs = np.asarray(inf.force_coefficients)[order]
stderr = np.asarray(inf.force_coefficients_stderr)[order]
print(f"PASTIS keeps {len(support)}/{len(labels)} terms; "
f"exactly the Gray-Scott ones: {set(support) == set(support_true)}")
print(model_summary(
labels, coeffs, stderr=stderr, support=support,
coeffs_true=theta_true[support_true], support_true=support_true,
title="Gray-Scott: inferred vs true",
))
measurement noise seen by SFI: sqrt(Λ) = [0.0057 0.0054] for (U, V); force estimator: 'robust'
dense 34-term fit: Gram condition number 5.4e+08
PASTIS keeps 7/34 terms; exactly the Gray-Scott ones: True
Gray-Scott: inferred vs true
────────────────────────────────────────────────────────────────────────────────
# Label Coefficient Std.Err SNR True Sig
────────────────────────────────────────────────────────────────────────────────
0 1→U̇ 3.63703e-02 5.42714e-04 67.0 3.67000e-02 **
1 U→U̇ -3.63201e-02 5.93803e-04 61.2 -3.67000e-02 **
8 UV²→U̇ -9.94925e-01 9.92765e-03 100.2 -1.00000e+00 ***
10 ∇²U→U̇ 1.60136e-01 5.36594e-04 298.4 1.60000e-01 ***
19 V→V̇ -1.04848e-01 2.08841e-03 50.2 -1.01600e-01 **
25 UV²→V̇ 1.02822e+00 1.80699e-02 56.9 1.00000e+00 **
28 ∇²V→V̇ 7.94249e-02 4.01603e-04 197.8 8.00000e-02 ***
────────────────────────────────────────────────────────────────────────────────
7/34 basis functions in support, sig: 7* / 7** / 3*** (|SNR| ≥ 2 / 10 / 100)
(Std.err. reflects sampling error only; discretization bias is not included.)
Zeroed (27): V→U̇, U²→U̇, UV→U̇, V²→U̇, U³→U̇, U²V→U̇, V³→U̇, ∇²V→U̇, ∇U·∇U→U̇, ∇V·∇V→U̇, ∇U·∇V→U̇, ∇⁴U→U̇, ∇⁴V→U̇, 1→V̇, U→V̇, U²→V̇, UV→V̇, V²→V̇, U³→V̇, U²V→V̇, V³→V̇, ∇²U→V̇, ∇U·∇U→V̇, ∇V·∇V→V̇, ∇U·∇V→V̇, ∇⁴U→V̇, ∇⁴V→V̇
The recovered equations, with one-standard-error uncertainties (top); the Pareto front — the best information gain at each model size, with the size each criterion selects (bottom left); and every selected coefficient divided by its true value (bottom right).
Bootstrap: regrow the colony¶
Restart the recovered equations from the four initial drops, with an independent noise realisation, and let them run for the whole 3000 time units — far beyond the four 12.5-unit clips they were learned from.
One subtlety: the estimator treats the noise as white from cell to cell, which conserved noise is not — its spectrum grows as \(|k|^2\). Knowing that structure, the per-cell diffusion \(\hat D\) converts into the continuum amplitude \(\hat\sigma = (\hat D / \langle |k|^2\rangle)^{1/2}\), and the bootstrap uses conserved noise of that amplitude.
k_grid = 2 * np.pi * np.fft.fftfreq(GRID[0], DX)
mean_k2 = 2 * np.mean(k_grid**2) # ⟨|k|²⟩ on the 2D grid
sigma_hat = float(np.sqrt(np.mean(np.diag(np.asarray(inf.diffusion_average))) / mean_k2))
print(f"conserved-noise amplitude: sigma_hat = {sigma_hat:.4f} (true {SIGMA})")
boot = OverdampedProcess(restrict(support),
D=conserved_noise_pbc(sigma=sigma_hat, grid_shape=GRID, dx=DX, n_fields=2))
boot.set_params(theta_F=jnp.asarray(coeffs, dtype=jnp.float32))
boot.set_extras(extras_global=box_extras)
boot.initialize(x0)
key, k_boot = random.split(key)
model = boot.simulate(dt=DT_SHOW, Nsteps=truth.T - 1, key=k_boot,
oversampling=100, # integrator step 0.125, as for the truth
compute_observables=False)
model = TrajectoryCollection.from_arrays(X=np.concatenate([np.asarray(x0)[None], model.to_array()]),
dt=DT_SHOW, extras_global=box_extras)
print(f"Bootstrap: {model.T} frames")
conserved-noise amplitude: sigma_hat = 0.0094 (true 0.01)
Bootstrap: 241 frames
Side by side over the whole run: the hidden truth (left), the camera’s view (centre) and the recovered equations (right). The patterns differ in detail — the noise and the spot divisions are random — but the colony grows the same way.
Two pattern statistics make the comparison quantitative: the mean concentration of \(V\), which grows with the number of spots, and the radially averaged autocorrelation \(C(r)\) of \(V\), whose first maximum past its first zero is the distance between neighbouring spots.
from SFI.utils.plotting import spatial_acorr2d
Xs, Xm = truth.to_array(), model.to_array()
def spot_spacing(X):
r, C = spatial_acorr2d(X[-1, :, 1].reshape(GRID), dx=DX)
beyond = r > r[np.argmax(C < 0)] # past the first zero crossing
return r[beyond][np.argmax(C[beyond])]
for name, X in [("truth", Xs), ("recovered equations", Xm)]:
print(f"{name:>20s}: <V> at t = {t_show[-1]:.0f}: {X[-1, :, 1].mean():.4f}, "
f"spot spacing {spot_spacing(X):.1f}")
r_bins, _ = spatial_acorr2d(Xs[-1, :, 1].reshape(GRID), dx=DX)
print(f"(C(r) is binned in steps of {r_bins[1] - r_bins[0]:.1f} cells)")
truth: <V> at t = 3000: 0.1354, spot spacing 13.4
recovered equations: <V> at t = 3000: 0.1318, spot spacing 12.0
(C(r) is binned in steps of 1.4 cells)
Left: colony growth, with the four analysis clips marked — the recovered equations track the truth over the whole run. Right: \(C(r)\) at the end of the run; the two spot spacings agree to within one radial bin.
Where it breaks¶
How much corruption can the pipeline take? We rerun inference and selection on the last clip alone — a dish full of spots — climbing a ladder of corruptions: first more dead pixels, then more pixel noise on top of 2% dead pixels.
LADDER = [ # (dead-pixel fraction, pixel noise)
(0.02, 0.0), (0.05, 0.0),
(0.02, 0.005), (0.02, 0.01), (0.02, 0.015), (0.02, 0.02),
]
sweep = []
for dead, noise in LADDER:
rec = degrade_spatial_data(clips[-1], downscale=1, noise=noise or None,
data_loss_fraction=dead, stencil_radius=2,
bc="pbc", seed=3)
inf_s = OverdampedLangevinInference(rec)
inf_s.compute_diffusion_constant()
inf_s.infer_force_linear(BASIS)
inf_s.sparsify_force(criterion="PASTIS")
inf_s.compute_force_error()
sweep.append(inf_s)
sup_s = set(np.asarray(inf_s.force_support))
print(f"{100 * dead:.0f}% dead, pixel noise {noise:<5}: "
f"{100 * np.mean(rec.datasets[0].dynamic_mask):4.1f}% of cells fit, "
f"sqrt(Λ) = {np.sqrt(np.diag(np.asarray(inf_s.Lambda))).round(4)}; "
f"{len(sup_s & set(support_true))}/7 true terms, "
f"{len(sup_s - set(support_true))} spurious")
2% dead, pixel noise 0.0 : 27.6% of cells fit, sqrt(Λ) = [0.0028 0.0018]; 7/7 true terms, 0 spurious
5% dead, pixel noise 0.0 : 4.0% of cells fit, sqrt(Λ) = [0.0029 0.0018]; 7/7 true terms, 0 spurious
2% dead, pixel noise 0.005: 27.5% of cells fit, sqrt(Λ) = [0.0057 0.0053]; 7/7 true terms, 0 spurious
2% dead, pixel noise 0.01 : 27.5% of cells fit, sqrt(Λ) = [0.0104 0.0102]; 7/7 true terms, 0 spurious
2% dead, pixel noise 0.015: 27.5% of cells fit, sqrt(Λ) = [0.0153 0.0151]; 7/7 true terms, 19 spurious
2% dead, pixel noise 0.02 : 27.5% of cells fit, sqrt(Λ) = [0.0202 0.02 ]; 2/7 true terms, 14 spurious
Top: which of the 34 candidates PASTIS keeps at each rung — gold for the Gray-Scott terms, pink for spurious ones, an orange frame for a missed true term. Bottom: the seven true coefficients, divided by their true values, with their error bars (values off the scale are drawn as arrows at the edge).
Dead pixels cost data, not the model. At 5% per frame the stencil exclusion leaves only 4% of the cells; the error bars widen (the two \(V\)-equation terms \(V\) and \(UV^2\) land about two of them low), and the seven terms still come back, with no spurious one.
Pixel noise is the breaking factor. On this clip the edge lies between pixel noise 0.01 and 0.015 — 2 to 3% of the spot peak: up to 0.01 PASTIS returns exactly the seven terms, at 0.015 it adds a swarm of spurious ones, and at 0.02 it loses true terms as well. Pixel noise enters inside the candidates: a noisy \(V\) turns \(V^2\) into \((V+\varepsilon)^2\), and every nonlinear term and stencil picks up an errors-in-variables bias that grows with the noise variance. The noise-robust estimator pairs frames whose noise is independent, which removes the noise’s direct contribution, but it cannot undo this distortion of the candidates themselves. On a well-conditioned library the bias would only nudge the coefficients. Here several cubic combinations of \(U\) and \(V\) nearly coincide on the data (the condition number printed above), so past some noise level a wrong combination fits better than the true one — and with hundreds of thousands of rows the improvement is significant: PASTIS keeps the spurious terms, and the coefficients lose their meaning.
More data cannot push this edge back: the bias stays while the error bars shrink, so with more rows the edge moves to lower noise. This is a genuine limit of the linear estimators on nearly collinear polynomial libraries, and the reason the four-clip analysis above uses a camera at half the noise this single clip tolerates.
Thumbnail¶
Total running time of the script: (8 minutes 33.239 seconds)