Note
Go to the end to download the full example code.
Aligning active Brownian particles — interaction kernels from noisy tracks¶
Infer the pair interactions of a population of aligning active
Brownian particles (ABPs) from tracking data — positions and headings
corrupted by localisation noise, with a few detections missing — using a
generic, over-complete dictionary of pair kernels from
SFI.bases.pairs.
Nothing about the kernel shapes is assumed: the dictionary contains exponential–polynomial kernels of several ranges, PASTIS keeps the ones the data support, and the recovered kernels come with confidence bands. The inferred model is then simulated from the first recorded frame and played side by side with the recording, and its collective order — an emergent statistic the fit never used — is compared with the data’s.
Tags
synthetic · overdamped · multi-particle · linear · sparsity
stamp_output()
[Generated: 2026-10-17 23:49]
System: aligning active Brownian particles¶
Each particle carries a position \((x, y)\) and a heading \(\theta\). It swims at speed \(c_0\) along \(\hat e_\theta\), is pushed away from close neighbours by a soft repulsion \(-\varepsilon/(1 + r^2/R_0^2)\,\hat r_{ij}\), and turns toward their headings with a torque \(A\,e^{-r/L_0}\sin(\theta_j - \theta_i)\). Positions diffuse weakly, headings more strongly (rotational noise \(D_\theta\)), in a periodic box.
The rotational noise is chosen close to the onset of collective order: the population is neither disordered nor a rigid flock — its global alignment waxes and wanes as local groups align and lose their common heading. This is also the regime where the alignment interaction is informative: in a fully polarised flock \(\sin(\theta_j - \theta_i) \approx 0\) for every pair and the torque cannot be measured.
from SFI.langevin import OverdampedProcess
N_particles = 60
L = 30.0 # periodic box side
box = jnp.array([L, L])
dt = 0.02
Nsteps = 5000 # 100 time units ≈ 30 rotational decorrelation times
D_xy, D_theta = 0.05, 0.3 # translational / rotational diffusion
theta_true = dict(c0=1.0, eps=2.0, R0=1.0, A=0.5, L0=2.0)
proc = OverdampedProcess(
make_abp_align_psf(dim=3),
D=jnp.diag(jnp.array([D_xy, D_xy, D_theta])),
extras_global={"box": box},
)
proc.set_params(theta_F=theta_true)
key, kx, kth, ksim = random.split(random.PRNGKey(0), 4)
x0 = jnp.concatenate(
[random.uniform(kx, (N_particles, 2)) * L,
random.uniform(kth, (N_particles, 1), minval=-jnp.pi, maxval=jnp.pi)],
axis=1,
)
proc.initialize(x0)
coll_true = proc.simulate(dt=dt, Nsteps=Nsteps, key=ksim)
def polar_order(coll):
"""Polar order parameter |<exp(i theta)>| per frame."""
theta = np.asarray(coll.to_array())[..., 2]
return np.abs(np.exp(1j * theta).mean(axis=1))
phi_true = polar_order(coll_true)
t_frames = np.arange(len(phi_true)) * dt
print(f"{coll_true.T} frames, {coll_true.N} particles; "
f"polar order ranges over [{phi_true.min():.2f}, {phi_true.max():.2f}]")
5000 frames, 60 particles; polar order ranges over [0.00, 0.67]
The polar order parameter \(\varphi = |\langle e^{i\theta}\rangle|\) keeps fluctuating instead of settling. The snapshot shows the most ordered frame (dot on the trace), with particles coloured by heading: a dominant direction is visible, but far from unanimous.
Corrupt the recording¶
Real tracking adds localisation noise to every coordinate — here \(\sigma = 0.05\) on positions and on headings, comparable to the displacement in one frame — and misses detections: 2 % of the particle positions are dropped at random. The masked detections are simply absent from the data; SFI skips every increment and feature that would need them.
sigma = 0.05
coll = coll_true.degrade(noise=sigma, data_loss_fraction=0.02, seed=1)
An over-complete dictionary of pair kernels¶
Three families of features, all built from SFI.bases.pairs:
self-propulsion — the heading vector \(\hat e_\theta\) (
heading_vector());radial forces — \(\phi_k(r)\,\hat r_{ij}\) summed over neighbours (
radial_pair_basis());alignment torques — \(\phi_k(r)\sin(\theta_j-\theta_i)\) on the heading (
angular_pair_basis()).
The radial kernels \(\phi_k(r) = r^n e^{-r/\ell}\) span \(n \in \{0, 1\}\) and \(\ell \in \{0.5, 1, 2, 4\}\) — 17 candidate features in total. The true repulsion (a Lorentzian) is not in the dictionary: the kernels can only approximate it, as with real data.
from SFI.bases.pairs import (
angular_pair_basis,
exp_poly_kernels,
heading_vector,
radial_pair_basis,
)
from SFI.statefunc import Basis
dim = 3 # (x, y, θ)
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_heading = 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_heading, B_repel, B_align])
Inference and model selection¶
A single linear solve, then PASTIS. With noisy tracks the localisation error of frame \(t\) enters both the increment \(\Delta x_t\) and the features evaluated at \(x_t\), and that correlation biases a plain regression. The default settings measure the localisation noise and, finding it, switch to the noise-robust estimators (Stratonovich moments and a shifted Gram), in which the noise realisations of features and increments cancel or are independent.
SFI also warns that the full dictionary is ill-conditioned. That is expected of an over-complete dictionary — kernels of neighbouring ranges overlap so much that the data cannot tell all 17 coefficients apart — and it is exactly what model selection resolves: the few kernels PASTIS keeps are well separated, and their sampling error bars are well defined.
from SFI import OverdampedLangevinInference
inf = OverdampedLangevinInference(coll)
inf.compute_diffusion_constant() # noise-robust estimator (auto)
inf.infer_force_linear(B) # preset="auto"
print(f"localisation noise detected -> preset {inf.metadata['force_preset']!r}")
inf.compute_force_error()
inf.sparsify_force(criterion="PASTIS")
inf.compute_force_error()
inf.compare_to_exact(model_exact=proc, data_exact=coll_true, maxpoints=2000)
inf.print_report()
print(f"\nNMSE(force): predicted {inf.force_predicted_MSE:.1e}, "
f"realised (vs ground truth) {float(inf.NMSE_force):.1e}")
print(f"D_xx = {float(inf.diffusion_average[0, 0]):.3f} (true {D_xy}), "
f"D_θθ = {float(inf.diffusion_average[2, 2]):.3f} (true {D_theta})")
UserWarning: force Gram condition number 2.39e+11 > 1e+06: the basis is ill-conditioned on these data (collinear or badly scaled features); the coefficients and error estimates are unreliable - drop or rescale features, or sparsify.
localisation noise detected -> preset 'robust'
--- StochasticForceInference Report ---
Average diffusion tensor:
[[ 6.3128918e-02 -5.4476922e-04 -3.2498172e-04]
[-5.4476934e-04 6.3402176e-02 1.6862663e-04]
[-3.2498178e-04 1.6862668e-04 2.9875630e-01]]
Measurement noise tensor:
[[ 2.3073119e-03 3.0155852e-06 7.3132210e-06]
[ 3.0155866e-06 2.2984121e-03 -1.9685673e-05]
[ 7.3132210e-06 -1.9685673e-05 2.5228583e-03]]
Force estimated information: 19016.75
Force: estimated normalized mean squared error (sampling only): 0.00013146306484644217
Force Gram condition number: 2.39e+11
Normalized MSE (force): 0.0015
Normalized MSE (diffusion): 0.0293
Force Coefficient Table
──────────────────────────────────────────────────────────────────────────
# Label Coefficient Std.Err SNR Sig
──────────────────────────────────────────────────────────────────────────
0 e_heading 9.89524e-01 5.12576e-03 193.0 ***
1 r^0·exp(-r/0.5) -5.06099e+00 2.95641e-01 17.1 **
6 r^1·exp(-r/1) -8.78166e-01 3.24701e-02 27.0 **
8 r^1·exp(-r/4) -2.66833e-02 1.02023e-03 26.2 **
11 g·r^0·exp(-r/2) 5.67753e-01 2.31896e-02 24.5 **
──────────────────────────────────────────────────────────────────────────
5/17 basis functions in support, sig: 5* / 5** / 1*** (|SNR| ≥ 2 / 10 / 100)
(Std.err. reflects sampling error only; discretization bias is not included.)
Zeroed (12): r^0·exp(-r/1), r^0·exp(-r/2), r^0·exp(-r/4), r^1·exp(-r/0.5), r^1·exp(-r/2), 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)
NMSE(force): predicted 1.3e-04, realised (vs ground truth) 1.5e-03
D_xx = 0.063 (true 0.05), D_θθ = 0.299 (true 0.3)
The Pareto front shows the information gained as terms are added: it rises steeply for the first few features and then plateaus, and PASTIS stops at the plateau. The selected model keeps the self-propulsion, a few radial kernels that together reproduce the repulsion, and a single alignment kernel. The realised error (known here because the data are synthetic) is about an order of magnitude above the predicted sampling error: the remainder is the bias left by the corrupted recording and by the approximate repulsion shape.
The positional diffusion \(D_{xx}\) also comes out high. The noise-robust estimator of \(D\) multiplies consecutive increments, and a persistent drift adds \(\tfrac32 \langle F_x^2\rangle\Delta t = \tfrac34 c_0^2\Delta t \approx 0.015\) to it — an \(O(\Delta t)\) bias that only matters because the swimming is strong compared with the weak positional noise. It is harmless here: the particles’ spreading is dominated by swimming (effective diffusivity \(c_0^2/2D_\theta \approx 1.7\)), and the rotational noise that controls the order is recovered accurately.
Recovered interaction kernels¶
Summing the selected kernels, \(\sum_k c_k \phi_k(r)\), gives the
radial force and the alignment strength as functions of distance, with
95 % confidence bands from the coefficient covariance
(kernel_predict_ci()). The grey zone marks
distances where fewer than 1 % of the observed pairs lie: repulsion
keeps particles apart, so the data say little there and the
reconstruction is an extrapolation.
from SFI.inference import kernel_predict_ci
# Per-block coefficients and covariance (pruned terms are exact zeros).
c_heading, _ = inf.coeff_block(B_heading)
c_repel, cov_repel = inf.coeff_block(B_repel)
c_align, cov_align = inf.coeff_block(B_align)
print(f"self-propulsion c0 = {float(np.ravel(c_heading)[0]):.3f} (true {theta_true['c0']})")
r_eval = np.linspace(0.05, 8.0, 200)
ci_repel = kernel_predict_ci(r_eval, kernels, c_repel, cov_repel)
ci_align = kernel_predict_ci(r_eval, kernels, c_align, cov_align)
true_repel = -theta_true["eps"] / (1 + (r_eval / theta_true["R0"]) ** 2)
true_align = theta_true["A"] * np.exp(-r_eval / theta_true["L0"])
# Pair distances actually sampled (minimum image), from a subset of frames.
Xs = np.asarray(coll.to_array())[::50, :, :2]
dxy = Xs[:, :, None, :] - Xs[:, None, :, :]
dxy -= L * np.round(dxy / L)
r_pairs = np.linalg.norm(dxy, axis=-1)[:, ~np.eye(N_particles, dtype=bool)]
r_low = float(np.percentile(r_pairs[r_pairs < 8.0], 1))
# Alignment strength at a typical neighbour distance, with its 95 % error.
a2 = kernel_predict_ci(np.array([2.0]), kernels, c_align, cov_align)
a2_true = theta_true["A"] * np.exp(-2.0 / theta_true["L0"])
print(f"alignment strength at r = 2: {a2['mean'][0]:.3f} ± {1.96 * a2['std'][0]:.3f} "
f"(true {a2_true:.3f})")
self-propulsion c0 = 0.990 (true 1.0)
alignment strength at r = 2: 0.209 ± 0.017 (true 0.184)
Where pairs are actually sampled, the radial force is reproduced by kernels that are individually quite unlike the Lorentzian. The alignment kernel \(e^{-r/2}\) is in the dictionary and PASTIS picks exactly it, but with an amplitude above the truth by more than its error bar: like the realised force error above, this is a bias left by the corrupted recording, which the sampling error bars do not include.
Bootstrap: does the inferred model reproduce the collective behaviour?¶
The fit only used single-step increments. The polar order, its fluctuations and its time scale are emergent, many-body properties — a genuine prediction. We simulate the inferred model (force and diffusion) from the first recorded frame, for as long as the recording, in a few independent replicas.
proc_boot = inf.simulate_bootstrapped_trajectory(random.PRNGKey(7), simulate=False)
x0_rec = jnp.asarray(coll.to_array()[0]) # first recorded frame
boots = []
for seed in range(4):
proc_boot.initialize(x0_rec)
boots.append(proc_boot.simulate(dt=dt, Nsteps=coll.T, key=random.PRNGKey(100 + seed),
compute_observables=False)) # positions only: saves memory
Side by side, the recording (left; missed detections blink out) and the first replica (right) start from the same configuration and soon part ways — individual trajectories are random, so a bootstrap can only be compared statistically. What should match is the collective behaviour: small groups that align, merge, turn together and break up.
To make “alike” quantitative, compare the polar order of the data with that of the replicas. A single run of 100 time units contains only a few order–disorder excursions, so replicas differ visibly from one another. Because the data are synthetic, we can also run replicas of the true model from the same start: they show how much the order of the recording itself could have fluctuated.
true_reps = []
for seed in range(4):
proc.initialize(x0)
true_reps.append(proc.simulate(dt=dt, Nsteps=Nsteps, key=random.PRNGKey(200 + seed),
compute_observables=False))
half = len(phi_true) // 2 # second halves: after the initial ordering transient
phi_data = polar_order(coll)
phi_boot = np.array([polar_order(c) for c in boots])
phi_ref = np.array([polar_order(c) for c in true_reps])
m_ref, m_boot = phi_ref[:, half:].mean(axis=1), phi_boot[:, half:].mean(axis=1)
print(f"mean polar order (second halves): data {phi_data[half:].mean():.2f}\n"
f" true-model replicas {np.round(m_ref, 2)} (average {m_ref.mean():.2f})\n"
f" inferred-model replicas {np.round(m_boot, 2)} (average {m_boot.mean():.2f})")
mean polar order (second halves): data 0.40
true-model replicas [0.35 0.3 0.49 0.5 ] (average 0.41)
inferred-model replicas [0.48 0.61 0.52 0.47] (average 0.52)
The verdict is instructive. The inferred model reproduces the phenomenology — partial, fluctuating order of the right size and time scale — but its replicas are on average more ordered than the data, whereas the replicas of the true model bracket it. Close to the onset of collective motion, the order is a steep function of the ratio of alignment to rotational noise, so it amplifies the small excess of inferred alignment found above. An emergent statistic near a transition is a far more stringent test than the single-step fit — which is exactly why a bootstrap is worth running on real data, where no ground truth is available to reveal such a bias.
Thumbnail¶
Total running time of the script: (3 minutes 35.353 seconds)