Note
Go to the end to download the full example code.
Van der Pol oscillator — underdamped inference¶
Infer the force field of a stochastic Van der Pol oscillator from position-only data. The system has inertia, but only positions are observed — as is typical of experimental tracking — so the velocity is reconstructed from the positions by the underdamped estimators.
We fit an over-complete polynomial basis in \((x, v)\), let PASTIS find the three true terms, validate with a bootstrap and the residual diagnostics, and then degrade the recording the way a real experiment would: localisation noise on every position, and a camera ten times slower. The parametric estimator still finds the three terms with honest error bars; a frame-rate sweep shows where and why it breaks.
Tags
synthetic · underdamped · nonlinear · sparsity · 1D
stamp_output()
[Generated: 2026-10-18 18:39]
System definition¶
The stochastic Van der Pol oscillator,
with \(\mu = 3\) (a strongly nonlinear relaxation oscillation, period \(\approx 8.9\)) and \(D = 0.05\). We record 8000 positions at \(\Delta t = 0.02\) — about eighteen cycles. The friction \(-\partial_v F = \mu(x^2 - 1)\) reaches about 10 at the turning points, so the simulator takes 40 internal steps per frame to keep the synthetic data accurate.
from SFI.bases import named_scalar, unit_axes, v_components, x_components
from SFI.langevin import UnderdampedProcess
from SFI.utils import plotting
mu = 3.0
D0 = 0.05
dt = 0.02
Nsteps = 8000
oversampling = 40
# Ground-truth force F(x, v) = mu (1 - x²) v - x, written compositionally.
(_x,) = x_components(1)
(_v,) = v_components(1)
(_ex,) = unit_axes(1)
mu_p = named_scalar("mu", default=mu)
F_exact = (mu_p * (1 - _x * _x) * _v - _x) * _ex
proc = UnderdampedProcess(F_exact, D=jnp.array([[D0]]))
proc.initialize(jnp.array([1.0]), v0=jnp.array([0.0]))
coll = proc.simulate(dt=dt, Nsteps=Nsteps, key=random.PRNGKey(0),
prerun=200, oversampling=oversampling)
t, X, _ = coll.to_arrays(dataset=0) # t:(T,), X:(T, N, d)
x = X[:, 0, 0]
Phase portrait¶
The limit cycle in the \((x, \dot{x})\) plane. The velocity shown here is a plain central difference of the positions — the inference itself works from the same position record.
Force inference and model selection¶
Monomials in \((x, v)\) up to degree 3 give 10 candidate terms; the
truth uses three (\(x\), \(v\), \(x^2 v\)). The data are
clean, so we use the "clean" preset of the linear underdamped
estimator (the automatic choice would also guard against measurement
noise) and the WeakNoise diffusion estimator, suited to a strong
drift; PASTIS then selects the model.
from SFI import UnderdampedLangevinInference
from SFI.bases import monomials_up_to
from SFI.utils.plotting import plot_pareto_front
B = monomials_up_to(order=3, dim=1, include_v=True, rank="vector")
labels = list(B.labels)
truth = {"x0·e0": -1.0, "v0·e0": mu, "(x0^2·v0)·e0": -mu}
inf = UnderdampedLangevinInference(coll)
inf.compute_diffusion_constant(method="WeakNoise")
inf.infer_force_linear(B, preset="clean")
inf.sparsify_force(criterion="PASTIS")
inf.compute_force_error()
inf.compare_to_exact(model_exact=proc, data_exact=coll, maxpoints=2000)
inf.print_report()
# The selected coefficients against the truth, in units of their standard error.
c_lin, cov_lin = inf.coeff_block(slice(None)) # full-basis order
for lbl, tv in truth.items():
i = labels.index(lbl)
err = np.sqrt(cov_lin[i, i])
print(f"{lbl:>13} = {c_lin[i]:+.3f} ± {err:.3f} true {tv:+.0f} "
f"off by {100 * (c_lin[i] / tv - 1):+.1f}% = {(c_lin[i] - tv) / err:+.1f}σ")
--- StochasticForceInference Report ---
Average diffusion tensor:
[[0.05639081]]
Measurement noise tensor:
[[-4.867757e-07]]
Force estimated information: 17561.345703125
Force: estimated normalized mean squared error (sampling only): 8.541486656874357e-05
Force Gram condition number: 1.16e+04
Normalized MSE (force): 0.0049
Normalized MSE (diffusion): 0.0128
Force Coefficient Table
─────────────────────────────────────────────────────────────────────
# Label Coefficient Std.Err SNR Sig
─────────────────────────────────────────────────────────────────────
1 x0·e0 -1.06326e+00 1.73099e-02 61.4 **
2 v0·e0 3.11072e+00 2.43126e-02 127.9 ***
7 (x0^2·v0)·e0 -3.20878e+00 1.79913e-02 178.4 ***
─────────────────────────────────────────────────────────────────────
3/10 basis functions in support, sig: 3* / 3** / 2*** (|SNR| ≥ 2 / 10 / 100)
(Std.err. reflects sampling error only; discretization bias is not included.)
Zeroed (7): 1·e0, x0^2·e0, (x0·v0)·e0, v0^2·e0, x0^3·e0, (x0·v0^2)·e0, v0^3·e0
x0·e0 = -1.063 ± 0.017 true -1 off by +6.3% = -3.7σ
v0·e0 = +3.111 ± 0.024 true +3 off by +3.7% = +4.6σ
(x0^2·v0)·e0 = -3.209 ± 0.018 true -3 off by +7.0% = -11.6σ
Left: the Pareto front — information gain rises steeply up to three terms and then flattens, so PASTIS stops at three. Right: each selected coefficient divided by its true value, with ±2σ error bars. All three overshoot the truth by a few per cent — several standard errors (printed above): this is the \(O(\Delta t)\) bias of the linear estimator, which the next sections diagnose and remove.
Force validation¶
Exact vs inferred force along the trajectory (every frame, so that the arrays follow the time series).
F_true, F_pred = inf.force_comparison_arrays(model_exact=proc, maxpoints=Nsteps)
Bootstrapped trajectory¶
A trajectory simulated from the inferred sparse model should trace the same limit cycle.
coll_boot, _ = inf.simulate_bootstrapped_trajectory(
random.PRNGKey(1), oversampling=oversampling, simulate=True
)
_, X_boot, _ = coll_boot.to_arrays(dataset=0)
x_boot = X_boot[:, 0, 0]
v_fd_boot = coll_boot.velocity_array(dataset=0, scheme="central")[:, 0, 0]
Diagnostics¶
The underdamped residual compares the second-difference acceleration \((x_{t+1} - 2x_t + x_{t-1})/\Delta t^2\) — the same kinematics the estimator fits — to the inferred force, standardised by the noise of a second difference of integrated white noise. Adjacent accelerations overlap, so every second sample is used.
The flags point at the coefficient bias seen above. finite_dt:
\(\Delta t\,|\partial_v F|\) reaches ~0.1–0.2 along the fast
branches of the cycle, where the linear estimator carries an
\(O(\Delta t)\) bias of several per cent. The residual
autocorrelation flag is its other face: with this much data, the
systematic error of the fitted force along the cycle shows up as
correlated residuals. The parametric estimator, used next, integrates
the dynamics across each sampling interval and removes it.
from SFI.diagnostics import assess, plot_summary
report = assess(inf, level="standard")
report.print_summary()
=== SFI diagnostics report ===
backend : linear
regime : UD
n_obs : 3999 n_particles: 1 d: 1
level : standard
-- Residuals --
mean = -0.0008 std = 0.9667 skew = +0.029 kurt-3 = -0.008 (n=3999)
✓ normality ks stat=0.015 p=0.324
✗ autocorr ljung_box stat=62.5 p=2.92e-06
✓ autocorr ljung_box_squared stat=18.7 p=0.543
predicted NMSE = 8.54e-05 χ²-excess NMSE = 0 χ² z = -3.18 (|z|>5 ⇒ bias)
-- Finite sampling interval --
dt*|grad F| rms = 0.121 p99 = 0.211 (w.r.t. v, 7998 points) verdict: coarse
-- Flags --
! [autocorr/ljung_box] p=2.92e-06 < 0.01 — missing time-correlated feature — widen the basis; if it persists, suspect coarse sampling: the parametric estimator (infer_force) extends the usable Δt
! [finite_dt] dt*|grad F| = 0.121 (p99 0.211): coarse sampling — O(Δt) biases of a few to tens of per cent — confirm with the parametric estimator (infer_force) or a stride-2 subsample
Robustness: localisation noise¶
Real tracking adds a localisation error to every position. We blur the positions with \(\sigma = 0.05\) — 2.5% of the oscillation amplitude, barely visible on the trajectory. For inertial data this is severe: a naive finite-difference velocity carries an error \(\sigma/(\sqrt{2}\,\Delta t)\), and the second-difference acceleration \(\sqrt{6}\,\sigma/\Delta t^2\).
sigma = 0.05
coll_noisy = coll.degrade(noise=sigma, seed=3)
print(f"naive velocity error sigma/(sqrt(2) dt) = {sigma / (np.sqrt(2) * dt):.2f}"
f" (speeds up to {np.abs(v_fd).max():.1f})")
print(f"naive acceleration error sqrt(6) sigma/dt^2 = {np.sqrt(6) * sigma / dt**2:.0f}"
f" (|F| up to {np.abs(F_true).max():.1f})")
F_rms = np.sqrt(np.mean(F_true**2))
print(f"force signal per step rms(F) dt^2 = {F_rms * dt**2:.1e} at dt = {dt}, "
f"{F_rms * (10 * dt)**2:.1e} at dt = {10 * dt:.1f} (sigma = {sigma})")
naive velocity error sigma/(sqrt(2) dt) = 1.77 (speeds up to 5.7)
naive acceleration error sqrt(6) sigma/dt^2 = 306 (|F| up to 22.9)
force signal per step rms(F) dt^2 = 1.9e-03 at dt = 0.02, 1.9e-01 at dt = 0.2 (sigma = 0.05)
Each frame-to-frame step carries a force signal of order
\(F\Delta t^2\) against a position error \(\sigma\). At the
full frame rate the first is about \(2\times 10^{-3}\), the second
\(5\times 10^{-2}\) (printed above): every step is noise-dominated,
and the acceleration — hence the force — is lost. Keeping one frame in
ten multiplies \(F\Delta t^2\) by a hundred, to about four times
\(\sigma\), and leaves \(\sigma\) unchanged.
degrade(downsample=10) does that: the same noisy recording, filmed
with a camera ten times slower (800 frames, \(\Delta t = 0.2\),
about 45 per cycle and only a handful per fast jump).
stride = 10
coll_coarse = coll_noisy.degrade(downsample=stride)
dt_coarse = stride * dt
Left: the noise is a small blur on the positions. Middle: at the full frame rate the finite-difference velocity is swamped. Right: on the slow frames it is usable on the slow branches, but the fast jumps are cut into a few chords — a naive analysis would get the dynamics wrong there.
Parametric inference on noisy, coarse frames¶
The parametric estimator
(infer_force())
models the localisation noise explicitly and estimates it, and it
integrates the dynamics across each frame interval instead of
differencing. Over \(\Delta t = 0.2\) the force changes a lot on
the fast branches, so n_substeps splits each interval into RK4
sub-steps no longer than half the fastest relaxation time of the cycle,
\(1/\max|\partial_v F| \approx 1/10\) (the friction at the turning
points). PASTIS then selects the terms as before.
lam_max = mu * (np.abs(x).max() ** 2 - 1) # max |dF/dv| on the cycle
def n_substeps_for(dt_obs):
"""RK4 sub-steps no longer than 1 / (2 lam_max)."""
return int(np.ceil(2 * lam_max * dt_obs))
inf_coarse = UnderdampedLangevinInference(coll_coarse)
inf_coarse.infer_force(B, n_substeps=n_substeps_for(dt_coarse))
inf_coarse.compute_force_error()
nmse_pred_coarse = inf_coarse.force_predicted_MSE # full 10-term fit (kept for the sweep)
inf_coarse.sparsify_force(criterion="PASTIS")
inf_coarse.compute_force_error()
inf_coarse.compare_to_exact(force_exact=proc.force_sf, data_exact=coll, maxpoints=2000)
inf_coarse.print_report()
sigma_hat = float(np.sqrt(np.asarray(inf_coarse.Lambda).ravel()[0]))
D_hat = float(np.asarray(inf_coarse.diffusion_average).ravel()[0])
print(f"max |dF/dv| = {lam_max:.1f} -> n_substeps = {n_substeps_for(dt_coarse)}")
print(f"estimated localisation noise sigma = {sigma_hat:.4f} (true {sigma})")
print(f"estimated diffusion constant D = {D_hat:.3f} (true {D0})")
c_par, cov_par = inf_coarse.coeff_block(slice(None))
for lbl, tv in truth.items():
i = labels.index(lbl)
err = np.sqrt(cov_par[i, i])
print(f"{lbl:>13} = {c_par[i]:+.3f} ± {err:.3f} true {tv:+.0f} "
f"off by {100 * (c_par[i] / tv - 1):+.1f}% = {(c_par[i] - tv) / err:+.1f}σ")
--- StochasticForceInference Report ---
Average diffusion tensor:
[[1.342046]]
Measurement noise tensor:
[[0.00215603]]
Force estimated information: 200.99644470214844
Force: estimated normalized mean squared error (sampling only): 0.0038556100656230636
Normalized MSE (force): 0.0028
Force Coefficient Table
─────────────────────────────────────────────────────────────────────
# Label Coefficient Std.Err SNR Sig
─────────────────────────────────────────────────────────────────────
1 x0·e0 -1.05316e+00 8.51209e-02 12.4 **
2 v0·e0 2.80122e+00 1.49032e-01 18.8 **
7 (x0^2·v0)·e0 -2.87245e+00 1.19749e-01 24.0 **
─────────────────────────────────────────────────────────────────────
3/10 basis functions in support, sig: 3* / 3** / 0*** (|SNR| ≥ 2 / 10 / 100)
(Std.err. reflects sampling error only; discretization bias is not included.)
Zeroed (7): 1·e0, x0^2·e0, (x0·v0)·e0, v0^2·e0, x0^3·e0, (x0·v0^2)·e0, v0^3·e0
max |dF/dv| = 10.2 -> n_substeps = 5
estimated localisation noise sigma = 0.0464 (true 0.05)
estimated diffusion constant D = 1.342 (true 0.05)
x0·e0 = -1.053 ± 0.085 true -1 off by +5.3% = -0.6σ
v0·e0 = +2.801 ± 0.149 true +3 off by -6.6% = -1.3σ
(x0^2·v0)·e0 = -2.872 ± 0.120 true -3 off by -4.3% = +1.1σ
From 800 noisy frames the fit selects exactly the three true terms, and the noise level comes out close to the truth. Its error bars are wider than on the clean data — the price of the noise and of the tenfold-fewer frames — and they are honest: the coefficients sit within about one standard error of the truth, free of the \(O(\Delta t)\) bias of the linear fit. The diffusion constant, on the other hand, is not measurable at this frame rate: the estimate printed above is far too large — across a fast jump the thermal kicks are a small part of the frame-to-frame scatter the fit has to explain. The force is what the slow frames still resolve.
Where does it break?¶
The same noisy recording, fitted at six frame rates — every
\(s\)-th frame, for strides from 1 to 20 — with the sub-steps
scaled to the interval as above. We keep both the full 10-term fit’s
predicted error (force_predicted_MSE, available without knowing the
truth) and the PASTIS-selected model.
strides = [1, 3, 5, 10, 15, 20]
sweep = {}
for s in strides:
if s == stride: # already fitted above
sweep[s] = (inf_coarse, nmse_pred_coarse)
continue
inf_s = UnderdampedLangevinInference(coll_noisy.degrade(downsample=s))
with warnings.catch_warnings():
# at the finest stride the fit finds no force and warns; the table says so
warnings.filterwarnings("ignore", message="infer_force: the parametric fit returned an all-zero")
inf_s.infer_force(B, n_substeps=n_substeps_for(s * dt))
inf_s.compute_force_error()
nmse_pred = inf_s.force_predicted_MSE
inf_s.sparsify_force(criterion="PASTIS")
inf_s.compute_force_error()
sweep[s] = (inf_s, nmse_pred)
true_idx = sorted(labels.index(lbl) for lbl in truth)
print(" stride dt frames F dt²/σ predicted NMSE PASTIS selection")
for s in strides:
inf_s, nmse_pred = sweep[s]
sup = sorted(int(i) for i in np.asarray(inf_s.force_support))
if sup == true_idx:
found = "the 3 true terms"
else:
found = "wrong: " + (", ".join(labels[i] for i in sup) if sup else "no term")
# A fit that finds no force at all has zero information: its NMSE is undefined.
nmse_txt = f"{nmse_pred:.3g}" if np.isfinite(nmse_pred) else "no force found"
print(f" {s:>4} {s * dt:.2f} {Nsteps // s:>6} {F_rms * (s * dt)**2 / sigma:7.2f}"
f" {nmse_txt:>14} {found}")
stride dt frames F dt²/σ predicted NMSE PASTIS selection
1 0.02 8000 0.04 no force found wrong: no term
3 0.06 2666 0.35 0.382 wrong: v0·e0, (x0^2·v0)·e0, (x0·v0^2)·e0
5 0.10 1600 0.97 0.093 wrong: (x0^2·v0)·e0, (x0·v0^2)·e0, v0^3·e0
10 0.20 800 3.86 0.0133 the 3 true terms
15 0.30 533 8.69 0.0246 the 3 true terms
20 0.40 400 15.44 0.19 wrong: (x0·v0^2)·e0, v0^3·e0
Two walls bound the usable window (shaded). On the left, fast frames:
the force signal per step, \(F\Delta t^2\), is below the
localisation noise (column F dt²/σ). At the full frame rate the fit
finds no force at all and PASTIS selects nothing; at strides 3 and 5
the predicted error is still large and the selection is wrong. The
wall sits where \(F\Delta t^2\) climbs past \(\sigma\). On the right,
slow frames: with a frame or two per fast jump the trajectory between
frames is no longer pinned down, the predicted error climbs again and
the selection fails at \(\Delta t = 0.4\). In between, the
predicted error — computed without the truth — is smallest where the
selected coefficients are closest to the truth. Hence a practical rule
for a noisy recording: fit a few strides, keep the one with the
smallest predicted error, and do not trust a selection made from a fit
whose predicted error is large.
Thumbnail¶
Total running time of the script: (2 minutes 0.395 seconds)