Nonreciprocal active particles at scale — 10 000 particles

synthetic overdamped multi-particle linear large-scale nonreciprocal

Infer three pairwise interaction kernels — repulsion, alignment and pursuit — from the tracks of 10 000 self-propelled particles whose interactions are nonreciprocal: each particle reacts to what it sees ahead of it, not to what is behind. Pursuit and alignment organise the swarm into worm-like streams of chevrons that sweep through the box — the kind of structure seen in tracked swarms of cells, insects or robots.

At this scale a list of all \(N^2/2 = 5\times 10^7\) pairs is out of reach. Both the simulation and the inference run on neighbour lists (CSR format) rebuilt every few steps; because the interaction kernels have a finite range, the lists capture every interacting pair exactly.

The page walks through:

  1. composing the force from the geometric primitives of SFI.bases.pairs — vision_gate() for the nonreciprocal coupling, particle_heading() for pursuit;

  2. simulation with Verlet neighbour lists (simulate_chunked());

  3. an overcomplete inference basis — compactly supported radial kernels of several ranges for each interaction;

  4. linear force inference on short stretches of the recording, each with its own neighbour list;

  5. the recovered kernels, with confidence bands and the range of pair distances the data actually sample;

  6. a bootstrap: the inferred model restarted from a frame of the data, played side by side with it, and compared on collective statistics the fit never used.

Tags

synthetic · overdamped · multi-particle · linear · large-scale · nonreciprocal

stamp_output()
[Generated: 2026-10-18 12:34]

System: nonreciprocal, vision-gated active particles

Each particle has state \((x, y, \theta)\) and moves at speed \(c_0\) along its heading \(\hat e_\theta\). Three pair interactions act on top of this self-propulsion; two of them are filtered by a vision cone \(v(\delta) = (1 + \cos\delta)/2\), where \(\delta\) is the bearing of the neighbour relative to the focal particle’s heading — so \(i\) may react to \(j\) while \(j\) ignores \(i\):

  • Repulsion: \(-\varepsilon\, b_{R}(r)\,\hat r_{ij}\)

  • Alignment (a torque on \(\theta_i\)): \(A\, v(\delta)\, \sin(\theta_j-\theta_i)\, b_{L_a}(r)\)

  • Pursuit: \(P\, v(\delta)\, b_{L_p}(r)\, \hat e_{\theta_j}\) — a particle is carried along by the neighbours it sees ahead of it.

The radial profiles are compact bumps \(b_\ell(r) = (1 - r/\ell)^2\) for \(r < \ell\), zero beyond: every interaction vanishes smoothly at a finite range, the largest of which, \(L_a = 4\), is the interaction cutoff. All three components of the state receive white noise of strength \(D\).

N_particles = 10_000
density = 0.15                                   # particles per unit area
Lx = Ly = float(np.sqrt(N_particles / density))  # periodic box, ≈ 258
dt = 0.02
D_iso = 0.02
box = jnp.array([Lx, Ly])
box_np = np.array([Lx, Ly])

theta_F_exact = dict(
    c0=1.0,              # self-propulsion speed
    eps=8.0, R0=1.0,     # repulsion strength, range
    A=1.0, La=4.0,       # alignment strength, range
    P=0.75, Lp=3.0,      # pursuit strength, range
)
cutoff = 4.0             # interaction range: every kernel vanishes beyond r = 4

Building the simulation force

Each primitive of SFI.bases.pairs is one geometric factor — a direction, a gate, a radial profile — and products of them are dispatched over the pairs of a CSR neighbour list stored in the extras (dispatch_pairs_from_extras).

from SFI.bases.pairs import (
    angle_coupling,
    compact_kernels,
    heading_vector,
    pair_direction,
    parametric_radial_kernel,
    particle_heading,
    scalar_pair_basis,
    vision_gate,
)
from SFI.statefunc import Basis

dim = 3                                    # (x, y, θ) per particle
xy = dict(box="extras", spatial_dims=slice(0, 2))

e_heading = heading_vector(dim=dim, angle_index=2)                      # ê_θ
e_ij = pair_direction(dim=dim, embed_dim=dim, embed_axes=[0, 1], **xy)  # r̂_ij
sin_dtheta = angle_coupling(jnp.sin, dim=dim, angle_index=2)            # sin(θ_j − θ_i), on θ
e_j = particle_heading(1, dim=dim, angle_index=2)                       # ê_θj
vision = vision_gate(lambda d: (1 + jnp.cos(d)) / 2, dim=dim, angle_index=2, **xy)


