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.
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.
- 1. A Hamiltonian neural network learns…
- 2. Why does a plain learned model drift?
- 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.
- 1. Hamilton's equations are…
- 2. An LNN learns…
- 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()- 1. An HNN conserves…
- 2. For friction, use…
- 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.
- 1. Along an HNN's flow, dH_θ/dt is…
- 2. A symplectic one-step map has Jacobian determinant…
- 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).
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
- S. Greydanus, M. Dzamba and J. Yosinski (2019). “Hamiltonian neural networks.” NeurIPS.
- M. Cranmer et al. (2020). “Lagrangian neural networks.” ICLR Workshop on Integration of Deep Neural Models and Differential Equations.
- 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.
- E. Hairer, C. Lubich and G. Wanner (2006). Geometric Numerical Integration, 2nd ed. Springer.
- M. Lutter, C. Ritter and J. Peters (2019). “Deep Lagrangian networks.” ICLR.