Experimental-data workflow template

synthetic overdamped nonlinear sparsity diagnostics 2D

The recommended workflow for applying SFI to experimental trajectories: load a recording, look at it, infer the force with a generic basis, let PASTIS select the model, and validate the result without any ground truth — residual diagnostics, a noise-aware refit, a data-length check and a bootstrap.

The recording is a 2D optical-tweezer track stored as a CSV file. It is a synthetic stand-in (generated by examples/experimental_data/generate_tweezer_csv.py) with the imperfections of real tracking data: a finite frame rate and localization noise as large as the bead’s displacement between two frames. The trap is not quite ideal; the task is to find out how, from the data alone. Replace the file path with your own recording to reuse the template.

Tags

synthetic · overdamped · nonlinear · sparsity · diagnostics · 2D

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

Step 1 — Load the trajectory

load() reads CSV (with an optional YAML header), Parquet and HDF5. This file starts with a # dt: 0.01 header, so the frame interval is set automatically.

from pathlib import Path

from SFI.trajectory import TrajectoryCollection

# The stand-in recording ships with the SFI examples (path relative to
# examples/gallery/); replace it with your own file to reuse the template.
csv_path = Path("../experimental_data/optical_tweezer.csv")
coll = TrajectoryCollection.load(csv_path)
dt = coll.dt
print(f"Loaded: {coll.T} frames, d = {coll.d}, dt = {dt}")
Loaded: 100000 frames, d = 2, dt = 0.01

Step 2 — Look at the data

Always look first: outliers, gaps, drifts. The bead explores a trap that is narrower along \(x\) than along \(y\) (left). At the frame scale the trace is jittery (middle), and the mean-squared displacement does not extrapolate to zero at zero lag (right): its intercept, \(2\sigma^2\) per axis, is the classic signature of localization noise of amplitude \(\sigma\).


Where the bead goes, First 300 frames, Short-lag MSD: noise floor

Step 3 — Fast linear inference and model selection

Start with a generic polynomial basis — all monomials up to degree 3 for each force component, 20 candidate terms — and the fast linear estimators. With default settings ("auto") SFI detects the measurement noise and switches both the diffusion estimate and the force fit to their noise-robust variants. PASTIS then selects the smallest model the data support.

from SFI import OverdampedLangevinInference
from SFI.bases import monomials_up_to

B = monomials_up_to(order=3, dim=2, rank="vector")
labels = list(B.labels)

inf_lin = OverdampedLangevinInference(coll)
inf_lin.compute_diffusion_constant()
inf_lin.infer_force_linear(B)
inf_lin.compute_force_error()
inf_lin.sparsify_force(criterion="PASTIS")
inf_lin.compute_force_error()
inf_lin.print_report()
  --- StochasticForceInference Report ---
Average diffusion tensor:
 [[ 0.4797724  -0.00216432]
 [-0.00216432  0.49701643]]
Measurement noise tensor:
 [[ 1.0157357e-02 -2.0265836e-05]
 [-2.0265859e-05  9.8764813e-03]]
Force estimated information: 783.7920532226562
Force: estimated normalized mean squared error (sampling only): 0.003189621823976812
Force Gram condition number: 73.1

  Force Coefficient Table
  ─────────────────────────────────────────────────────────────────────
  #    Label          Coefficient       Std.Err     SNR  Sig
  ─────────────────────────────────────────────────────────────────────
  2    x0·e0         -6.03152e-01   1.06647e-01     5.7  *
  3    x0·e1          5.42954e-01   5.72284e-02     9.5  *
  4    x1·e0         -4.66171e-01   4.23374e-02    11.0  **
  5    x1·e1         -8.82995e-01   4.30728e-02    20.5  **
  12   x0^3·e0       -1.30592e+00   1.16675e-01    11.2  **
  ─────────────────────────────────────────────────────────────────────
  5/20 basis functions in support, sig: 5* / 3** / 0*** (|SNR| ≥ 2 / 10 / 100)
  (Std.err. reflects sampling error only; discretization bias is not included.)
  Zeroed (15): 1·e0, 1·e1, 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^2·x1)·e1, (x0·x1^2)·e0, (x0·x1^2)·e1, x1^3·e0, x1^3·e1

Step 4 — Residual diagnostics

Without ground truth, the first check is statistical: are the standardized residuals of the fit consistent with white Gaussian noise? Each flag, if any, comes with a one-line hint.

report_lin = inf_lin.diagnose()
report_lin.print_summary()
=== SFI diagnostics report ===
backend  : linear
regime   : OD
n_obs    : 99999  n_particles: 1  d: 2
level    : standard

-- Residuals --
  mean = +0.0016  std = 0.9958  skew = +0.003  kurt-3 = -0.012  (n=199998)
  ✓ normality ks                 stat=0.00234   p=0.225
  ✓ autocorr  ljung_box          stat=28.8      p=0.092
  ✓ autocorr  ljung_box_squared  stat=24.4      p=0.224
  predicted NMSE = 0.00319  χ²-excess NMSE = 0.0293 (≤ 0.65 at 95%)  χ² z = +0.08 (|z|>5 ⇒ bias)

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