def bump(r, ell):
    return jnp.where(r < ell, (1 - r / ell) ** 2, 0.0)


k_repel = parametric_radial_kernel(lambda r, p: -p["eps"] * bump(r, p["R0"]),
                                   params={"eps": (), "R0": ()}, dim=dim, **xy)
k_align = parametric_radial_kernel(lambda r, p: p["A"] * bump(r, p["La"]),
                                   params={"A": (), "La": ()}, dim=dim, **xy)
k_pursuit = parametric_radial_kernel(lambda r, p: p["P"] * bump(r, p["Lp"]),
                                     params={"P": (), "Lp": ()}, dim=dim, **xy)

csr = dict(indptr_key="indptr", indices_key="indices")
F_sim = (
    e_heading.to_psf(coeff_key="c0")
    + (k_repel * e_ij).dispatch_pairs_from_extras(**csr, return_as="psf")
    + (k_align * vision * sin_dtheta).dispatch_pairs_from_extras(**csr, return_as="psf")
    + (k_pursuit * vision * e_j).dispatch_pairs_from_extras(**csr, return_as="psf")
)

Simulation with Verlet neighbour lists

simulate_chunked() integrates rebuild_every steps with a fixed neighbour list, then rebuilds it (with scipy.spatial.cKDTree) from the current positions. The list holds every pair closer than cutoff + skin. Between two rebuilds a pair distance shrinks by at most twice the largest single-particle displacement, so as long as no particle moves farther than skin / 2, every pair that comes within the cutoff is already on the list and the simulated force is exact — the Verlet criterion. Particles swim at \(c_0 = 1\) and pursuit makes the streams faster; we rebuild every 10 steps (0.2 time units) with a skin of 3, i.e. we allow speeds up to 7.5. The simulator checks the criterion at every rebuild and would warn if it failed.

from SFI.langevin import OverdampedProcess
from SFI.langevin.chunked import simulate_chunked
from SFI.utils.neighbors import make_neighbor_extras

rebuild_every = 10
skin = 3.0
n_relax, n_record = 1250, 750          # 25 time units to form streams, then 15 recorded

key = random.PRNGKey(0)
key, kx, kth = random.split(key, 3)
x0 = jnp.concatenate([random.uniform(kx, (N_particles, 2)) * box,
                      random.uniform(kth, (N_particles, 1), minval=-jnp.pi, maxval=jnp.pi)],
                     axis=1)

proc = OverdampedProcess(F_sim, D=D_iso, extras_global={
    "box": box, **make_neighbor_extras(np.asarray(x0[:, :2]), cutoff + skin, box_np)})
proc.set_params(theta_F=theta_F_exact)
proc.initialize(x0)

chunk_kw = dict(cutoff=cutoff, skin=skin, box=box_np, rebuild_every=rebuild_every,
                spatial_dims=slice(0, 2))
coll = simulate_chunked(proc, dt=dt, Nsteps=n_relax + n_record, key=random.PRNGKey(1), **chunk_kw)

X_all = np.concatenate([np.asarray(x0)[None], coll.to_array(axis="time")])   # frame k = step k
print(f"{N_particles} particles in a {Lx:.0f} × {Ly:.0f} periodic box, "
      f"{X_all.shape[0] - 1} steps of dt = {dt}")
10000 particles in a 258 × 258 periodic box, 2000 steps of dt = 0.02

The swarm

Starting from random positions and headings, the particles organise within a few tens of time units into long-lived, worm-like streams made of chevron-shaped groups, each travelling along its stream. The snapshot is the last frame of the run, coloured by heading angle; the dashed frame marks the region shown in the bootstrap movie below.


N = 10000,  t = 40  (colour = heading)

How the streams form: the whole run, one frame every 0.16 time units.


Overcomplete inference basis

For inference we keep the geometric primitives but replace each parametric profile by a generic dictionary of compact bumps \((1 - r/\ell)^2\) (compact_kernels()) at ranges \(\ell = 1, 2, 3, 4\) — the largest equals the cutoff, so the same neighbour lists serve the inference. The alignment dictionary starts at \(\ell = 2\): inside the streams, neighbours closer than 1 are almost exactly parallel, so a range-1 alignment bump would rest on almost no signal (its column of the Gram matrix is tiny, and SFI warns that the fit is ill-conditioned).

