Diagnostics — should we trust a fit?

diagnostics overdamped nonlinear 1D synthetic

An inference always returns numbers; the question is whether the model behind them is consistent with the data. SFI.diagnostics answers it without ground truth: it recomputes the standardised residuals of a fit and tests whether they look like independent standard Gaussian noise, and it checks that the sampling interval is fine enough for the estimator used.

We fit one double-well recording in three ways — the right model, a model with a missing term, and the right model on data with unmodelled measurement noise — and read the three reports. Only at the end do we compare with the true force.

Tags

diagnostics · overdamped · nonlinear · 1D · synthetic

stamp_output()
[Generated: 2026-10-18 18:52]

The data: a particle hopping between two wells

\(F(x) = x - x^3\) has stable points at \(x = \pm 1\), and the particle hops between them; we record 8000 frames at \(\Delta t = 0.05\). A second copy of the recording carries Gaussian localization noise of standard deviation 0.05, about 40% of the typical one-step displacement.

import SFI
from SFI.bases import monomials_up_to, unit_axes, x_components
from SFI.langevin import OverdampedProcess

(x,) = x_components(1)
(ex,) = unit_axes(1)
proc = OverdampedProcess((x - x * x * x) * ex, D=0.15)
proc.initialize(jnp.array([0.5]))
coll = proc.simulate(dt=0.05, Nsteps=8000, key=random.PRNGKey(2), prerun=200, oversampling=10)
coll_noisy = coll.degrade(noise=0.05, seed=3)

Three fits

All three use the fast linear estimators in their clean-data setting ("WeakNoise" diffusion, preset="clean" force), which assume no measurement noise:

  • A — the cubic basis \(\{1, x, x^2, x^3\}\), which contains the true force;

  • B — the linear basis \(\{1, x\}\), which misses the cubic term;

  • C — the cubic basis again, on the noisy copy.

B_cubic = monomials_up_to(order=3, dim=1, rank="vector")
B_linear = monomials_up_to(order=1, dim=1, rank="vector")


def clean_fit(data, basis):
    inf = SFI.OverdampedLangevinInference(data)
    inf.compute_diffusion_constant(method="WeakNoise")
    inf.infer_force_linear(basis, preset="clean")
    inf.compute_force_error()
    return inf


fits = {"A": clean_fit(coll, B_cubic),
        "B": clean_fit(coll, B_linear),
        "C": clean_fit(coll_noisy, B_cubic)}

Run the diagnostics

diagnose() (equivalently SFI.diagnostics.assess()) returns a report; print_summary lists the tests and, under -- Flags --, every failed check with a one-line hint at the likely cure. We read the three reports one by one below; the figure first gives an overview, with two of the panels of plot_summary() for each fit: the Q–Q plot of the residuals against \(\mathcal N(0,1)\) (points on the diagonal) and their autocorrelation (bars inside the 95% band).

reports = {name: inf.diagnose() for name, inf in fits.items()}
A: cubic basis, B: missing $x^3$ term, C: unmodelled noise

Reading the reports

A passes every residual test: Gaussian, uncorrelated, and a χ² excess consistent with zero (the test is calibrated for the finite \(\Delta t\), which makes the residual standard deviation slightly below 1).

print(f"Fit A: D = {float(fits['A'].diffusion_average[0, 0]):.3f}")
reports["A"].print_summary()
Fit A: D = 0.149

=== SFI diagnostics report ===
backend  : linear
regime   : OD
n_obs    : 7999  n_particles: 1  d: 1
level    : standard

-- Residuals --
  mean = +0.0000  std = 0.9612  skew = +0.008  kurt-3 = -0.017  (n=7999)
  ✓ normality ks                 stat=0.0115    p=0.236
  ✓ autocorr  ljung_box          stat=18.4      p=0.563
  ✓ autocorr  ljung_box_squared  stat=35.9      p=0.0158
  predicted NMSE = 0.0124  χ²-excess NMSE = 0.172 (≤ 0.6 at 95%)  χ² z = +0.66 (|z|>5 ⇒ bias)

