Note
Go to the end to download the full example code.
Multi-experiment ABP inference — shared interactions, per-condition motility¶
Infer one interaction model from several recordings made under different conditions — here three active-particle experiments at different densities and box sizes, whose particles also swim at different speeds (think of different temperatures, fuel or illumination levels).
Each recording is a separate TrajectoryDataset
with its own periodic box in extras_global; the datasets are merged
into one TrajectoryCollection and fitted
jointly. The interaction kernels are shared — they must explain all
three experiments at once — while the self-propulsion speed gets one
coefficient per experiment through
dataset_indicator(). Everything stays linear in the
coefficients, so the fit is a single linear solve followed by
PASTIS. The pooled model is then validated experiment by
experiment, and each recording is replayed side by side with a
simulation of the model collapsed to that condition.
Note
For per-experiment parameters that enter nonlinearly (a
per-condition interaction range, say), the same idea is expressed with
per_dataset_scalar() inside a parametric model fitted
by infer_force().
Dataset pooling and weights are covered in Trajectory data;
the single-experiment version of this system, with noisy tracks, is
Aligning active Brownian particles — interaction kernels from noisy tracks.
Tags
synthetic · overdamped · multi-particle · multi-experiment · linear · sparsity
stamp_output()
[Generated: 2026-10-18 10:19]
Three experiments, one interaction law¶
All experiments share the same aligning-ABP interactions — soft repulsion and short-range alignment (see Aligning active Brownian particles — interaction kernels from noisy tracks) — but differ in particle number, box size and swimming speed \(c_0\). The same interactions then produce three different collective states — from a disordered gas to a polar flock — which is exactly why pooling them constrains the interactions better than any single recording.
from SFI.langevin import OverdampedProcess
dt = 0.02
Nsteps = 2000
D = jnp.diag(jnp.array([0.05, 0.05, 0.3])) # translational / rotational noise
shared = dict(eps=2.0, R0=1.0, A=0.5, L0=2.0) # interaction parameters (shared)
# (label, N particles, box side, swimming speed c0)
experiments = [
("dilute", 10, 30.0, 0.8),
("moderate", 30, 20.0, 1.0),
("crowded", 60, 15.0, 1.3),
]
collections, processes = [], []
key = random.PRNGKey(42)
for label, N, L, c0 in experiments:
key, kx, kth, ksim = random.split(key, 4)
x0 = jnp.concatenate(
[random.uniform(kx, (N, 2)) * L,
random.uniform(kth, (N, 1), minval=-jnp.pi, maxval=jnp.pi)],
axis=1,
)
proc = OverdampedProcess(make_abp_align_psf(dim=3), D=D,
extras_global={"box": jnp.array([L, L])})
proc.set_params(theta_F=dict(c0=c0, **shared))
proc.initialize(x0)
collections.append(proc.simulate(dt=dt, Nsteps=Nsteps, key=ksim))
processes.append(proc)
print(f"{label:>8}: N={N:2d}, box {L:.0f}×{L:.0f}, density {N / L**2:.3f}, c0={c0}")
dilute: N=10, box 30×30, density 0.011, c0=0.8
moderate: N=30, box 20×20, density 0.075, c0=1.0
crowded: N=60, box 15×15, density 0.267, c0=1.3
Shared kernels, per-experiment speed¶
The dictionary is that of the single-experiment demo, with one change:
the heading feature is multiplied by
dataset_indicator(), a one-hot vector that reads the
dataset index the collection injects automatically. The product gives
three self-propulsion features, each active in one experiment only, so
each experiment gets its own fitted speed; the 16 pair-kernel features
are shared.
from SFI.bases import dataset_indicator
from SFI.bases.pairs import angular_pair_basis, exp_poly_kernels, heading_vector, radial_pair_basis
from SFI.statefunc import Basis
dim = 3
kernels = exp_poly_kernels(degrees=[0, 1], lengths=[0.5, 1.0, 2.0, 4.0])
pair_kw = dict(symmetric=True, exclude_self=True, owners="focal",
reducer="sum", return_as="basis")
B_speed = dataset_indicator(len(experiments), dim=dim) * heading_vector(dim=dim, angle_index=2)
B_repel = radial_pair_basis(
kernels, dim=dim, box="extras", spatial_dims=slice(0, 2),
embed_dim=dim, embed_axes=[0, 1],
).dispatch_pairs(**pair_kw)
B_align = angular_pair_basis(
kernels, jnp.sin, dim=dim, angle_index=2, output_index=2,
box="extras", spatial_dims=slice(0, 2),
).dispatch_pairs(**pair_kw)
B = Basis.stack([B_speed, B_repel, B_align])
print(f"{B.n_features} candidate features: {B_speed.n_features} per-experiment, "
f"{B_repel.n_features + B_align.n_features} shared")
19 candidate features: 3 per-experiment, 16 shared
Joint inference¶
Merge the recordings — each keeps its own box — and fit. With
weights="pool" every frame of every experiment counts equally. The
simulated tracks carry no localisation noise, so we ask for the
"clean" estimators directly rather than letting the default settings
test for noise, and estimate \(D\) with the "WeakNoise" stencil,
which is insensitive to the strong swimming drift.
As in the single-experiment demo, the full, deliberately over-complete dictionary is ill-conditioned — see the force Gram condition number in the report below (neighbouring kernels overlap); PASTIS resolves it by keeping a few well-separated kernels.
from SFI import OverdampedLangevinInference
coll = collections[0].merge(collections[1:], weights="pool")
inf = OverdampedLangevinInference(coll)
inf.compute_diffusion_constant(method="WeakNoise") # clean data, strong drift
inf.infer_force_linear(B, preset="clean") # noise-free simulated tracks
inf.compute_force_error()
inf.sparsify_force(criterion="PASTIS")
inf.compute_force_error()
inf.print_report()
--- StochasticForceInference Report ---
Average diffusion tensor:
[[ 5.0249189e-02 1.4884665e-04 9.1796945e-05]
[ 1.4884662e-04 4.9660776e-02 -2.2522893e-04]
[ 9.1796865e-05 -2.2522890e-04 3.0051982e-01]]
Measurement noise tensor:
[[-1.01368329e-04 1.49111356e-05 1.52351595e-05]
[ 1.49111320e-05 -4.05944447e-04 -9.00807026e-06]
[ 1.52351568e-05 -9.00807026e-06 1.84630553e-04]]
Force estimated information: 29066.6171875
Force: estimated normalized mean squared error (sampling only): 0.00010321118486709006
Force Gram condition number: 1.72e+09
Force Coefficient Table
──────────────────────────────────────────────────────────────────────────
# Label Coefficient Std.Err SNR Sig
──────────────────────────────────────────────────────────────────────────
0 ds0·e_heading 7.90538e-01 1.58459e-02 49.9 **
1 ds1·e_heading 9.96251e-01 9.29434e-03 107.2 ***
2 ds2·e_heading 1.29583e+00 6.47514e-03 200.1 ***
4 r^0·exp(-r/1) -2.19390e+00 5.03937e-02 43.5 **
6 r^0·exp(-r/4) -2.15591e-01 1.05403e-02 20.5 **
13 g·r^0·exp(-r/2) 5.06867e-01 9.17184e-03 55.3 **
──────────────────────────────────────────────────────────────────────────
6/19 basis functions in support, sig: 6* / 6** / 2*** (|SNR| ≥ 2 / 10 / 100)
(Std.err. reflects sampling error only; discretization bias is not included.)
Zeroed (13): r^0·exp(-r/0.5), r^0·exp(-r/2), r^1·exp(-r/0.5), r^1·exp(-r/1), r^1·exp(-r/2), r^1·exp(-r/4), g·r^0·exp(-r/0.5), g·r^0·exp(-r/1), g·r^0·exp(-r/4), g·r^1·exp(-r/0.5), g·r^1·exp(-r/1), g·r^1·exp(-r/2), g·r^1·exp(-r/4)
PASTIS keeps the three speeds, a couple of radial kernels and a single alignment kernel — the true \(e^{-r/2}\), with an amplitude within its error bar of the truth (table above). Each experiment’s speed is recovered within its error bar too: the shared interactions are pinned down by all three recordings at once, which is what lets the speeds be separated cleanly.
Per-experiment validation¶
A pooled fit could explain the average while failing one condition. Evaluating the inferred force against the truth separately in each experiment rules this out.
for k, ((label, N, L, c0), coll_k, proc_k) in enumerate(zip(experiments, collections, processes)):
X_k = jnp.asarray(coll_k.to_array())[::10]
extras_k = {"box": jnp.array([L, L]), "dataset_index": k}
F_exact = np.asarray(proc_k.force_sf(X_k, extras=extras_k))
F_inf = np.asarray(inf.force_inferred(X_k, extras=extras_k))
nmse = np.mean((F_exact - F_inf) ** 2) / np.mean(F_exact ** 2)
print(f"{label:>8}: NMSE(force) = {nmse:.4f}")
dilute: NMSE(force) = 0.0003
moderate: NMSE(force) = 0.0004
crowded: NMSE(force) = 0.0002
Reproducing each experiment from the pooled fit¶
simulate_bootstrapped_trajectory(..., dataset=k) collapses the
pooled model to condition \(k\) — its own swimming speed and its
box — and simulates it from that experiment’s first frame, for as long
as the recording.
n_replicas = 3
boots = [
[inf.simulate_bootstrapped_trajectory(random.PRNGKey(10 * k + r), dataset=k)[0]
for r in range(n_replicas)]
for k in range(len(experiments))
]
Top row: the three recordings; bottom row: the inferred model (the first replica of each condition), started from the same frames. Individual trajectories part ways quickly — the dynamics is stochastic — but the collective states match: independent swimmers in the dilute box, transient aligned groups at moderate density, and in the crowded box a polar flock that forms within a few time units. The two crowded flocks need not travel the same way: the direction of a flock is a spontaneously broken symmetry, chosen at random as it forms. All boxes are drawn on the same length scale.
The polar order \(\varphi = |\langle e^{i\theta}\rangle|\), an emergent quantity the fit never used, makes the comparison quantitative. For reference, \(N\) independent random headings give \(\varphi \approx \sqrt{\pi/4N}\) by chance alone.
Dilute: data and replicas sit at that chance level — no collective order.
Crowded: a stable flock, with the same order in the data and in every replica.
Moderate: order well above chance, but it comes and goes on long time scales, so one run of 40 time units is a small sample: the replicas’ mean orders spread widely, and the data lie just above the top of that spread. Only the statistics of many runs could tell a genuine discrepancy here.
def polar_order(c):
theta = np.asarray(c.to_array())[..., 2]
return np.abs(np.exp(1j * theta).mean(axis=1))
t_axis = np.arange(Nsteps) * dt
for k, (label, N, _, _) in enumerate(experiments):
phi_d = polar_order(collections[k])
phi_b = [polar_order(c) for c in boots[k]]
print(f"{label:>8}: mean polar order, data {phi_d.mean():.2f}, "
f"bootstrap replicas {np.round([p.mean() for p in phi_b], 2)} "
f"(random headings: {np.sqrt(np.pi / (4 * N)):.2f})")
dilute: mean polar order, data 0.29, bootstrap replicas [0.3 0.25 0.33] (random headings: 0.28)
moderate: mean polar order, data 0.58, bootstrap replicas [0.33 0.45 0.55] (random headings: 0.16)
crowded: mean polar order, data 0.91, bootstrap replicas [0.91 0.91 0.91] (random headings: 0.11)
Thumbnail¶
Total running time of the script: (2 minutes 41.229 seconds)
🏷 Tags: synthetic, overdamped, multi-particle, multi-experiment, linear, sparsity