-- Flags --
  (no issues at α = 0.01)

The linear fit passes. But clean residual tests are necessary, not sufficient: they see missing structure (autocorrelation, non-Gaussianity), while a smooth bias of the coefficients — the typical effect of localization noise on a nonlinear basis — leaves the residuals white. The decisive cross-check is an independent estimator built for this situation.

Step 5 — Noise-aware parametric refit

The parametric estimator infer_force() models the localization noise explicitly: it fits the force, the diffusion and the noise covariance \(\Lambda\) jointly, so no separate diffusion call is needed. It is slower than the linear route, and it is the estimator to report for noisy recordings (Measurement noise and coarse sampling).

inf = OverdampedLangevinInference(coll)
inf.infer_force(B)
inf.compute_force_error()
inf.sparsify_force(criterion="PASTIS")
inf.compute_force_error()
inf.print_report()

sigma_hat = np.sqrt(np.diag(np.asarray(inf.Lambda)))
print(f"Estimated localization noise: sigma = {sigma_hat.round(3)} per axis")

inf.diagnose().print_summary()
  --- StochasticForceInference Report ---
Average diffusion tensor:
 [[ 4.9040568e-01 -2.7900399e-04]
 [-2.7900399e-04  5.0439650e-01]]
Measurement noise tensor:
 [[ 1.0102225e-02 -4.2224718e-05]
 [-4.2224718e-05  9.8163448e-03]]
Force estimated information: 484.08819580078125
Force: estimated normalized mean squared error (sampling only): 0.0034608620542676415

  Force Coefficient Table
  ─────────────────────────────────────────────────────────────────────
  #    Label          Coefficient       Std.Err     SNR  Sig
  ─────────────────────────────────────────────────────────────────────
  2    x0·e0         -8.77113e-01   1.23931e-01     7.1  *
  3    x0·e1          5.61351e-01   6.01242e-02     9.3  *
  4    x1·e0         -4.75769e-01   4.38930e-02    10.8  **
  5    x1·e1         -8.97860e-01   4.44586e-02    20.2  **
  12   x0^3·e0       -1.12199e+00   1.45206e-01     7.7  *
  ─────────────────────────────────────────────────────────────────────
  5/20 basis functions in support, sig: 5* / 2** / 0*** (|SNR| ≥ 2 / 10 / 100)
  (Std.err. reflects sampling error only; discretization bias is not included.)
  Zeroed (15): 1·e0, 1·e1, 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^2·x1)·e1, (x0·x1^2)·e0, (x0·x1^2)·e1, x1^3·e0, x1^3·e1
Estimated localization noise: sigma = [0.101 0.099] per axis

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

-- Residuals --
  mean = +0.0018  std = 0.9934  skew = +0.003  kurt-3 = -0.012  (n=199998)
  ✓ normality ks                 stat=0.00296   p=0.0603
  ✓ autocorr  ljung_box          stat=23.8      p=0.253
  ✓ autocorr  ljung_box_squared  stat=24.5      p=0.222
  predicted NMSE = 0.00346  χ²-excess NMSE = 0.0103 (≤ 0.65 at 95%)  χ² z = +0.03 (|z|>5 ⇒ bias)

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

-- Flags --
  (no issues at α = 0.01)

The noise amplitude matches the MSD noise floor of step 2, and the residuals pass again. Left: the Pareto front of the parametric fit — the information gained by the best model of each size; it flattens once five terms are in, where PASTIS stops (AIC, less strict, would admit two more). Right: the selected coefficients of both routes with 95% error bars. Where the two estimators disagree by more than their errors, the linear estimate is the one biased by the noise.

support = [int(i) for i in np.asarray(inf.force_support)]
union = sorted(set(support) | {int(i) for i in np.asarray(inf_lin.force_support)})

# full-basis coefficients and covariance of each sparse fit (pruned terms are 0)
(c_par, cov_par), (c_lin, cov_lin) = inf.coeff_block(B), inf_lin.coeff_block(B)
c_par, e_par = c_par[union], np.sqrt(np.diag(cov_par))[union]
c_lin, e_lin = c_lin[union], np.sqrt(np.diag(cov_lin))[union]
Pareto front (parametric fit), Selected terms, both estimators

Read as physics: \(x\,\hat e_x\) and \(y\,\hat e_y\) are the trap stiffnesses; the antisymmetric pair \(y\,\hat e_x\), \(x\,\hat e_y\) is a rotation — a non-conservative force, the signature of a non-ideal tweezer; and \(x^3\,\hat e_x\) is an anharmonicity along \(x\).

Step 6 — Is there enough data?

Refit the selected model on the first quarter and the first half of the recording. A trustworthy model has coefficients that stay put within their error bars while the error bars shrink as \(1/\sqrt{T}\); terms that drift or flip sign as data are added are not yet resolved.

