Lab: Hamiltonian networks and energy drift
A Hamiltonian network learns an energy and takes its motion from that energy. A solver then turns the motion into a trajectory, and it can leak energy. Integrate an oscillator with Euler and symplectic Euler and watch the drift.
What runs in CodeSplash
- SEQ012Hamiltonian Neural Networks Explained here
You will be able to
- Derive the motion of a system from its Hamiltonian
- Explain why a Hamiltonian vector field conserves energy in continuous time
- Compare explicit Euler with symplectic Euler on a known oscillator and read the energy drift
- Keep integration error apart from modeling error when judging a learned model
Energy decides the motion
ReadA frictionless system can be written with positions , momenta and one function, its HamiltonianHamiltonianA system's total energy written in positions q and momenta p; its derivatives give how both change over time. , the total energy. The motion follows from its derivatives:
Along this flow , because the canonical matrix is skew-symmetric: energy is conserved. A spring with mass and stiffness has .
A network that learns the energy
ReadAn ordinary neural ODE learns directly, and nothing stops it from creating or losing energy. A Hamiltonian neural networkHamiltonian neural networkA network that learns one energy value per state and takes its motion from that energy's derivatives, so the learned flow conserves it. learns a scalar instead and takes the motion from its derivatives with the rule above. Training compares those derivatives with measured .
The learned flow then conserves exactly in continuous time. That is a built-in assumption: it suits frictionless systems in canonical coordinates, and it is wrong for damped or driven ones.
Reference · SEQ012 · Explained hereHamiltonian Neural NetworksAn architecture learning a scalar Hamiltonian whose derivatives define a vector field with canonical conservative structure.Check the identity
ExploreThe reference checks the conservation identity on a known spring with , , at , . The energy there is 0.775 and the instantaneous drift is 0.
import numpy as np
q, p, m, k = .7, .4, 2., 3.
grad_H = np.array([k * q, p / m]); field = np.array([p / m, -k * q]) # (dq/dt, dp/dt)
print(.5 * k * q * q + p * p / (2 * m), grad_H @ field) # energy, driftq <- .7; p <- .4; m <- 2; k <- 3
grad_H <- c(k * q, p / m); field <- c(p / m, -k * q) # (dq/dt, dp/dt)
print(c(.5 * k * q^2 + p^2 / (2 * m), sum(grad_H * field))) # energy, driftZero drift holds for the continuous flow. A computer takes discrete steps.
The solver can leak energy
ReadTo get a trajectory you integrate the flow with step . Explicit Euler updates position and momentum both from the old state. Symplectic Euler updates momentum first and uses the new momentum for the position:
Both approximate the same vector field. A symplectic integratorSymplectic integratorA step rule for Hamiltonian systems whose energy error stays bounded over long runs instead of drifting, as Euler steps do. keeps the geometry of Hamiltonian flow, so its energy error stays bounded over long runs. Explicit Euler's doesn't.
Predict the drift
PredictPredict first
A unit spring starts at , (energy one half) and is integrated for 400 steps of with each method. What happens to the energy?
Reveal
Euler climbs, symplectic Euler wobbles. Explicit Euler spirals outward: every step adds a little energy, and it compounds. Symplectic Euler's energy oscillates close to its start and doesn't drift away, though it isn't exactly constant either. Run the code in the next step to see both.
Run both solvers
Exploreimport numpy as np
h, steps = .05, 400
E = lambda q, p: .5 * q * q + .5 * p * p
qe, pe = 1., 0.; qs, ps = 1., 0.; drift_e = drift_s = 0.
for _ in range(steps):
qe, pe = qe + h * pe, pe - h * qe # explicit Euler: both from the old state
ps = ps - h * qs; qs = qs + h * ps # symplectic Euler: new momentum first
drift_e = max(drift_e, abs(E(qe, pe) - .5)); drift_s = max(drift_s, abs(E(qs, ps) - .5))
print("largest energy change: Euler", drift_e, "symplectic", drift_s)h <- .05; steps <- 400
E <- function(q, p) .5 * q^2 + .5 * p^2
qe <- 1; pe <- 0; qs <- 1; ps <- 0; drift_e <- 0; drift_s <- 0
for (i in seq_len(steps)) {
new <- c(qe + h * pe, pe - h * qe); qe <- new[1]; pe <- new[2] # explicit Euler
ps <- ps - h * qs; qs <- qs + h * ps # symplectic Euler
drift_e <- max(drift_e, abs(E(qe, pe) - .5)); drift_s <- max(drift_s, abs(E(qs, ps) - .5))
}
print(c(euler = drift_e, symplectic = drift_s))Halve and run again: both errors shrink, but only Euler's keeps growing with time. Add a damping term to and energy should fall; the Hamiltonian form can no longer describe the system.
Notebook exercise · ~12 min
Energy drift, Euler against leapfrog
Integrate a frictionless oscillator with explicit Euler and with leapfrog, track the energy, and measure how leapfrog's error shrinks with the step.
- Explicit Euler
Take 500 Euler steps with dt = 0.1 from (q, p) = (1, 0). Store the energy at the end in
energy_euler.Show a solution
Pythonq, p = 1.0, 0.0 for _ in range(500): q, p = euler(q, p, 0.1) energy_euler = energy(q, p)Rs <- c(1, 0) for (i in 1:500) s <- euler(s[1], s[2], 0.1) energy_euler <- energy(s[1], s[2]) - Leapfrog's largest drift
Take 500 leapfrog steps with dt = 0.1. Store the largest absolute difference between the energy after any step and the starting energy 0.5 in
drift_01.Show a solution
Pythondef max_drift(dt, n): q, p, worst = 1.0, 0.0, 0.0 for _ in range(n): q, p = leapfrog(q, p, dt) worst = max(worst, abs(energy(q, p) - 0.5)) return worst drift_01 = max_drift(0.1, 500)Rmax_drift <- function(dt, n) { s <- c(1, 0); worst <- 0 for (i in seq_len(n)) { s <- leapfrog(s[1], s[2], dt) worst <- max(worst, abs(energy(s[1], s[2]) - 0.5)) } worst } drift_01 <- max_drift(0.1, 500) - Halve the step
Run leapfrog over the same time span with dt = 0.05 (1,000 steps) and store the ratio of the two largest drifts, drift at dt = 0.1 divided by drift at dt = 0.05, in
ratio.Show a solution
Pythonratio = drift_01 / max_drift(0.05, 1000)Rratio <- drift_01 / max_drift(0.05, 1000)
In the app this opens as a Python or R notebook with the sample data, and its checks mark your progress.
DExplorable · Symplectic integrators and energy drift
Why does a simulated orbit slowly gain energy, and how do some solvers avoid it?
Over this run, what will the selected integrator's energy do?
System
A mass on a spring, or a swinging pendulum (nonlinear: wide swings take longer).
Integrator
Explicit Euler and Runge–Kutta 4 aren't symplectic; symplectic Euler and leapfrog are.
Time between solver steps. One spring period is 2π ≈ 6.28.
How many steps to run.
Starting position, released from rest.
Largest energy error: Explicit Euler 631.60% · Symplectic Euler 5.26% · Leapfrog 0.25% · Runge–Kutta 4 2.8×10⁻⁴%. Gray lines are the other three integrators; errors below 10⁻¹² are drawn at the bottom.
Commit your prediction above to see the result
Make your prediction to see the result.
Two kinds of error
ReadWhen a trained Hamiltonian network's rollout drifts, there are two suspects. Modeling error: is the wrong energy, or the system isn't Hamiltonian. Integration error: the solver and step size leak energy from a correct flow. Separate them by integrating the known or learned with a symplectic method and a smaller step before blaming the model.
A real HNN study would also fit the energy network and test it on trajectories it never saw, from new starting states.
What runs here
ReadCheck: Hamiltonian dynamics
CheckpointCheck yourself
What does a Hamiltonian neural network learn?
Show the answer
Answer: b
The motion is derived from the learned energy, which builds conservation into the continuous flow.
Check yourself
For , what is ?
Show the answer
Answer: a
, and .
Check yourself
Your pendulum data include friction. What goes wrong with a basic Hamiltonian network?
Show the answer
Answer: b
The basic form assumes an autonomous, frictionless system in canonical coordinates. Damping or forcing needs a different model.
Check yourself
Integrating the same known oscillator, explicit Euler's energy grows while symplectic Euler's wobbles. What explains the difference?
Show the answer
Answer: b
Both follow , . Updating momentum first gives the symplectic method its bounded error.
Check yourself
A trained HNN's rollouts gain energy over time. What should you check first?
Show the answer
Answer: b
Integration error is not model uncertainty. Rule out the solver before blaming the learned energy.
Recap
Recap- A Hamiltonian gives the motion through its derivatives, and that flow conserves energy.
- An HNN learns the energy, not the motion, so its continuous flow conserves it.
- Solvers can leak energy: explicit Euler drifts, symplectic Euler stays in a band.
- Separate integration error from modeling error. HNNs are explained here only.
Concepts in this lesson