Note
Go to the end to download the full example code.
Neural-network energy landscape — Müller–Brown potential¶
Can a small neural network learn an energy landscape from a single trajectory? A particle hops between the three wells of the Müller–Brown surface; we parametrize its potential by a network built from SFI’s compositional basis operations and obtain the force as minus its gradient, by automatic differentiation — every fitted force is conservative by construction.
In symbols, the network is a potential \(U_\theta(\mathbf{x})\) with
weights \(\theta\), and the force
\(\mathbf{F} = -\nabla U_\theta\) comes from its .d_x()
derivative. The benchmark is the standard linear route — a polynomial
potential — on the same data:
Polynomial potential (closed-form linear fit): fast and with error bars, but its smooth monomials cannot follow the narrow wells. Its predicted error (sampling only) is far below the error it actually makes: the gap is basis bias.
Neural-network potential (parametric fit, nonlinear in the weights), finished by a linear refit of its last layer, which restores the closed-form error bars of the linear route.
Finally, a trajectory simulated from the learned landscape hops between the same wells as the data.
Note
This is an advanced example: the network is fitted with the
parametric estimator
(infer_force()).
Start with the main gallery if you are new to SFI.
Tags
synthetic · overdamped · nonlinear · neural-network · thermodynamics · 2D
stamp_output()
[Generated: 2026-10-18 18:55]
A particle on the Müller–Brown surface¶
The Müller–Brown potential is a classic benchmark from computational chemistry: three wells joined by two saddles,
rescaled by \(\alpha = 0.01\) so that forces are \(\mathcal{O}(1)\). With \(D = 0.2\) the barriers are a few \(k_BT\): the particle dwells in each well and repeatedly hops between them over the 150 time units of the recording.
from SFI.langevin import OverdampedProcess
from SFI.statefunc import make_sf
# Standard Müller–Brown parameters
_A = jnp.array([-200.0, -100.0, -170.0, 15.0])
_a = jnp.array([-1.0, -1.0, -6.5, 0.7])
_b = jnp.array([0.0, 0.0, 11.0, 0.6])
_c = jnp.array([-10.0, -10.0, -6.5, 0.7])
_xbar = jnp.array([1.0, 0.0, -0.5, -1.0])
_ybar = jnp.array([0.0, 0.5, 1.5, 1.0])
ALPHA = 0.01
def muller_brown_potential(xy):
"""Müller–Brown potential (rescaled)."""
x, y = xy[0], xy[1]
exponents = (
_a * (x - _xbar) ** 2
+ _b * (x - _xbar) * (y - _ybar)
+ _c * (y - _ybar) ** 2
)
return ALPHA * jnp.sum(_A * jnp.exp(exponents))
F_exact = make_sf(jax.grad(lambda xy: -muller_brown_potential(xy)), dim=2, rank=1)
D0 = 0.2
dt = 0.01
proc = OverdampedProcess(F_exact, D=D0 * jnp.eye(2))
proc.initialize(jnp.array([-0.5, 1.5]))
coll = proc.simulate(dt=dt, Nsteps=15_000, key=random.PRNGKey(42), prerun=500, oversampling=10)
Bright = low energy. The trajectory concentrates in the three wells, with thin threads across the saddles.
Polynomial potential — the linear baseline¶
Write the potential on scalar monomials, \(U = \sum_i c_i\, u_i\),
and differentiate the library once: \(\mathbf{b}_i = -\nabla u_i\)
(.d_x()). The force is still linear in the coefficients, so the
closed-form estimator applies and returns the energy coefficients
directly. The data are clean, so we use the "clean" preset and the
WeakNoise diffusion estimator (the drift is strong compared with the
noise here).
from SFI import OverdampedLangevinInference
from SFI.bases import monomials_up_to
poly_order = 5
U_poly_lib = monomials_up_to(order=poly_order, dim=2, include_constant=False, rank="scalar")
B_poly = -(U_poly_lib.d_x()) # b_i = -grad u_i (rank-0 -> rank-1)
inf_poly = OverdampedLangevinInference(coll)
inf_poly.compute_diffusion_constant(method="WeakNoise")
inf_poly.infer_force_linear(B_poly, preset="clean")
inf_poly.compute_force_error()
inf_poly.compare_to_exact(model_exact=proc)
theta_poly = np.asarray(inf_poly.force_coefficients_full)
def U_poly(pts):
"""Fitted polynomial potential U = sum_i c_i u_i."""
return np.asarray(U_poly_lib(pts)) @ theta_poly
print(f"polynomial ({theta_poly.size} terms): predicted NMSE = {inf_poly.force_predicted_MSE:.4f},"
f" NMSE vs truth = {float(inf_poly.NMSE_force):.3f}")
polynomial (20 terms): predicted NMSE = 0.0149, NMSE vs truth = 0.400
The error against the truth is far above the predicted (sampling-only) error: with this much data the limitation is the basis, not the sampling.
Neural-network potential¶
A two-hidden-layer network built in SFI’s expression tree,
2 → 16 → 16 → 1:
X(dim=2).rank_to_features()puts \((x, y)\) on the feature axis;.dense(n, weight=…, bias=…)is a learnable affine layer and.elementwisemap(jnp.tanh)the activation;the scalar head (no bias — an energy offset is unobservable) is the potential \(U_\theta\), and
-U.d_x()its conservative force.
from SFI.bases import X
H = 16 # hidden width
mlp_U = (
X(dim=2).rank_to_features()
.dense(H, weight="W1", bias="b1").elementwisemap(jnp.tanh)
.dense(H, weight="W2", bias="b2").elementwisemap(jnp.tanh)
.dense(1, weight="W3", bias=None) # U(x): rank-0, 1 feature
)
mlp = -(mlp_U.d_x()) # F = -grad U
# Glorot initialisation of the weights, zero biases.
theta0, init_key = {}, random.PRNGKey(123)
for name, shape in [("W1", (2, H)), ("b1", (H,)), ("W2", (H, H)), ("b2", (H,)), ("W3", (H, 1))]:
init_key, sub = random.split(init_key)
theta0[name] = (jnp.sqrt(2.0 / sum(shape)) * random.normal(sub, shape)
if name.startswith("W") else jnp.zeros(shape))
print(f"MLP potential: {mlp.template.size} parameters")
MLP potential: 336 parameters
The weights enter nonlinearly, so the fit uses the parametric
estimator, here with its L-BFGS solver (inner="lbfgs"): on a
saturating network the default Gauss–Newton path diverges and would
fall back to L-BFGS anyway. A short optimisation budget
(max_outer, inner_maxiter) is enough because the last-layer
refit below finishes the job.
inf_nn = OverdampedLangevinInference(coll)
inf_nn.infer_force(mlp, theta0, inner="lbfgs", max_outer=2, inner_maxiter=60)
inf_nn.compare_to_exact(model_exact=proc)
print(f"neural network (optimiser output): NMSE vs truth = {float(inf_nn.NMSE_force):.3f}")
neural network (optimiser output): NMSE vs truth = 0.058
Last-layer refit: error bars for the network¶
Freeze the trained hidden layers and treat their activations
\(z_h(\mathbf{x})\) (plus the linear tilts \(x, y\)) as a
scalar potential library — exactly like the monomials above. One
.d_x() turns it into gradient force features, and the closed-form
linear estimator refits the last layer in seconds, with error bars and
a predicted error. This is the network result we report.
from SFI.statefunc import make_basis
theta_nn = mlp.unflatten_params(inf_nn.force_coefficients_full)
def hidden_features(x, *, mask=None, extras=None):
z = jnp.tanh(theta_nn["W1"].T @ x + theta_nn["b1"])
z = jnp.tanh(theta_nn["W2"].T @ z + theta_nn["b2"])
return jnp.concatenate([z, x]) # (H + 2,) potential features
Z_last = make_basis(hidden_features, dim=2, rank=0, n_features=H + 2)
B_last = -(Z_last.d_x())
inf_last = OverdampedLangevinInference(coll)
inf_last.compute_diffusion_constant(method="WeakNoise")
inf_last.infer_force_linear(B_last, preset="clean")
inf_last.compute_force_error()
inf_last.compare_to_exact(model_exact=proc)
theta_last = np.asarray(inf_last.force_coefficients_full)
def U_nn(pts):
"""Network potential U = sum_h c_h z_h + c_x x + c_y y."""
return np.asarray(Z_last(pts)) @ theta_last
print(print_model_comparison(
[inf_poly, inf_nn, inf_last],
[f"Polynomial (deg {poly_order})", "NN (optimiser)", "NN + last-layer refit"],
metrics=["n_params", "force_predicted_MSE", "NMSE_force"],
))
Model Comparison
Model n_params force_predicted_MSE NMSE_force
────────────────────────────────────────────────────────────────
Polynomial (deg 5) 20 0.01487 0.3996
NN (optimiser) 336 — 0.05781
NN + last-layer refit 18 0.01077 0.03665
The network cuts the error about tenfold, with 18 refitted coefficients on top of its frozen hidden layers (the refit also improves on the optimiser’s own output). Its realised error is still a few times the predicted one, which counts sampling noise only: a 16-unit network remains an approximation of the sharp wells.
Inferred energy landscapes¶
Both models parametrize \(U\) itself, so the landscape is read off directly. Each surface is shifted by its mean over the visited region (an additive constant is unobservable). The polynomial cannot carve the shallow middle well; the network recovers the three-well topography. Far from the data, both extrapolate freely.
Point-wise force error¶
The polynomial’s error concentrates on the steep well walls and saddles; the network’s is lower and more uniform. Both colour scales are capped at the 99th percentile of the errors along the trajectory, so cells far outside the data (where both models extrapolate) saturate.
force_poly = inf_poly.force_inferred
force_nn = inf_last.force_inferred
Bootstrap: does the learned landscape hop like the data?¶
A trajectory simulated from the network’s force and the inferred diffusion should dwell in the same wells and hop across the same saddles. Left: the data on the true landscape; right: the bootstrap on the learned one.
coll_boot, _ = inf_last.simulate_bootstrapped_trajectory(random.PRNGKey(1), oversampling=10)
Thumbnail¶
Total running time of the script: (2 minutes 5.721 seconds)