Foundations to Frontier
Tests
J. Scientific Machine Learning › J3 Neural Differential Equations

Hamiltonian and Lagrangian neural networks

A neural network that learns a vector field directly can fit the data well and still produce orbits that slowly spiral in or out, because nothing forces it to conserve energy. Hamiltonian neural networks (HNNs) learn a scalar energy function H(q, p) and obtain the dynamics from Hamilton's equations, q̇ = ∂H/∂p and ṗ = −∂H/∂q, so the learned H is conserved exactly by the true flow. Lagrangian neural networks learn L(q, q̇) and obtain accelerations from the Euler–Lagrange equation, which works in any coordinates. The integrator matters too. Symplectic methods such as leapfrog and implicit midpoint keep energy errors bounded for very long times, while explicit Euler blows up and RK4 drifts slowly. In this page's exercises, Euler reached an energy error of 49 over 1000 time units of a pendulum, while leapfrog stayed within 0.0011. A plain network and an HNN fitted to the same noisy derivatives had similar field errors (0.1 and 0.07). After 100 time units the plain network's energy was off by 0.6 and the HNN's by 0.005.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Building conservation of energy into a network

A swinging pendulum without friction keeps the same energy forever. A neural network that learns how the pendulum moves usually gets this slightly wrong, and over many swings the small errors add up: the learned pendulum slowly speeds up or dies down. A Hamiltonian neural network avoids this by learning the energy itself and computing the motion from it with the rules of classical mechanics; the motion then keeps that energy automatically. The way we step forward in time matters as well: some methods keep energy nearly fixed for millions of steps. The demo compares the energy of a plain learned model and a Hamiltonian one over a long run.

Neural differential equation lab
Energy error E(t) − E(0) of a frictionless pendulum integrated for 50 time units with step 0.1. Red: a plain learned vector field (drift 0.280). Green: the field of a learned Hamiltonian (drift 0.001). Structure keeps orbits closed even when the fit is imperfect.
Why engineers care

Orbit propagation for satellites and planets uses energy-preserving (symplectic) integrators, which is why solar-system simulations can run for billions of years without the planets drifting away.

📝 Quick check (Level 0)
0/3 answered
  1. 1. A Hamiltonian neural network learns…
  2. 2. Why does a plain learned model drift?
  3. 3. Symplectic integrators are used for…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Hamiltonian mechanics (A13-12): state (q, p), energy H(q, p), dynamics q̇ = ∂H/∂p, ṗ = −∂H/∂q. Along the true flow dH/dt = 0, and phase-space volume is preserved (Liouville).
  • HNN (Greydanus, Dzamba and Yosinski, 2019): a network H_θ(q, p) → scalar; the field (∂H_θ/∂p, −∂H_θ/∂q) comes from automatic differentiation; the loss compares it with observed derivatives or trajectories. The learned H_θ is conserved exactly by its own flow.
  • Lagrangian mechanics (A13-11): L(q, q̇); the Euler–Lagrange equation gives q̈ = (∂²L/∂q̇²)⁻¹(∂L/∂q − ∂²L/∂q∂q̇ · q̇). LNNs (Cranmer et al., 2020) learn L and need no canonical momenta, so any coordinates work.
  • Integrators:
    • Non-symplectic: explicit Euler (energy grows), RK4 (accurate, slow drift).
    • Symplectic: leapfrog / Störmer–Verlet for separable H, implicit midpoint for any H; energy errors stay bounded because they exactly conserve a nearby ‘shadow’ Hamiltonian.
  • Extensions: dissipative and port-Hamiltonian networks for friction and inputs; symplectic networks (SympNets) that are symplectic maps by construction; constrained HNNs in Cartesian coordinates.
📝 Quick check (Level 1)
0/3 answered
  1. 1. Hamilton's equations are…
  2. 2. An LNN learns…
  3. 3. Leapfrog applies to…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