ranges = (1.0, 2.0, 3.0, 4.0)
kernels = [k for ell in ranges for k in compact_kernels(degrees=[0], cutoff=ell)]
kernels_align = kernels[1:]                                        # ℓ = 2, 3, 4

B_repel = (scalar_pair_basis(kernels, dim=dim, **xy) * e_ij
           ).dispatch_pairs_from_extras(**csr, return_as="basis")
B_align = (scalar_pair_basis(kernels_align, dim=dim, **xy) * vision * sin_dtheta
           ).dispatch_pairs_from_extras(**csr, return_as="basis")
B_pursuit = (scalar_pair_basis(kernels, dim=dim, **xy) * vision * e_j
             ).dispatch_pairs_from_extras(**csr, return_as="basis")
B_full = Basis.stack([e_heading, B_repel, B_align, B_pursuit])
print(f"{B_full.n_features} features: self-propulsion + {B_repel.n_features} repulsion "
      f"+ {B_align.n_features} alignment + {B_pursuit.n_features} pursuit kernels")
12 features: self-propulsion + 4 repulsion + 3 alignment + 4 pursuit kernels

Fitting on short stretches, each with its own neighbour list

Real tracking data come without neighbour lists, so we build them from the data the way the simulator did: we cut the recorded stretch into intervals of 10 steps, build each interval’s list from its first frame with radius cutoff + skin, and check the Verlet criterion on the tracks themselves. Because the kernels vanish at the cutoff and no pair can enter their range unseen, the pair features of every interval are continuous and exact — the lists are invisible to the estimator (see Cutoffs and neighbour lists). Lists are padded to a common length so that one compiled program serves every interval.

from SFI import OverdampedLangevinInference
from SFI.utils.neighbors import build_neighbor_csr, pad_neighbor_csr

starts = range(t_start, t_start + n_record, 5 * rebuild_every)    # one interval in five
lists = [build_neighbor_csr(X_all[s, :, :2], cutoff + skin, box_np) for s in starts]
max_nnz = max(len(indices) for _, indices in lists)

intervals, max_disp = [], 0.0
for s, (indptr, indices) in zip(starts, lists):
    X_k = X_all[s:s + rebuild_every + 1]                           # 11 frames, 10 steps
    disp = np.abs(X_k[:, :, :2] - X_k[0, :, :2])
    disp = np.minimum(disp, box_np - disp)                         # periodic wrap
    max_disp = max(max_disp, float(np.sqrt((disp ** 2).sum(-1)).max()))
    indptr, indices = pad_neighbor_csr(indptr, indices, max_nnz)
    intervals.append((X_k, {"box": box, "indptr": jnp.asarray(indptr),
                            "indices": jnp.asarray(indices)}))


def interval_collection(stride=1):
    """All intervals in one collection, keeping every ``stride``-th frame."""
    parts = [TrajectoryCollection.from_arrays(X=X_k[::stride], dt=stride * dt, extras_global=eg)
             for X_k, eg in intervals]
    return parts[0].concat(parts[1:])


coll_fit = interval_collection()
print(f"{len(intervals)} intervals × {rebuild_every} steps × {N_particles} particles")
print(f"largest displacement within an interval: {max_disp:.2f}  (skin / 2 = {skin / 2})")
15 intervals × 10 steps × 10000 particles
largest displacement within an interval: 1.00  (skin / 2 = 1.5)

The tracks are noise-free synthetic data, so we use the "clean" preset (Itô moments with the trapeze Gram matrix). The drift is strong compared with the noise over one step, so the diffusion constant is measured with the "WeakNoise" estimator.

inf = OverdampedLangevinInference(coll_fit)
inf.compute_diffusion_constant(method="WeakNoise")
inf.infer_force_linear(B_full, preset="clean")
inf.compute_force_error()
inf.compare_to_exact(force_exact=F_sim.bind(theta_F_exact), maxpoints=4000)

c0_hat, c0_cov = inf.coeff_block(e_heading)
print(f"D (x, y, θ)    = {np.diag(np.asarray(inf.diffusion_average)).round(4)}   (true {D_iso})")
print(f"c0             = {float(np.ravel(c0_hat)[0]):.4f} ± "
      f"{float(np.sqrt(np.ravel(c0_cov)[0])):.4f}   (true {theta_F_exact['c0']})")