conv = {}
for frac in (0.25, 0.5):
    first_part, _ = coll.split_time(frac)        # the first `frac` of the recording
    inf_f = OverdampedLangevinInference(first_part)
    inf_f.infer_force(B[support])               # the five selected terms only
    inf_f.compute_force_error()
    conv[frac] = (np.asarray(inf_f.force_coefficients), np.asarray(inf_f.force_coefficients_stderr))
conv[1.0] = (np.asarray(inf.force_coefficients), np.asarray(inf.force_coefficients_stderr))
for frac, (c, e) in conv.items():
    print(f"{frac:4.0%} of the data: " + ", ".join(
        f"{labels[i]} = {ci:+.2f} ± {ei:.2f}" for i, ci, ei in zip(support, c, e)))
Convergence with data length
 25% of the data: x0·e0 = -1.05 ± 0.25, x0·e1 = +0.78 ± 0.12, x1·e0 = -0.51 ± 0.08, x1·e1 = -0.82 ± 0.09, x0^3·e0 = -1.04 ± 0.30
 50% of the data: x0·e0 = -1.08 ± 0.18, x0·e1 = +0.64 ± 0.09, x1·e0 = -0.47 ± 0.06, x1·e1 = -0.88 ± 0.06, x0^3·e0 = -1.00 ± 0.21
100% of the data: x0·e0 = -0.88 ± 0.12, x0·e1 = +0.56 ± 0.06, x1·e0 = -0.48 ± 0.04, x1·e1 = -0.90 ± 0.04, x0^3·e0 = -1.12 ± 0.15

All five terms are resolved from the first quarter of the recording on, and no estimate moves by more than its 95% error bar.

Step 7 — Bootstrap

Finally, simulate new recordings from the inferred model — force, diffusion, and the estimated localization noise added on top — and compare them with the data, on statistics the fit never targeted: the stationary distribution, and the antisymmetric cross-correlation

\[A(\tau) = \langle x(t)\,y(t+\tau)\rangle - \langle y(t)\,x(t+\tau)\rangle ,\]

which vanishes for any equilibrium (conservative) trap: it measures how much the rotation breaks time-reversal symmetry. Twenty bootstraps give the spread expected for a recording of this length.

coll_boot, proc_boot = inf.simulate_bootstrapped_trajectory(random.PRNGKey(123))
boots = [coll_boot] + [proc_boot.simulate(dt=dt, Nsteps=coll.T, key=random.PRNGKey(s)) for s in range(19)]
boots = [b.degrade(noise=float(sigma_hat.mean()), seed=s) for s, b in enumerate(boots)]
Stationary density, Broken time-reversal symmetry

The recording sits inside the bootstrap spread on both counts: the inferred model reproduces the shape of the trap and the strength and lifetime of its circulation.

Checking against the generator

This recording is synthetic, so — unlike with real data — we can grade the workflow. The generator uses a harmonic trap of stiffness \(k = 1\), a cubic term \(-x^3\) along \(x\), a rotation of rate \(\omega = 0.5\), \(D = 0.5\) and a localization noise of \(0.1\) per axis.

theta_true = {"x0·e0": -1.0, "x1·e1": -1.0, "x1·e0": -0.5, "x0·e1": 0.5, "x0^3·e0": -1.0}
truth = np.array([theta_true.get(labels[i], 0.0) for i in union])
print("term       true    parametric (z)          linear (z)")
for j, i in enumerate(union):
    print(f"{labels[i]:9s} {truth[j]:+.2f}   {c_par[j]:+.3f} ± {e_par[j]:.3f} ({(c_par[j] - truth[j]) / e_par[j]:+.1f})"
          f"   {c_lin[j]:+.3f} ± {e_lin[j]:.3f} ({(c_lin[j] - truth[j]) / e_lin[j]:+.1f})")
Both estimators vs the generator
term       true    parametric (z)          linear (z)
x0·e0     -1.00   -0.877 ± 0.124 (+1.0)   -0.603 ± 0.107 (+3.7)
x0·e1     +0.50   +0.561 ± 0.060 (+1.0)   +0.543 ± 0.057 (+0.8)
x1·e0     -0.50   -0.476 ± 0.044 (+0.6)   -0.466 ± 0.042 (+0.8)
x1·e1     -1.00   -0.898 ± 0.044 (+2.3)   -0.883 ± 0.043 (+2.7)
x0^3·e0   -1.00   -1.122 ± 0.145 (-0.8)   -1.306 ± 0.117 (-2.6)

Both routes find the right five terms. The parametric coefficients deviate from the generator by what sampling noise allows: the largest deviation, about two standard errors on the \(y\) stiffness, is shared by the linear estimate, so it is a fluctuation of this recording rather than a bias. The linear ones are biased beyond their error bars on the terms the noise enters nonlinearly — the \(x\) stiffness and the cubic, which trade off against each other — even though their residual diagnostics looked clean. On real data, that is exactly what the step-5 comparison is for.

Thumbnail

Total running time of the script: (3 minutes 17.487 seconds)

🏷 Tags: synthetic, overdamped, nonlinear, sparsity, diagnostics, 2D

Gallery generated by Sphinx-Gallery