Integrators that respect energy

Exercise 1.

  • Explicit Euler, RK4, leapfrog and implicit midpoint on the frictionless pendulum over 1000 time units.
  • The largest energy error of each, and whether RK4’s error grows with time.
  • Accelerations from a Lagrangian by the Euler–Lagrange equation with numerical second derivatives, as an LNN does with autodiff.

Practice.

  • Use an HNN or LNN when the system conserves energy (or another quantity); add dissipation explicitly if it does not (port-Hamiltonian, dissipative HNN).
  • Pair a structured model with a structure-preserving integrator for long rollouts: leapfrog for separable H, implicit midpoint or Gauss–Legendre otherwise.
  • Train on trajectories, not only derivatives, when derivatives are not observed; integrate with the same symplectic scheme during training.
  • Remember the limit: an HNN conserves its learned H, not the true energy; phase errors still accumulate.
  • Tools: JAX or PyTorch autodiff for ∂H/∂z; diffrax and torchdiffeq for solvers; Julia’s DiffEqPhysics; the original HNN and LNN reference code.
import torch

H = torch.nn.Sequential(torch.nn.Linear(2, 64), torch.nn.Tanh(), torch.nn.Linear(64, 1))

def hnn_field(z):                                  # z = (q, p), shape (n, 2)
    z = z.requires_grad_(True)
    dH = torch.autograd.grad(H(z).sum(), z, create_graph=True)[0]
    return torch.stack([dH[:, 1], -dH[:, 0]], 1)   # (∂H/∂p, −∂H/∂q)

opt = torch.optim.Adam(H.parameters(), lr=1e-3)
for it in range(5000):
    loss = ((hnn_field(z_obs) - dz_obs) ** 2).mean()
    opt.zero_grad(); loss.backward(); opt.step()
🐍 Exercise 1: integrators and the Euler–Lagrange equation
Integrate a frictionless pendulum for 1000 time units with Euler, RK4, leapfrog and implicit midpoint and compare their energy errors; compute accelerations from a Lagrangian by the Euler–Lagrange equation.
📝 Quick check (Level 2)
0/3 answered
  1. 1. An HNN conserves…
  2. 2. For friction, use…
  3. 3. For non-separable learned H, a symplectic choice is…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Why the learned energy is conserved. For f = (∂H/∂p, −∂H/∂q), dH/dt = ∂H/∂q · q̇ + ∂H/∂p · ṗ = ∂H/∂q ∂H/∂p − ∂H/∂p ∂H/∂q = 0. Every trajectory of the learned field stays on a level set of H_θ, so orbits of a 1D system close and cannot spiral. A generic field f_θ has no such invariant: a small divergence ∇·f ≠ 0 makes areas shrink or grow, and orbits spiral in or out. In Exercise 2 both models fitted the field about equally well, but over 100 time units the plain network’s energy changed by 0.6 while the HNN’s stayed within 0.03.

Symplectic integrators and shadow Hamiltonians. A symplectic map preserves phase-space area; its Jacobian has determinant 1. Backward error analysis shows that such a method exactly follows the flow of a modified Hamiltonian H̃ = H + O(hᵖ), so the true energy oscillates within O(hᵖ) without drift. Explicit Euler multiplies areas by 1 + h² cos q per step for the pendulum, so energy grows; RK4 is not symplectic but so accurate that its drift is tiny over short times and grows slowly.

What still goes wrong. H_θ differs from H. The HNN’s orbits are closed but have slightly wrong periods, so the phase error grows linearly in time; in Exercise 2 the angle error over the last 10 of 100 time units was 0.09–0.5, depending on the seed. With learned errors of this size, RK4 and implicit midpoint gave the same result.

📝 Quick check (Level 3)
0/3 answered
  1. 1. Along an HNN's flow, dH_θ/dt is…
  2. 2. A symplectic one-step map has Jacobian determinant…
  3. 3. Why do HNN predictions still drift in phase?

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Does building Hamiltonian structure into a learned model keep long rollouts physical?