print(f"predicted NMSE = {inf.force_predicted_MSE:.1e}   (sampling error, from the data alone)")
print(f"realised NMSE  = {float(inf.NMSE_force):.1e}   (against the true force)")
D (x, y, θ)    = [0.0199 0.0199 0.0199]   (true 0.02)
c0             = 1.0024 ± 0.0021   (true 1.0)
predicted NMSE = 3.9e-06   (sampling error, from the data alone)
realised NMSE  = 8.6e-06   (against the true force)

With 1.5 million particle displacements the sampling error is tiny — that is what the predicted NMSE measures, from the data alone. The error against the true force is about twice as large: a small systematic part remains, because the linear estimator is exact only as \(\Delta t \to 0\) and inside the dense chevrons the repulsion between neighbours changes appreciably within one frame. Both are well below a percent of the force.

Recovered interaction kernels

Each kernel is reconstructed as \(\sum_k c_k \phi_k(r)\) with a 95% confidence band from the coefficient covariance (kernel_predict_ci()). The grey histogram shows how often each pair distance occurs in the data. Repulsion keeps the particles apart, so almost no pair is closer than about 0.5: below that the kernels are an extrapolation of the dictionary. The bands widen there, but they only account for sampling noise, not for how the dictionary chooses to extrapolate — read the kernels where the histogram has pairs.

from SFI.inference import kernel_predict_ci

r_eval = np.linspace(0.0, cutoff, 241)
ci = {
    "repel": kernel_predict_ci(r_eval, kernels, *inf.coeff_block(B_repel)),
    "align": kernel_predict_ci(r_eval, kernels_align, *inf.coeff_block(B_align)),
    "pursuit": kernel_predict_ci(r_eval, kernels, *inf.coeff_block(B_pursuit)),
}
p = theta_F_exact
true_kernels = {
    "repel": -p["eps"] * np.asarray(bump(r_eval, p["R0"])),
    "align": p["A"] * np.asarray(bump(r_eval, p["La"])),
    "pursuit": p["P"] * np.asarray(bump(r_eval, p["Lp"])),
}
Repulsion, Alignment (vision-gated), Pursuit (vision-gated)

Residual diagnostics

Standardised residuals pooled over all particles and the three state components — a check of the fit that needs no ground truth.

from SFI.diagnostics import assess

report = assess(inf, level="standard")
report.print_summary()
=== SFI diagnostics report ===
backend  : linear
regime   : OD
n_obs    : 1500000  n_particles: 10000  d: 3
level    : standard

-- Residuals --
  mean = -0.0002  std = 0.9821  skew = -0.000  kurt-3 = +0.002  (n=4500000)
  ✗ normality ks                 stat=0.00451   p=4.19e-80
  ✗ autocorr  ljung_box          stat=40.4      p=0.00442
  ✓ autocorr  ljung_box_squared  stat=16.4      p=0.692
  predicted NMSE = 3.87e-06  χ²-excess NMSE = 0.00866 (≤ 0.0099 at 95%)  χ² z = +11.40 (|z|>5 ⇒ bias)

-- Finite sampling interval -- unavailable: interacting (particles_input) bases are not supported

-- Flags --
  ! [normality/ks] p=4.19e-80 < 0.01 — non-Gaussian residuals — rare events not captured by the basis, or a non-Gaussian noise structure
  ! [autocorr/ljung_box] p=4.42e-03 < 0.01 — missing time-correlated feature — widen the basis; if it persists, suspect coarse sampling: the parametric estimator (infer_force) extends the usable Δt
  ! [mse_consistency] residual chi^2 excess z = +11.40 (mean |z|^2 = 2.894 vs expected 2.876); if all of it were force error it would imply NMSE ~ 0.0087 (2.2e+03x the predicted 3.9e-06): a scale for the excess, not a measured force error — residuals larger than the noise model predicts: model bias or finite-Δt effects; on experimental data usually measurement noise: consider the parametric estimator (infer_force)

With 4.5 million residuals the tests resolve tiny departures. Every residual moment is within 2% of \(\mathcal N(0, 1)\); the standard deviation sits slightly below 1, as expected at a finite frame interval — the χ² line’s expectation accounts for that, the normality test, which compares with exactly \(\mathcal N(0, 1)\), does not. The χ² line compares the residual variance with its expectation at the sampled \(\Delta t\), computed to first order in \(\Delta t\). A fraction-of-a-percent excess is enough for a large z-score at this sample size, and the NMSE the report converts it to is a scale for the excess, not a measured error: the comparison with the true force above shows a realised error about twice the predicted one, not a thousand times.