-- Finite sampling interval --
  dt*|grad F| rms = 0.119  p99 = 0.287  (w.r.t. x, 8000 points)  verdict: coarse

-- Flags --
  ! [finite_dt] dt*|grad F| = 0.119 (p99 0.287): 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

B fails the autocorrelation test. The missing cubic force varies slowly as the particle wanders in and out of the wells, so it leaves a correlated signal in the residuals and the Ljung–Box test flags it — “widen the basis”. Its marginal residuals still look Gaussian: only the autocorrelation test sees structure the basis cannot express.

print(f"Fit B: D = {float(fits['B'].diffusion_average[0, 0]):.3f}")
reports["B"].print_summary()
Fit B: D = 0.149

=== SFI diagnostics report ===
backend  : linear
regime   : OD
n_obs    : 7999  n_particles: 1  d: 1
level    : standard

-- Residuals --
  mean = -0.0000  std = 0.9781  skew = +0.022  kurt-3 = -0.023  (n=7999)
  ✓ normality ks                 stat=0.00804   p=0.676
  ✗ autocorr  ljung_box          stat=59.3      p=9.15e-06
  ✓ autocorr  ljung_box_squared  stat=36        p=0.0156
  predicted NMSE = 0.0615  χ²-excess NMSE = 0  χ² z = -3.30 (|z|>5 ⇒ bias)

-- Finite sampling interval --
  dt*|grad F| rms = 0.00846  p99 = 0.00846  (w.r.t. x, 8000 points)  verdict: fine

-- Flags --
  ! [autocorr/ljung_box] p=9.15e-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

C fails three tests at once. Localization noise corrupts both the increments and the positions at which the force is evaluated. The clean diffusion estimator counts the noise as extra diffusion (\(\hat D\) comes out about 50% high), so the whitened residuals are too narrow — Q–Q slope below 1, and the normality test fails; the residuals are correlated over a few frames (Ljung–Box); and their χ² excess is far above what the predicted error allows.

print(f"Fit C: D = {float(fits['C'].diffusion_average[0, 0]):.3f}")
reports["C"].print_summary()
Fit C: D = 0.226

=== SFI diagnostics report ===
backend  : linear
regime   : OD
n_obs    : 7999  n_particles: 1  d: 1
level    : standard

-- Residuals --
  mean = -0.0000  std = 0.7997  skew = -0.002  kurt-3 = -0.078  (n=7999)
  ✗ normality ks                 stat=0.0539    p=1.13e-20
  ✗ autocorr  ljung_box          stat=60.9      p=5.18e-06
  ✓ autocorr  ljung_box_squared  stat=28.2      p=0.104
  predicted NMSE = 0.00998  χ²-excess NMSE = 0.419 (≤ 0.57 at 95%)  χ² z = +4.71 (|z|>5 ⇒ bias)

-- Finite sampling interval --
  dt*|grad F| rms = 0.161  p99 = 0.405  (w.r.t. x, 8000 points)  verdict: coarse

-- Flags --
  ! [normality/ks] p=1.13e-20 < 0.01 — non-Gaussian residuals — rare events not captured by the basis, or a non-Gaussian noise structure
  ! [autocorr/ljung_box] p=5.18e-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
  ! [mse_consistency] residual chi^2 excess z = +4.71 (mean |z|^2 = 0.6366 vs expected 0.6133); if all of it were force error it would imply NMSE ~ 0.42 (42x the predicted 0.01): 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)
  ! [finite_dt] dt*|grad F| = 0.161 (p99 0.405): 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

The hint points at the cure: the parametric estimator, which models the noise.

inf_C = SFI.OverdampedLangevinInference(coll_noisy)
inf_C.infer_force(B_cubic)      # profiles diffusion D and noise covariance Λ
inf_C.compute_force_error()
print(f"estimated noise amplitude: {np.sqrt(float(inf_C.Lambda[0, 0])):.3f}  (true 0.05)")
reports["C'"] = inf_C.diagnose()
reports["C'"].print_summary()
estimated noise amplitude: 0.052  (true 0.05)

