Note
Go to the end to download the full example code.
Lotka–Volterra ecosystem — a food web from a few noisy censuses¶
Ecological time series are short, sparse and noisy. How little data does it take to map who inhibits whom in a community? Here, eight replicate cultures of a 6-species Lotka–Volterra community are inoculated at random low densities and counted every two time units, with a 10% counting error: 20 censuses per culture, 160 noisy snapshots in total, taken at an interval as long as the species’ growth time. From these, the parametric force estimator and PASTIS model selection recover the sparse interaction network.
In log-population coordinates \(x_i = \log n_i\) the dynamics read
with growth rates \(r_i\), a sparse interaction matrix \(A\) (\(A_{ij}\) is the effect of species \(j\) on species \(i\)) and demographic noise \(D\). The candidate library has 42 terms — a constant and the six populations \(e^{x_j}\), for each of the six species — and the true model uses 20 of them: 6 growth rates and 14 interactions (6 self-limitations and 8 cross-species couplings).
Tags
synthetic · overdamped · nonlinear · sparsity · ecology
stamp_output()
[Generated: 2026-10-18 18:30]
The community¶
Every species limits itself (negative diagonal of \(A\)); a few off-diagonal couplings encode competition (both negative) or exploitation (one positive, one negative). The positive growth rates and the interactions admit a coexistence equilibrium \(n^\star = -A^{-1} r\) with all six species present.
from SFI import make_sf
from SFI.langevin import OverdampedProcess
dim = 6
r = jnp.array([0.50, 0.65, 0.55, 0.65, 0.58, 0.62]) # growth rates
A = jnp.array([ # A[i, j]: effect of j on i
[-0.90, -0.60, 0.00, 0.00, 0.00, 0.00],
[ 0.00, -0.70, -0.60, 0.00, 0.00, 0.00],
[+0.60, 0.00, -0.90, 0.00, 0.00, -0.40],
[ 0.00, 0.00, 0.00, -0.90, -0.50, 0.00],
[ 0.00, 0.00, 0.00, 0.00, -0.40, -0.60],
[ 0.00, 0.00, -0.40, +0.40, 0.00, -1.00],
])
D0 = 0.002 # demographic noise
def lv_force(x):
"""Lotka–Volterra force in log-population coordinates."""
return r + A @ jnp.exp(x)
proc = OverdampedProcess(make_sf(lv_force, dim=dim, rank=1), D=jnp.eye(dim) * D0)
n_star = jnp.linalg.solve(A, -r)
print("coexistence equilibrium n* =", np.round(np.asarray(n_star), 3))
coexistence equilibrium n* = [0.225 0.496 0.504 0.398 0.584 0.577]
The experiment: eight cultures, twenty censuses each¶
Each culture is seeded with every species at a random 0.1–10% of its
equilibrium abundance and followed for 40 time units. The cultures are
independent replicates of the same process; passing one initial
condition per culture (shape (8, 6)) simulates them together, and
SFI stores them as eight non-interacting trajectories of one dataset.
The simulation runs at a fine time step; the “experiment” then keeps
one census every \(\Delta t = 2\) and adds a 10% counting error
(\(\sigma = 0.1\) in log units) to every count.
n_cultures = 8
duration = 40.0
census_interval = 2.0
counting_noise = 0.10
dt_sim = 0.01
def run_cultures(seed):
"""Simulate `n_cultures` replicate cultures from random low inocula."""
key_seed, key_noise = random.split(random.PRNGKey(seed))
log_fraction = random.uniform(key_seed, (n_cultures, dim),
minval=jnp.log(1e-3), maxval=jnp.log(1e-1))
proc.initialize(jnp.log(n_star) + log_fraction) # one row per culture
return proc.simulate(dt=dt_sim, Nsteps=int(duration / dt_sim),
key=key_noise, oversampling=20)
def census(coll_true, interval, seed):
"""Keep one frame every `interval` and add the counting error."""
return coll_true.degrade(downsample=int(round(interval / dt_sim)),
noise=counting_noise, seed=100 + seed)
coll_true = run_cultures(seed=0)
coll = census(coll_true, census_interval, seed=0)
n_census = coll.T
print(f"{n_cultures} cultures x {n_census} censuses = {n_cultures * n_census} noisy snapshots "
f"(Δt = {census_interval}, σ = {counting_noise})")
8 cultures x 20 censuses = 160 noisy snapshots (Δt = 2.0, σ = 0.1)
Each culture shows the same two phases: a growth phase, where every species multiplies at its own rate (straight lines on the log scale, about threefold between censuses), then saturation at the coexistence equilibrium, where the populations fluctuate by ~10–20% — comparable to the counting error. The growth phase pins the growth rates; the way each species bends away from straight growth as the others become abundant pins the interactions.
Candidate library: a constant plus the six populations¶
In log coordinates the force is linear in the populations
\(e^{x_j}\), so the library is
\(\{1,\; e^{x_1},\; \dots,\; e^{x_6}\}\) — built from the
coordinate primitives with an elementwise exp — vectorised over the
six species: \(7 \times 6 = 42\) candidate terms.
from SFI.bases import ones_basis, x_components
xs = x_components(dim)
X_all = xs[0]
for xi in xs[1:]:
X_all = X_all & xi # (x0, ..., x5) as features
populations = X_all.elementwisemap(jnp.exp, label_fn=lambda s: f"exp({s})")
B = (ones_basis(dim) & populations).vectorize(dim) # 42 force terms
labels = list(B.labels)
theta_true = np.asarray(jnp.vstack((r[None, :], A.T))).ravel() # same order as B
support_true = np.flatnonzero(theta_true)
print(f"{len(labels)} candidate terms, {len(support_true)} in the true model")
42 candidate terms, 20 in the true model
A quick linear fit, and what it says about the sampling¶
The closed-form linear estimator is the fast first pass. The
finite-\(\Delta t\) diagnostic
finite_dt_scale() then measures
\(\Delta t\,\|\nabla \hat F\|\) — how much the force changes
within one census interval. Above about 0.2 the linear estimator’s
finite-\(\Delta t\) corrections are no longer guaranteed, and the
parametric estimator, which integrates the flow across each interval,
is the safe tool.
import SFI
from SFI.diagnostics import finite_dt_scale
inf_lin = SFI.OverdampedLangevinInference(coll)
inf_lin.compute_diffusion_constant()
inf_lin.infer_force_linear(B)
scale = finite_dt_scale(inf_lin)
print(f"linear preset chosen by 'auto': {inf_lin.metadata['force_preset']} "
f"(noise estimate Tr Λ = {float(inf_lin.Lambda_trace):.2f}; true {dim * counting_noise**2:.2f})")
print(f"Δt·|∇F| = {scale['grad_phi_dt']:.2f} (99th percentile {scale['grad_p99_dt']:.2f}) "
f"-> verdict: {scale['verdict']}")
inf_lin.compute_force_error()
inf_lin.sparsify_force(criterion="PASTIS")
inf_lin.compute_force_error()
linear preset chosen by 'auto': clean (noise estimate Tr Λ = -1.00; true 0.06)
Δt·|∇F| = 2.35 (99th percentile 3.13) -> verdict: unreliable
Note which preset "auto" picked: "clean". Its noise detector
reads measurement noise from the anticorrelation of successive
increments, and on these data the steady growth trends correlate
successive increments positively and hide it. The linear fit below is
therefore the clean-data estimator (Itô moments with a trapezoid-rule
Gram); we keep the default, as a user would, and let the comparison
show what it gives.
The parametric estimator¶
infer_force() predicts
each census from the previous one with a Runge–Kutta flow step, models
the counting error explicitly (its level is estimated together with
the force and the demographic noise), and removes the bias the noise
would otherwise cause inside the exponential features. The one
non-default argument is the number of Runge–Kutta substeps per census
interval. The diagnostic above puts \(\Delta t\,\|\nabla \hat F\|\)
well above 1 — the dynamics change substantially within one interval —
so we split each interval into \(\lceil \Delta t\,\|\nabla \hat
F\| \rceil\) substeps (99th percentile over the data), each shorter than
the fastest local time scale \(1/\|\nabla \hat F\|\). This is a
numerical resolution choice, not a tuning knob: beyond it, more
substeps leave the fit unchanged.
n_substeps = int(np.ceil(scale["grad_p99_dt"]))
print(f"n_substeps = {n_substeps}")
inf = SFI.OverdampedLangevinInference(coll)
inf.infer_force(B, n_substeps=n_substeps)
inf.compute_force_error()
inf.sparsify_force(criterion="PASTIS")
inf.compute_force_error()
inf.compare_to_exact(force_exact=proc.force_sf, maxpoints=2000)
inf.print_report()
n_substeps = 4
--- StochasticForceInference Report ---
Average diffusion tensor:
[[ 0.0025565 0.00283424 -0.00021723 0.00042052 0.00105589 0.00175205]
[ 0.00283424 0.0067197 -0.00112066 0.00033449 0.00082333 0.00097519]
[-0.00021723 -0.00112066 0.00472094 0.00254174 0.00221366 0.0020611 ]
[ 0.00042052 0.00033449 0.00254174 0.00417083 0.00113528 0.00141438]
[ 0.00105589 0.00082333 0.00221366 0.00113528 0.00304136 0.00294236]
[ 0.00175205 0.00097519 0.0020611 0.00141438 0.00294236 0.00369833]]
Measurement noise tensor:
[[ 0.01322865 -0.00621094 0.00215162 -0.00132267 0.00099219 -0.00201226]
[-0.00621094 0.00347443 0.00061254 -0.0001183 -0.00067737 -0.0004141 ]
[ 0.00215162 0.00061254 0.00506745 -0.00227316 -0.00045952 -0.00433726]
[-0.00132267 -0.0001183 -0.00227316 0.00702266 -0.00035505 -0.00189484]
[ 0.00099219 -0.00067737 -0.00045952 -0.00035505 0.01036945 -0.00441561]
[-0.00201226 -0.0004141 -0.00433726 -0.00189484 -0.00441561 0.00877315]]
Force estimated information: 1940.315185546875
Force: estimated normalized mean squared error (sampling only): 0.003908701134666855
Normalized MSE (force): 0.0059
Force Coefficient Table
───────────────────────────────────────────────────────────────────
# Label Coefficient Std.Err SNR Sig
───────────────────────────────────────────────────────────────────
0 1·e0 4.86621e-01 1.56375e-02 31.1 **
1 1·e1 6.70937e-01 2.07307e-02 32.4 **
2 1·e2 5.35980e-01 2.02832e-02 26.4 **
3 1·e3 6.64795e-01 1.99232e-02 33.4 **
4 1·e4 5.93699e-01 1.80905e-02 32.8 **
5 1·e5 6.12126e-01 1.93693e-02 31.6 **
6 exp(x0)·e0 -8.93386e-01 4.08653e-02 21.9 **
8 exp(x0)·e2 6.54800e-01 6.79109e-02 9.6 *
12 exp(x1)·e0 -5.68986e-01 2.47019e-02 23.0 **
13 exp(x1)·e1 -6.65226e-01 3.44567e-02 19.3 **
19 exp(x2)·e1 -6.80702e-01 4.06836e-02 16.7 **
20 exp(x2)·e2 -9.32250e-01 4.57588e-02 20.4 **
23 exp(x2)·e5 -3.79036e-01 2.93359e-02 12.9 **
27 exp(x3)·e3 -8.98455e-01 3.87493e-02 23.2 **
29 exp(x3)·e5 4.10015e-01 4.84965e-02 8.5 *
33 exp(x4)·e3 -5.39203e-01 3.10576e-02 17.4 **
34 exp(x4)·e4 -4.24469e-01 2.00291e-02 21.2 **
38 exp(x5)·e2 -3.78152e-01 3.77872e-02 10.0 **
40 exp(x5)·e4 -6.12713e-01 3.18609e-02 19.2 **
41 exp(x5)·e5 -1.02201e+00 4.95493e-02 20.6 **
───────────────────────────────────────────────────────────────────
20/42 basis functions in support, sig: 20* / 18** / 0*** (|SNR| ≥ 2 / 10 / 100)
(Std.err. reflects sampling error only; discretization bias is not included.)
Zeroed (22): exp(x0)·e1, exp(x0)·e3, exp(x0)·e4, exp(x0)·e5, exp(x1)·e2, exp(x1)·e3, exp(x1)·e4, exp(x1)·e5, exp(x2)·e0, exp(x2)·e3, exp(x2)·e4, exp(x3)·e0, exp(x3)·e1, exp(x3)·e2, exp(x3)·e4, exp(x4)·e0, exp(x4)·e1, exp(x4)·e2, exp(x4)·e5, exp(x5)·e0, exp(x5)·e1, exp(x5)·e3
The force, which is what we are after, comes with a predicted error; the realised error against the true model (both printed in the report) is of the same order. The 6×6 demographic-noise and counting-noise matrices printed above are only loosely pinned: over one census interval the counting error (\(2\sigma^2 = 0.02\)) outweighs the demographic noise (\(2D\Delta t = 0.008\)), and 160 snapshots split the two only roughly. Their diagonals against the truth:
sigma_hat = np.sqrt(np.diag(np.asarray(inf.Lambda)))
D_hat = np.diag(np.asarray(inf.diffusion_average))
print(f"counting noise σ per species: {np.round(sigma_hat, 3)} (true {counting_noise})")
print(f"demographic noise D per species: {np.round(D_hat, 4)} (true {D0})")
counting noise σ per species: [0.115 0.059 0.071 0.084 0.102 0.094] (true 0.1)
demographic noise D per species: [0.0026 0.0067 0.0047 0.0042 0.003 0.0037] (true 0.002)
Which terms were found?¶
Both estimators’ selections against the true support, and the relative
error of the 42 coefficients (zeros included) after selection. Basis
labels count species from 0: exp(x0)·e2 is the effect of species 1
on species 3, \(A_{31}\).
from SFI.inference.sparse import overlap_metrics
def recovery(fit):
"""Support recovery (F1, misses, false positives) and coefficient error."""
m = overlap_metrics(list(support_true), list(np.asarray(fit.force_support)))
f1 = 2 * m["TP"] / (2 * m["TP"] + m["FP"] + m["FN"])
coeffs = np.asarray(fit.force_coefficients_full)
err = np.linalg.norm(coeffs - theta_true) / np.linalg.norm(theta_true)
return f1, m["FN"], m["FP"], err
for name, fit in [("linear", inf_lin), ("parametric", inf)]:
f1, fn, fp, err = recovery(fit)
sel = set(np.asarray(fit.force_support).tolist())
print(f"{name:>10}: keeps {len(sel)}/{len(labels)} terms, F1 = {f1:.2f}, "
f"missed {[labels[i] for i in sorted(set(support_true) - sel)]}, "
f"spurious {[labels[i] for i in sorted(sel - set(support_true))]}, "
f"coefficient error {100 * err:.1f}%")
linear: keeps 20/42 terms, F1 = 1.00, missed [], spurious [], coefficient error 9.0%
parametric: keeps 20/42 terms, F1 = 1.00, missed [], spurious [], coefficient error 4.6%
Pareto front and coefficients with error bars¶
Left: the information gained by the best model of each size along the parametric fit’s Pareto front; PASTIS (gold) stops where an extra term no longer pays for itself, while AIC (orange) would keep a few more. Right: the selected coefficients (gold bars, 1-σ error bars) against the truth (orange outlines), with the linear estimator’s selection for comparison (teal diamonds). \(r_i\) are growth rates and \(A_{ij}\) the effect of species \(j\) on species \(i\).
coeffs, cov = inf.coeff_block(slice(0, len(labels)))
stderr = np.sqrt(np.clip(np.diag(cov), 0.0, None))
coeffs_lin, cov_lin = inf_lin.coeff_block(slice(0, len(labels)))
stderr_lin = np.sqrt(np.clip(np.diag(cov_lin), 0.0, None))
The interaction network¶
The off-diagonal couplings drawn as a network: an arrow from \(j\) to \(i\) for every non-zero \(A_{ij}\), its width growing with \(|A_{ij}|\); the ring around each species grows with its self-limitation \(|A_{ii}|\). At this census interval both estimators recover every coupling with no spurious one (see the printed selections above); the parametric coefficients are about twice as accurate.
A_true = np.asarray(A)
A_lin = coeffs_lin.reshape(dim + 1, dim)[1:].T # rows: affected species
A_par = coeffs.reshape(dim + 1, dim)[1:].T
Bootstrap: replaying the experiment with the inferred model¶
Does the selected model reproduce the cultures, not just the coefficients? We restart each culture 20 times from its first census with the inferred force and noise and compare the spread of these replays (median and 10–90% band) with the censuses. The replays are recorded at a fine time step to show the full trajectories between censuses.
boot_proc = inf.simulate_bootstrapped_trajectory(random.PRNGKey(1), simulate=False)
n_replays = 20
first_census = jnp.asarray(coll.to_array()[0]) # (cultures, species)
boot_proc.initialize(jnp.tile(first_census, (n_replays, 1)))
coll_boot = boot_proc.simulate(dt=0.1, Nsteps=int(duration / 0.1), key=random.PRNGKey(2),
oversampling=20)
The replays track the censuses through both phases: the timing and order of the growth spurts, the overshoots, and the equilibrium levels. All replays of a culture start from the same noisy census, so their spread comes from the demographic noise alone; it is widest for species 1, whose slow return to equilibrium lets fluctuations accumulate (and somewhat wider than the truth, since \(\hat D\) is over-estimated).
How coarse, how few? Linear vs parametric¶
Keep the experiment fixed — eight cultures followed for 40 time units, 10% counting error — and vary only how often they are counted: from \(\Delta t = 0.5\) (80 censuses per culture) to \(\Delta t = 8\) (5 censuses). Each setting is repeated on three independent experiments (new inocula, demographic and counting noise), and both estimators run exactly as above, followed by PASTIS.
census_intervals = [0.5, 1.0, 2.0, 4.0, 8.0]
seeds = [0, 1, 2]
cultures = {seed: run_cultures(seed) for seed in seeds}
sweep = {"linear": np.zeros((len(census_intervals), len(seeds), 2)),
"parametric": np.zeros((len(census_intervals), len(seeds), 2))}
D_ratio = np.zeros((len(census_intervals), len(seeds))) # parametric D̂ / D
presets = set() # linear presets picked by "auto"
for a, interval in enumerate(census_intervals):
for b, seed in enumerate(seeds):
data = census(cultures[seed], interval, seed)
lin = SFI.OverdampedLangevinInference(data)
lin.compute_diffusion_constant()
lin.infer_force_linear(B)
presets.add(lin.metadata["force_preset"])
n_sub = int(np.ceil(finite_dt_scale(lin)["grad_p99_dt"]))
lin.sparsify_force(criterion="PASTIS")
par = SFI.OverdampedLangevinInference(data)
par.infer_force(B, n_substeps=n_sub)
par.sparsify_force(criterion="PASTIS")
for name, fit in [("linear", lin), ("parametric", par)]:
f1, fn, fp, err = recovery(fit)
sweep[name][a, b] = f1, err
D_ratio[a, b] = np.mean(np.diag(np.asarray(par.diffusion_average))) / D0
print(f"Δt = {interval:>3} ({data.T:>2} censuses/culture): "
+ "; ".join(f"{name} F1 = {np.round(sweep[name][a, :, 0], 2)}, "
f"error = {np.round(100 * sweep[name][a, :, 1]).astype(int)}%"
for name in sweep)
+ f"; parametric D/D_true = {np.round(D_ratio[a], 1)}")
print(f"linear preset(s) picked by 'auto' across the sweep: {sorted(presets)}")
Δt = 0.5 (80 censuses/culture): linear F1 = [0.9 0.85 0.9 ], error = [63 78 81]%; parametric F1 = [1. 1. 1.], error = [5 3 4]%; parametric D/D_true = [2.3 2.6 2.8]
Δt = 1.0 (40 censuses/culture): linear F1 = [1. 1. 0.92], error = [16 14 47]%; parametric F1 = [1. 1. 1.], error = [5 4 4]%; parametric D/D_true = [1.8 2.1 2.2]
Δt = 2.0 (20 censuses/culture): linear F1 = [1. 1. 1.], error = [9 5 7]%; parametric F1 = [1. 1. 1.], error = [5 4 4]%; parametric D/D_true = [2.1 2.5 2.1]
Δt = 4.0 (10 censuses/culture): linear F1 = [1. 1. 1.], error = [6 7 6]%; parametric F1 = [1. 1. 0.97], error = [ 8 5 22]%; parametric D/D_true = [6.3 6.2 6.4]
Δt = 8.0 ( 5 censuses/culture): linear F1 = [0.78 0.59 0.72], error = [61 77 68]%; parametric F1 = [0. 0.16 0. ], error = [100 96 100]%; parametric D/D_true = [144.5 29.4 147. ]
linear preset(s) picked by 'auto' across the sweep: ['clean']
Reading the sweep (the numbers are printed above):
Dense censuses (\(\Delta t \le 1\), 40–80 per culture): consecutive counts differ mostly by counting error. The parametric estimator models that error and finds the exact network in every run. The linear estimator runs in its clean-data mode throughout (its automatic noise detection is fooled by the growth trends, see the printed presets); the noise costs it missed or spurious couplings and coefficient errors several times larger than the parametric ones.
Coarse censuses (\(\Delta t = 2\)–4, 20–10 per culture): both estimators find the network. The counting error is now small compared with the change between censuses, and the linear estimator’s trapezoid-rule Gram integrates the force across each interval accurately on these smooth growth-then-saturation curves — well beyond the regime the finite-\(\Delta t\) diagnostic certifies. The parametric estimator’s demographic-noise estimate, about twice too large at finer sampling, grows to about six times the truth at \(\Delta t = 4\) (the printed \(\hat D/D\)); this widens its error bars, and PASTIS then drops a weak coupling in one run out of three.
Five censuses per culture (\(\Delta t = 8\)) are too few: 32 census intervals for 42 candidate terms and two noise matrices. The parametric estimator’s error bars become so wide that PASTIS keeps at most a handful of terms, while the linear estimator returns a partly wrong network.
Bottom line: with the parametric estimator, eight cultures counted 20 to 80 times each recovered the full network in every run, and counted 10 times in two runs out of three. The linear estimator needs the populations to change by more than the counting error between censuses; when they do, it is a fast and accurate first pass.
Thumbnail¶
The inferred network, for the gallery grid.
Total running time of the script: (5 minutes 29.655 seconds)