Is the excess a missing interaction or the finite frame interval? A missing interaction biases the fit whatever the frame interval; a discretisation effect grows with it. Refitting the same intervals on every other frame is a check that needs no ground truth — useful here because the report’s automatic finite-\(\Delta t\) scale is not available for interacting bases:

inf_2dt = OverdampedLangevinInference(interval_collection(stride=2))
inf_2dt.compute_diffusion_constant(method="WeakNoise")
inf_2dt.infer_force_linear(B_full, preset="clean")
inf_2dt.compute_force_error()
inf_2dt.compare_to_exact(force_exact=F_sim.bind(theta_F_exact), maxpoints=4000)
report_2dt = assess(inf_2dt, level="standard")

for label, fit, rep in [("Δt ", inf, report), ("2Δt", inf_2dt, report_2dt)]:
    chi2 = rep.residuals["mse_consistency"]
    excess = chi2["mean_mahalanobis_norm"] / chi2["expected_mahalanobis_norm"] - 1
    print(f"frame interval {label}:  χ² excess {100 * excess:+.2f}% (z = {chi2['excess_z']:+.0f})   "
          f"predicted NMSE {fit.force_predicted_MSE:.1e}   realised NMSE {float(fit.NMSE_force):.1e}")
frame interval Δt :  χ² excess +0.62% (z = +11)   predicted NMSE 3.9e-06   realised NMSE 8.6e-06
frame interval 2Δt:  χ² excess +2.24% (z = +25)   predicted NMSE 3.9e-06   realised NMSE 1.4e-05

Doubling the frame interval more than triples the χ² excess, and the realised error grows while the predicted sampling error does not: the excess comes from the finite frame interval — inside the dense chevrons the steep repulsion between neighbours changes within one frame — not from a missing interaction. At the recorded frame rate the resulting bias is a fraction of a percent of the force.

Bootstrap: does the inferred model make the same swarm?

An inferred model is a simulator. We restart it from the first frame of the recorded stretch — with the same neighbour-list machinery — and run it for the same 15 time units.

proc_boot = inf.simulate_bootstrapped_trajectory(random.PRNGKey(2), simulate=False)
proc_boot.set_extras(extras_global={
    "box": box, **make_neighbor_extras(X_all[t_start, :, :2], cutoff + skin, box_np)})
proc_boot.initialize(jnp.asarray(X_all[t_start]))
coll_boot = simulate_chunked(proc_boot, dt=dt, Nsteps=n_record, key=random.PRNGKey(3), **chunk_kw)

X_data = X_all[t_start:t_start + n_record + 1]                    # the same frames of the data
X_boot = np.concatenate([X_all[t_start][None], coll_boot.to_array(axis="time")])

The data (left) and the inferred model (right), in the region framed in the snapshot above, one frame every 0.06 time units. Both start from the same configuration. The large streams persist in both runs while the details soon part ways — individual trajectories are random — but the two should look alike: the same chevrons, moving at the same speeds.


To make “alike” quantitative we compare, over the second half of both runs, three collective statistics that the fit never targeted: the pair correlation \(g(r)\) — how particles pack inside the chevrons; the alignment \(\langle\cos(\theta_i-\theta_j)\rangle\) of pairs at distance \(r\) — how far orientational order reaches along the streams; and the distribution of particle speeds, measured over 0.2 time units — pursuit lets a particle swim faster than \(c_0\) when it follows others.


Pair correlation, Pair alignment, Particle speeds

The inferred model reproduces all three: how neighbours pack inside the chevrons (the peaks of \(g(r)\)), how far orientational order reaches along the streams, and the speeds. Most particles move well faster than \(c_0 = 1\) (dotted line; the measured speed also contains a small diffusive part) because they are carried along by the neighbours they pursue — and the inferred pursuit kernel reproduces the whole distribution, tail included.

Thumbnail

Total running time of the script: (10 minutes 53.215 seconds)

🏷 Tags: synthetic, overdamped, multi-particle, linear, large-scale, nonreciprocal

Gallery generated by Sphinx-Gallery