=== SFI diagnostics report ===
backend  : parametric
regime   : OD
n_obs    : 7999  n_particles: 1  d: 1
level    : standard

-- Residuals --
  mean = +0.0017  std = 0.9632  skew = +0.004  kurt-3 = -0.078  (n=7999)
  ✓ normality ks                 stat=0.0107    p=0.32
  ✓ autocorr  ljung_box          stat=29.5      p=0.0785
  ✓ autocorr  ljung_box_squared  stat=30        p=0.0692
  predicted NMSE = 0.0175  χ²-excess NMSE = 0.205 (≤ 0.67 at 95%)  χ² z = +0.73 (|z|>5 ⇒ bias)

-- Finite sampling interval --
  dt*|grad F| rms = 0.123  p99 = 0.305  (w.r.t. x, 8000 points)  verdict: coarse

-- Flags --
  ! [finite_dt] dt*|grad F| = 0.123 (p99 0.305): 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

The noise-aware refit C’ recovers the noise amplitude and its residuals pass every test.

The caution every fit carries

All reports, C’ included, end with a finite_dt caution: near the wells \(\Delta t\,|F'(x)|\) reaches 0.3, a regime where the linear estimators can carry \(O(\Delta t)\) biases of a few per cent. This flag is about the sampling, not the fit, so it does not go away; the hint is to confirm the linear result with the parametric estimator, whose flow-based residual is accurate at coarser \(\Delta t\).

inf_A_par = SFI.OverdampedLangevinInference(coll)
inf_A_par.infer_force(B_cubic)
inf_A_par.compute_force_error()

labels = ["1", "x", "x²", "x³"]
exact = [0.0, 1.0, 0.0, -1.0]
fA, fP = fits["A"], inf_A_par
print("term   linear (A)        parametric        exact")
for i, lab in enumerate(labels):
    print(f"{lab:4s}  {fA.force_coefficients[i]:+.3f} ± {fA.force_coefficients_stderr[i]:.3f}"
          f"   {fP.force_coefficients[i]:+.3f} ± {fP.force_coefficients_stderr[i]:.3f}   {exact[i]:+.1f}")
term   linear (A)        parametric        exact
1     +0.008 ± 0.053   +0.032 ± 0.057   +0.0
x     +1.089 ± 0.080   +1.101 ± 0.091   +1.0
x²    +0.020 ± 0.054   -0.008 ± 0.060   +0.0
x³    -1.074 ± 0.063   -1.103 ± 0.077   -1.0

The two estimators agree well within the error bars: at this sampling the \(O(\Delta t)\) bias is below the statistical error, and fit A stands.

Behind the scenes: the forces

This recording is synthetic, so we can now look at what the diagnostics were detecting. B cannot bend its straight line into the double well; C’s force is too steep, because each noise kick is undone at the next frame, which mimics an extra restoring force; A and C’ lie on the exact force within their 95% bands.

for name, f in (("C", fits["C"]), ("C'", inf_C)):
    c = np.asarray(f.force_coefficients)
    print(f"fit {name:2s}: x {c[1]:+.2f}, x³ {c[3]:+.2f}   (exact +1, -1)")
Inferred forces with 95% bands (data histogram behind)
fit C : x +1.48, x³ -1.44   (exact +1, -1)
fit C': x +1.07, x³ -1.08   (exact +1, -1)

Takeaways

  • Run inf.diagnose() after every fit. Clean residual tests are necessary, not sufficient: they see missing structure and unmodelled noise, not a smooth bias that leaves the residuals white.

  • Correlated residuals point to missing dynamics (B) — or, together with too-narrow residuals and a χ² excess, to measurement noise (C). Each flag’s hint names the cure.

  • A finite_dt caution is about the sampling: confirm with the parametric estimator.

The Diagnostics user guide lists every test; Experimental-data workflow template applies them to a recording with no ground truth.

Thumbnail

Total running time of the script: (0 minutes 40.803 seconds)

🏷 Tags: diagnostics, overdamped, nonlinear, 1D, synthetic

Gallery generated by Sphinx-Gallery