Note
Go to the end to download the full example code.
Anisotropic diffusion tensor field¶
Recover a position-dependent, anisotropic diffusion tensor — and the force — from a single 2D trajectory. A tracer in a ring trap experiences fluctuations whose radial component grows with distance from the center (think of a probe in a radially stretched gel, or near a topological defect in an active film): the local noise ellipse rotates with position.
We fit both fields on generic polynomial dictionaries, let PASTIS decide which terms the data support — 6 of 20 force terms, 5 of 18 tensor terms — and read the selected fields with their error bands, including the principal axes of the noise.
Tags
synthetic · overdamped · multiplicative-noise · anisotropic · sparsity · 2D
stamp_output()
[Generated: 2026-10-18 02:22]
Model and simulation¶
A particle in a ring potential \(U = \tfrac{k}{4}(r^2 - R^2)^2\) with a radially anisotropic diffusion tensor (Itô convention):
Radial kicks grow with \(r\); tangential noise stays at \(D_0\). Both fields are polynomial, so we can build them compositionally from coordinate and matrix-template primitives.
import SFI
from SFI.bases import identity_matrix_basis, symmetric_matrix_basis, unit_axes, x_components
from SFI.langevin import OverdampedProcess
k = 4.0 # ring trap stiffness
R = 1.5 # ring radius
D0 = 0.2 # isotropic (tangential) diffusion
a = 0.15 # radial anisotropy growth
dt = 0.005
Nsteps = 50_000
x, y = x_components(2)
ex, ey = unit_axes(2)
I = identity_matrix_basis(2)
S = symmetric_matrix_basis(2) # templates Sxx, Sxy, Syy
Sxx, Sxy, Syy = S[0], S[1], S[2]
r2 = x**2 + y**2
F_model = (-k * (r2 - R**2)) * (x * ex + y * ey)
D_model = D0 * I + a * (x**2 * Sxx + x * y * Sxy + y**2 * Syy)
proc = OverdampedProcess(F=F_model, D=D_model,
theta_F=jnp.ones(F_model.n_features),
theta_D=jnp.ones(D_model.n_features))
proc.initialize(jnp.array([R, 0.0]))
coll = proc.simulate(dt=dt, Nsteps=Nsteps, key=random.PRNGKey(11),
prerun=500, oversampling=10)
Trajectory¶
The tracer diffuses around the annulus, sampling all orientations of the local anisotropy.
Force: fit and select¶
We do not assume the form of the trap. The force is fitted on all
vector monomials up to degree 3 (20 candidate terms); the truth,
\(F = -k(r^2 - R^2)\,\mathbf{x}\), uses six of them. The data are
clean, and the stiff ring confinement can be mistaken for measurement
noise by the automatic choice, so we select the clean-data estimators
explicitly (WeakNoise diffusion constant, clean force preset).
sparsify_force() then
runs PASTIS on the Pareto front of sparse models.
from SFI.bases import monomials_up_to
from SFI.utils.formatting import model_summary
B_force = monomials_up_to(order=3, dim=2, rank="vector")
F_labels = list(B_force.labels)
F_true = {"x0·e0": k * R**2, "x0^3·e0": -k, "(x0·x1^2)·e0": -k,
"x1·e1": k * R**2, "(x0^2·x1)·e1": -k, "x1^3·e1": -k}
inf = SFI.OverdampedLangevinInference(coll)
inf.compute_diffusion_constant(method="WeakNoise")
inf.infer_force_linear(B_force, preset="clean")
inf.sparsify_force(criterion="PASTIS")
inf.compute_force_error() # standard errors of the selected terms
F_sup = [int(i) for i in np.asarray(inf.force_support)]
F_true_idx = [F_labels.index(lbl) for lbl in F_true]
print(f"PASTIS keeps {len(F_sup)}/{len(F_labels)} force terms; "
f"exactly the true ones: {sorted(F_sup) == sorted(F_true_idx)}")
print(model_summary(F_labels, np.asarray(inf.force_coefficients),
stderr=np.asarray(inf.force_coefficients_stderr), support=F_sup,
coeffs_true=np.array(list(F_true.values())), support_true=F_true_idx,
title="Force: selected vs true"))
PASTIS keeps 6/20 force terms; exactly the true ones: True
Force: selected vs true
────────────────────────────────────────────────────────────────────────────────────
# Label Coefficient Std.Err SNR True Sig
────────────────────────────────────────────────────────────────────────────────────
2 x0·e0 8.84744e+00 2.37274e-01 37.3 9.00000e+00 **
5 x1·e1 8.76654e+00 2.41798e-01 36.3 9.00000e+00 **
12 x0^3·e0 -3.92220e+00 1.01589e-01 38.6 -4.00000e+00 **
15 (x0^2·x1)·e1 -3.84918e+00 1.18540e-01 32.5 -4.00000e+00 **
16 (x0·x1^2)·e0 -3.91368e+00 1.18441e-01 33.0 -4.00000e+00 **
19 x1^3·e1 -3.91676e+00 1.04032e-01 37.6 -4.00000e+00 **
────────────────────────────────────────────────────────────────────────────────────
6/20 basis functions in support, sig: 6* / 6** / 0*** (|SNR| ≥ 2 / 10 / 100)
(Std.err. reflects sampling error only; discretization bias is not included.)
Zeroed (14): 1·e0, 1·e1, x0·e1, x1·e0, x0^2·e0, x0^2·e1, (x0·x1)·e0, (x0·x1)·e1, x1^2·e0, x1^2·e1, x0^3·e1, (x0^2·x1)·e0, (x0·x1^2)·e1, x1^3·e0
Left: the Pareto front — the best information gain at each model size;
it climbs until the six true terms are in and is flat beyond, and
PASTIS stops at the knee. Right: each selected coefficient divided by
its true value, with ±2σ error bars from
compute_force_error().
Diffusion tensor: fit and select¶
The diffusion field gets the same treatment, with a rank-2 tensor
basis: degree-2 matrix monomials spanning all symmetric-tensor fields
with quadratic entries (18 candidates; the truth uses 5).
sparsify_diffusion()
runs PASTIS on the diffusion fit, scoring each subset by its likelihood
in the metric of the fit’s own sandwich covariance, and
compute_diffusion_error()
returns the covariance of the selected model. M_mode="WeakNoise"
is the clean-data local estimator, for the same reason as above.
B_diff = monomials_up_to(order=2, dim=2, rank="symmetric_matrix")
D_labels = list(B_diff.labels)
D_true = {"1·S00": D0, "1·S11": D0, "x0^2·S00": a, "(x0·x1)·S01": a, "x1^2·S11": a}
inf.infer_diffusion_linear(B_diff, M_mode="WeakNoise")
inf.sparsify_diffusion(criterion="PASTIS")
inf.compute_diffusion_error() # standard errors of the selected terms
D_sup = [int(i) for i in np.asarray(inf.diffusion_support)]
D_true_idx = [D_labels.index(lbl) for lbl in D_true]
print(f"PASTIS keeps {len(D_sup)}/{len(D_labels)} diffusion terms; "
f"exactly the true ones: {sorted(D_sup) == sorted(D_true_idx)}")
print(model_summary(D_labels, np.asarray(inf.diffusion_coefficients),
stderr=np.asarray(inf.diffusion_coefficients_stderr), support=D_sup,
coeffs_true=np.array(list(D_true.values())), support_true=D_true_idx,
title="Diffusion: selected vs true"))
c_D, cov_D = inf.coeff_block(slice(None), field="diffusion") # full-basis order
dev = [f"{lbl} {(c_D[i] - tv) / np.sqrt(cov_D[i, i]):+.1f}σ"
for lbl, tv in D_true.items() for i in [D_labels.index(lbl)]]
print("deviation from truth:", ", ".join(dev))
inf.compare_to_exact(model_exact=proc)
print(f"NMSE vs truth: force {float(inf.NMSE_force):.4f}, "
f"diffusion {float(inf.NMSE_diffusion):.4f}")
PASTIS keeps 5/18 diffusion terms; exactly the true ones: True
Diffusion: selected vs true
───────────────────────────────────────────────────────────────────────────────────
# Label Coefficient Std.Err SNR True Sig
───────────────────────────────────────────────────────────────────────────────────
0 1·S00 2.07971e-01 3.69849e-03 56.2 2.00000e-01 **
2 1·S11 2.00718e-01 3.52458e-03 56.9 2.00000e-01 **
9 x0^2·S00 1.40000e-01 3.84393e-03 36.4 1.50000e-01 **
13 (x0·x1)·S01 1.50228e-01 2.61644e-03 57.4 1.50000e-01 **
17 x1^2·S11 1.50641e-01 3.92654e-03 38.4 1.50000e-01 **
───────────────────────────────────────────────────────────────────────────────────
5/18 basis functions in support, sig: 5* / 5** / 0*** (|SNR| ≥ 2 / 10 / 100)
(Std.err. reflects sampling error only; discretization bias is not included.)
Zeroed (13): 1·S01, x0·S00, x0·S01, x0·S11, x1·S00, x1·S01, x1·S11, x0^2·S01, x0^2·S11, (x0·x1)·S00, (x0·x1)·S11, x1^2·S00, x1^2·S01
deviation from truth: 1·S00 +2.2σ, 1·S11 +0.2σ, x0^2·S00 -2.6σ, (x0·x1)·S01 +0.1σ, x1^2·S11 +0.2σ
NMSE vs truth: force 0.0009, diffusion 0.0003
Same reading as for the force: the Pareto front flattens once five terms are in (AIC, a less strict criterion, would admit a sixth). The selected coefficients scatter around the truth by about their error bars; the largest deviation, on the \(x^2\) part of \(D_{xx}\), is offset by the constant part of \(D_{xx}\), and its symmetric partner on \(D_{yy}\) sits on the truth.
Tensor glyphs: exact vs inferred¶
Each glyph is the ellipse \(\mathbf{u}^{\!\top} D^{-1}\mathbf{u} = \text{const}\) of the local tensor — long axis along the fast direction. Exact field on the left, the selected model on the right: the radial orientation and the \(r^2\) growth are both recovered.
# Glyph positions on a polar grid covering the sampled annulus, and a
# callable for the exact tensor field D(x) = D0 I + a r^2 r-hat r-hat^T.
r_glyph = np.linspace(0.9, 2.0, 4)
th_glyph = np.linspace(0, 2 * np.pi, 12, endpoint=False)
pts = np.array([[r * np.cos(t), r * np.sin(t)] for r in r_glyph for t in th_glyph])
def D_exact_field(p):
p = np.asarray(p).reshape(-1, 2)
return np.array([D0 * np.eye(2) + a * np.outer(q, q) for q in p])
def D_inferred_field(p):
return inf.diffusion_inferred(jnp.asarray(p))
Radial and tangential eigenvalues¶
Projecting the inferred tensor onto the local radial and tangential directions separates the two physical components: the radial diffusivity grows as \(D_0 + a r^2\) while the tangential one stays flat at \(D_0\). Curves are averaged over the polar angle; bands are ±2σ, propagated from the covariance of the selected coefficients. The grey histogram shows where the tracer actually went: the bands are narrowest on the ring, where the data are.
r_prof = np.linspace(0.8, 2.1, 30)
th_s = np.linspace(0, 2 * np.pi, 24, endpoint=False)
def radial_tangential_rows(basis):
"""Linear maps coefficients -> angle-averaged D_rr(r), D_θθ(r)."""
L_rr = np.zeros((len(r_prof), basis.n_features))
L_tt = np.zeros_like(L_rr)
for t_ in th_s:
pts_ray = np.column_stack([r_prof * np.cos(t_), r_prof * np.sin(t_)])
Bf = np.asarray(basis(jnp.array(pts_ray))) # (n_r, 2, 2, F)
rhat = np.array([np.cos(t_), np.sin(t_)])
that = np.array([-np.sin(t_), np.cos(t_)])
L_rr += np.einsum("i,nijf,j->nf", rhat, Bf, rhat) / len(th_s)
L_tt += np.einsum("i,nijf,j->nf", that, Bf, that) / len(th_s)
return L_rr, L_tt
L_rr, L_tt = radial_tangential_rows(B_diff)
C_D, Cov_D = inf.coeff_block(slice(None), field="diffusion") # full-basis order
D_rr, D_tt = L_rr @ C_D, L_tt @ C_D
D_rr_err = np.sqrt(np.einsum("nf,fg,ng->n", L_rr, Cov_D, L_rr))
D_tt_err = np.sqrt(np.einsum("nf,fg,ng->n", L_tt, Cov_D, L_tt))
The same workflow applies unchanged to experimental 2D tracking data; see the multiplicative-noise demo for localisation noise and the Itô-convention caveats that come with state-dependent noise.
Thumbnail¶
Dedicated single-panel figure for the gallery thumbnail.
Total running time of the script: (0 minutes 31.835 seconds)