Note
Go to the end to download the full example code.
Home ranges in a shared landscape, from noisy gappy data¶
Four tracked agents roam overlapping territories crossed by winding river valleys. From their noisy, gappy, positions-only tracks we ask: where does each agent live — the centre, size and orientation of its home range — how strongly do they avoid each other, and how much does the terrain steer them?
Each agent \(i\) is tethered to its own anchor \(\mathbf{x}^0_i\) by its own tensor stiffness \(\mathsf{A}_i\) (an ellipse, not a circle); agents repel one another; and all feel the slope of a known topographic map \(h\):
Everything stays linear in the parameters: expanding \(-\mathsf{A}_i(\mathbf{x}-\mathbf{x}^0_i) = -\mathsf{A}_i\mathbf{x} + \mathbf{c}_i\), we fit \((\mathsf{A}_i, \mathbf{c}_i)\) and recover the anchor \(\mathbf{x}^0_i = \mathsf{A}_i^{-1}\mathbf{c}_i\); the known map enters as one fixed feature \(-\nabla h\) with a shared coupling \(k\). The fit is the noise-aware parametric estimator, checked against ground truth, by the residual diagnostics, and by a bootstrap simulation.
Tags
synthetic · underdamped · multi-particle · 2D · per-particle
stamp_output()
[Generated: 2026-10-18 18:44]
A colony in a river landscape¶
N = 4 agents. Each stiffness tensor \(\mathsf{A}_i\) has its
own eigenvalues and tilt, and the anchors are close enough for the
ranges to overlap. The map \(h(\mathbf{x})\) carves two
meandering river valleys — Gaussian channels whose centrelines wind
sinusoidally, with structure finer than a home range.
import SFI
from SFI.bases import V, identity_matrix_basis
from SFI.bases.pairs import gaussian_kernels, radial_pair_basis
from SFI.langevin import UnderdampedProcess
from SFI.statefunc import make_basis
N, d = 4, 2
eigs = np.array([[1.4, 0.5], [0.45, 1.3], [1.1, 0.4], [0.6, 1.0]])
tilts = np.array([0.3, 1.1, -0.6, 2.0])
A_true = np.zeros((N, d, d))
for i in range(N):
c, s = np.cos(tilts[i]), np.sin(tilts[i])
R = np.array([[c, -s], [s, c]])
A_true[i] = R @ np.diag(eigs[i]) @ R.T
anchors = np.array([[0.0, 0.0], [1.6, 0.5], [0.7, 1.7], [-1.0, 1.2]])
gamma_true, k_rep, ell, D_true, k_topo = 1.6, -0.4, 0.7, 0.18, 0.6 # k_rep<0 ⇒ repulsive
# Known topography h: two meandering Gaussian valleys along a tilted axis.
_ang = 0.6
_t_hat = jnp.array([np.cos(_ang), np.sin(_ang)]) # along-valley axis
_n_hat = jnp.array([-np.sin(_ang), np.cos(_ang)]) # across-valley axis
_chans = ((0.55, 0.9, 1.1, 0.10, -0.55), # (depth, wavelength, phase,
(0.40, 1.3, -0.7, 0.09, 0.75)) # width, centre offset)
_MEANDER = 0.35 # centreline amplitude
def grad_h(x):
u = jnp.dot(x, _t_hat) # along-valley
vperp = jnp.dot(x, _n_hat) # across-valley
G = jnp.zeros(2)
for depth, L, ph, wd, offc in _chans:
phase = 2.0 * jnp.pi * u / L + ph
cu = offc + _MEANDER * jnp.sin(phase) # winding centreline
dcu = _MEANDER * (2.0 * jnp.pi / L) * jnp.cos(phase)
s = vperp - cu
g = jnp.exp(-0.5 * (s / wd) ** 2)
G = G + depth * (s / wd**2) * g * (_n_hat - dcu * _t_hat)
return G
def topo_height(xy): # for plotting the landscape
th, nh = np.asarray(_t_hat), np.asarray(_n_hat)
u, vperp = xy @ th, xy @ nh
H = np.zeros(xy.shape[0])
for depth, L, ph, wd, offc in _chans:
cu = offc + _MEANDER * np.sin(2.0 * np.pi * u / L + ph)
H -= depth * np.exp(-0.5 * ((vperp - cu) / wd) ** 2)
return H
The force basis: 5N + 3 linear features¶
SFI’s built-in bases are shared by all particles; individual
coefficients need one custom brick — the only custom code on this
page. make_basis() reads each agent’s id from its
per-particle extras and emits five features (three for the symmetric
tensor, two for \(\mathbf{c}_i\)) that are non-zero only for that
agent. Friction, a Gaussian pair repulsion and the landscape slope
\(-\nabla h\) are shared.
def home(x, *, extras):
i = extras["home_id"]
x0c, x1c = x[0], x[1]
blocks = jnp.stack([
jnp.array([-x0c, 0.0]), # A_xx
jnp.array([0.0, -x1c]), # A_yy
jnp.array([-x1c, -x0c]), # A_xy
jnp.array([1.0, 0.0]), # c_x
jnp.array([0.0, 1.0]), # c_y
], axis=1)
onehot = (jnp.arange(N) == i).astype(x.dtype)
return (onehot[None, :, None] * blocks[:, None, :]).reshape(d, 5 * N)
B_home = make_basis(home, dim=d, rank=1, n_features=5 * N,
extras_keys=("home_id",), particle_extras=("home_id",),
labels=[f"{p}[{i}]" for i in range(N) for p in ("Axx", "Ayy", "Axy", "cx", "cy")])
B_friction = V(dim=d)
B_repulsion = radial_pair_basis(gaussian_kernels([ell]), dim=d).dispatch_pairs()
B_landscape = make_basis(lambda x: (-grad_h(x))[:, None], dim=d, rank=1, n_features=1,
labels=["-grad h"])
B = B_home & B_friction & B_repulsion & B_landscape
Simulate, then corrupt the recording¶
The recording gets Gaussian localisation noise and 3% of the positions are dropped. The relevant scale for the noise is the displacement per frame, not the range size: velocities and accelerations are differences of positions, so the noise enters the acceleration as \(\sigma/\Delta t^2\).
theta_well = []
for i in range(N):
A, x0 = A_true[i], anchors[i]
c = A @ x0
theta_well += [A[0, 0], A[1, 1], A[0, 1], c[0], c[1]]
theta_true = jnp.asarray(theta_well + [-gamma_true, k_rep, k_topo])
proc = UnderdampedProcess(B, D=D_true, theta_F=theta_true)
proc.set_extras(extras_local={"home_id": jnp.arange(N)})
proc.initialize(jnp.asarray(anchors), v0=jnp.zeros((N, d)))
coll_clean = proc.simulate(
dt=0.02, Nsteps=12000, key=random.PRNGKey(0), oversampling=8, prerun=200,
)
sigma_loc = 0.008 # localisation noise (std per coordinate)
coll = coll_clean.degrade(noise=sigma_loc, data_loss_fraction=0.03, seed=3)
dt = coll.dt
X_clean = coll_clean.to_array() # (T, N, d), ground truth (for the comparison only)
spread = float(X_clean.std(axis=0).mean())
step = float(np.sqrt(np.mean(np.diff(X_clean, axis=0) ** 2)))
print(f"{coll.T} frames; range size ~{spread:.2f}; displacement per frame ~{step:.4f}")
print(f"localisation noise σ = {sigma_loc} (~{sigma_loc / step:.1f}× the per-frame step)")
12000 frames; range size ~0.39; displacement per frame ~0.0067
localisation noise σ = 0.008 (~1.2× the per-frame step)
Left: the whole recording on the map (river beds bright). Right: a close-up of one agent over 200 frames — the observed positions (dots) scatter around the true path by as much as it advances per frame.
Noise-aware parametric fit¶
At this noise level the linear estimator is overwhelmed; the
parametric infer_force()
models the noise and estimates the diffusion and the noise level
itself. For the bootstrap below we also fit an isotropic diffusion
\(D\,\mathsf{I}\) (the motion is isotropic, and a full matrix
would add a poorly constrained direction).
inf = SFI.UnderdampedLangevinInference(coll)
inf.infer_force(B)
inf.compute_force_error()
inf.infer_diffusion(identity_matrix_basis(d))
# Each agent's tensor and anchor, from its five coefficients.
c_hat = np.asarray(inf.force_coefficients).ravel()
s_hat = np.asarray(inf.force_coefficients_stderr).ravel()
A_hat = np.zeros((N, d, d))
x0_hat = np.zeros((N, d))
for i in range(N):
a, b, cc, cx, cy = c_hat[5 * i:5 * i + 5]
A_hat[i] = np.array([[a, cc], [cc, b]])
x0_hat[i] = np.linalg.solve(A_hat[i], [cx, cy])
for name, j, true in [("friction γ", 5 * N, gamma_true), ("repulsion", 5 * N + 1, k_rep),
("landscape k", 5 * N + 2, k_topo)]:
sign = -1 if j == 5 * N else 1 # the friction feature is +v
print(f"{name:>12}: {sign * c_hat[j]:+.2f} ± {s_hat[j]:.2f} (true {true:+.2f})")
print(f"localisation noise: σ̂ = {np.sqrt(np.mean(np.diag(np.asarray(inf.Lambda)))):.4f}"
f" (true {sigma_loc})")
print(f"anchor error, mean over agents: {np.mean(np.linalg.norm(x0_hat - anchors, axis=1)):.3f}"
f" (range size ~{spread:.2f})")
friction γ: +1.68 ± 0.10 (true +1.60)
repulsion: -0.31 ± 0.12 (true -0.40)
landscape k: +0.59 ± 0.01 (true +0.60)
localisation noise: σ̂ = 0.0080 (true 0.008)
anchor error, mean over agents: 0.065 (range size ~0.39)
Validate: ground truth and residual diagnostics¶
On a synthetic benchmark the inferred force can be compared with the
truth directly: the realised error (Normalized MSE) should be of
the order of the predicted one.
inf.compare_to_exact(model_exact=proc)
inf.print_report()
--- StochasticForceInference Report ---
Average diffusion tensor:
[[0.17809245 0.00509613]
[0.00509613 0.18136162]]
Measurement noise tensor:
[[ 6.3588086e-05 -6.3044030e-07]
[-6.3044030e-07 6.4551190e-05]]
Force estimated information: 205.4620361328125
Force: estimated normalized mean squared error (sampling only): 0.005384977090877494
Normalized MSE (force): 0.0029
Normalized MSE (diffusion): 0.0001
Force Coefficient Table
─────────────────────────────────────────────────────────────────────────
# Label Coefficient Std.Err SNR Sig
─────────────────────────────────────────────────────────────────────────
0 Axx[0] 1.12045e+00 1.52670e-01 7.3 *
1 Ayy[0] 5.45682e-01 1.09774e-01 5.0 *
2 Axy[0] 3.70898e-01 9.05939e-02 4.1 *
3 cx[0] 4.91286e-02 5.03591e-02 1.0 ·
4 cy[0] 3.42550e-02 5.49116e-02 0.6 ·
5 Axx[1] 1.23565e+00 1.84978e-01 6.7 *
6 Ayy[1] 7.47512e-01 1.31514e-01 5.7 *
7 Axy[1] -4.15431e-01 1.16354e-01 3.6 *
8 cx[1] 1.81647e+00 2.95060e-01 6.2 *
9 cy[1] -2.69020e-01 1.89451e-01 1.4 ·
10 Axx[2] 8.07221e-01 1.20652e-01 6.7 *
11 Ayy[2] 5.72372e-01 1.07153e-01 5.3 *
12 Axy[2] -3.15267e-01 9.03893e-02 3.5 *
13 cx[2] -1.55376e-02 1.29353e-01 0.1 ·
14 cy[2] 7.44164e-01 1.58376e-01 4.7 *
15 Axx[3] 1.09906e+00 1.28988e-01 8.5 *
16 Ayy[3] 6.77139e-01 1.19044e-01 5.7 *
17 Axy[3] 2.34898e-01 8.86206e-02 2.7 *
18 cx[3] -8.41119e-01 1.62884e-01 5.2 *
19 cy[3] 5.78472e-01 1.59198e-01 3.6 *
20 v -1.68285e+00 1.03044e-01 16.3 **
21 r^0·gauss(σ=0.7) -3.14604e-01 1.18418e-01 2.7 *
22 -grad h 5.89491e-01 1.45779e-02 40.4 **
─────────────────────────────────────────────────────────────────────────
23/23 basis functions in support, sig: 19* / 2** / 0*** (|SNR| ≥ 2 / 10 / 100)
(Std.err. reflects sampling error only; discretization bias is not included.)
Without ground truth, the residual tests are the check. They account for the estimated localisation noise — including the correlation it induces between successive accelerations — so a well-specified fit passes them despite the noise.
report = inf.diagnose()
report.print_summary()
=== SFI diagnostics report ===
backend : parametric
regime : UD
n_obs : 21867 n_particles: 4 d: 2
level : standard
-- Residuals --
mean = +0.0003 std = 1.0022 skew = +0.002 kurt-3 = -0.015 (n=43734)
✓ normality ks stat=0.00284 p=0.871
✓ autocorr ljung_box stat=23.4 p=0.267
✓ autocorr ljung_box_squared stat=12 p=0.916
predicted NMSE = 0.00538 χ²-excess NMSE = 0.0317 (≤ 0.092 at 95%) χ² z = +0.87 (|z|>5 ⇒ bias)
-- Finite sampling interval -- unavailable: interacting (particles_input) bases are not supported
-- Flags --
(no issues at α = 0.01)
Bootstrap: simulate the inferred model¶
A fresh trajectory drawn from the fitted force and diffusion (right) next to the data (left), both over the inferred home ranges (dashed): the same territories, overlaps and drift along the river valleys.
coll_boot, _ = inf.simulate_bootstrapped_trajectory(key=random.PRNGKey(5), oversampling=8)
True vs inferred home ranges¶
Recovered ellipses (dashed) over the ground truth (solid): each agent’s range — centre, elongation, tilt — is recovered from noisy, gappy, positions-only data, together with the shared friction, repulsion and river coupling.
Notes¶
One
make_basis()brick withparticle_extras=gives per-agent tensor coefficients; the centre stays a linear parameter via \(\mathbf{c}_i = \mathsf{A}_i\mathbf{x}^0_i\).A known landscape enters as a fixed feature \(-\nabla h\) with one shared coupling — the same pattern fits any external field whose shape is known (a river, a thermal gradient, an illumination map).
Underdamped dynamics with localisation noise is the hardest regime SFI targets: velocities are never observed and the noise is amplified by \(1/\Delta t^2\). See Underdamped systems and Measurement noise and coarse sampling.
Total running time of the script: (3 minutes 42.355 seconds)
🏷 Tags: synthetic, underdamped, multi-particle, 2D, per-particle