History.

  • W. R. Hamilton (1833) and J.-L. Lagrange (1788) formulated the mechanics; R. de Vogelaere (1956) and R. Ruth (1983) built the first symplectic integrators; E. Hairer, C. Lubich and G. Wanner (2002) developed geometric numerical integration.
  • S. Greydanus, M. Dzamba and J. Yosinski (2019) introduced Hamiltonian neural networks; M. Cranmer et al. (2020) Lagrangian neural networks; P. Jin et al. (2020) SympNets.
  • Structure-preserving learning has since been extended to dissipative, port-Hamiltonian and constrained systems.

Exercise 2. Frictionless pendulum; 200 random states with energy between −0.9 and 0.5 and derivatives with noise 0.05. Plain network: field = W₂ tanh(Az + b); HNN: H = w·tanh(Az + b), field from its gradient; both width 24, fitted by Levenberg–Marquardt. Rollouts from (1, 0) with step 0.1 for 100 time units; energy errors use the true energy (initial value −0.54). Rounded to one significant figure.

model field error final energy error largest energy error angle RMS, last 10 units
plain network + RK4 0.1 0.6 0.6 0.6
HNN + RK4 0.07 0.005 0.03 0.09
HNN + implicit midpoint 0.07 0.007 0.03 0.1

Exercise 1 (true pendulum, h = 0.1, 1000 time units): largest energy errors were 49 (Euler), 4.6 × 10⁻⁵ and growing (RK4), 1.1 × 10⁻³ (leapfrog) and 8.8 × 10⁻⁵ (implicit midpoint).

  • Same fit, different physics. Both learned fields were about equally accurate, but only the HNN kept the orbit closed; the plain network’s energy changed by 0.6, more than the 0.46 separating the orbit’s energy from the pendulum at rest.
  • Structure beat integrator choice here: with a learned model, modelling errors dominate, and RK4 and implicit midpoint gave the same answer.
  • Integrators matter for the true system: Euler is useless for long runs; symplectic methods keep energy bounded indefinitely; RK4 is very accurate but drifts.
  • Seeds 1 and 2: plain network final energy error 0.3 and 0.2, HNN 0.001 and 0.01; HNN angle RMS 0.5 and 0.4 (phase drift).
🐍 Exercise 2 (research): does building Hamiltonian structure into a learned model keep long rollouts physical?
Fit a plain vector-field network and a Hamiltonian network to noisy pendulum derivatives and compare their energy conservation and accuracy over 100 time units with RK4 and implicit midpoint.

Structure-preserving learning in practice

  • Molecular dynamics: learned potentials (energy functions) give forces as gradients, so simulations conserve energy and run with symplectic Verlet integrators.
  • Orbital mechanics: learned perturbation models inside symplectic propagators for long-term satellite and asteroid prediction (J9-4).
  • Plasma and accelerator physics: symplectic maps learned for particle tracking over millions of turns.
  • Robotics: Lagrangian networks learn mass matrices and potentials of manipulators for model-based control.

References

  1. S. Greydanus, M. Dzamba and J. Yosinski (2019). “Hamiltonian neural networks.” NeurIPS.
  2. M. Cranmer et al. (2020). “Lagrangian neural networks.” ICLR Workshop on Integration of Deep Neural Models and Differential Equations.
  3. P. Jin, Z. Zhang, A. Zhu, Y. Tang and G. E. Karniadakis (2020). “SympNets: intrinsic structure-preserving symplectic networks for identifying Hamiltonian systems.” Neural Networks.
  4. E. Hairer, C. Lubich and G. Wanner (2006). Geometric Numerical Integration, 2nd ed. Springer.
  5. M. Lutter, C. Ritter and J. Peters (2019). “Deep Lagrangian networks.” ICLR.