Skip to content

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.

Advanced ~18 min10 steps

What runs in CodeSplash

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

Read first

01

Energy decides the motion

Read

A frictionless system can be written with positions qq, momenta pp and one function, its HamiltonianHamiltonianA system's total energy written in positions q and momenta p; its derivatives give how both change over time. H(q,p)H(q, p), the total energy. The motion follows from its derivatives:

q˙=∂H∂p,p˙=−∂H∂q.\dot q = \frac{\partial H}{\partial p}, \qquad \dot p = -\frac{\partial H}{\partial q}.

Along this flow dHdt=∇H⊤J∇H=0\frac{dH}{dt} = \nabla H^\top J \nabla H = 0, because the canonical matrix JJ is skew-symmetric: energy is conserved. A spring with mass mm and stiffness kk has H=12kq2+p2/(2m)H = \tfrac{1}{2} k q^2 + p^2 / (2m).

02

A network that learns the energy

Read

An ordinary neural ODE learns (q˙,p˙)(\dot q, \dot p) 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 Hθ(q,p)H_\theta(q, p) instead and takes the motion from its derivatives with the rule above. Training compares those derivatives with measured (q˙,p˙)(\dot q, \dot p).

The learned flow then conserves HθH_\theta 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.
03

Check the identity

Explore

The reference checks the conservation identity on a known spring with m=2m = 2, k=3k = 3, at q=0.7q = 0.7, p=0.4p = 0.4. The energy there is 0.775 and the instantaneous drift ∇H⊤(q˙,p˙)\nabla H^\top (\dot q, \dot p) is 0.

Python
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, drift
R
q <- .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, drift

Zero drift holds for the continuous flow. A computer takes discrete steps.

04

The solver can leak energy

Read

To get a trajectory you integrate the flow with step hh. Explicit Euler updates position and momentum both from the old state. Symplectic Euler updates momentum first and uses the new momentum for the position:

pt+1=pt−h ∂H∂q(qt),qt+1=qt+h pt+1m.p_{t+1} = p_t - h\,\frac{\partial H}{\partial q}(q_t), \qquad q_{t+1} = q_t + h\,\frac{p_{t+1}}{m}.

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.

05

Predict the drift

Predict

Predict first

A unit spring starts at q=1q = 1, p=0p = 0 (energy one half) and is integrated for 400 steps of h=0.05h = 0.05 with each method. What happens to the energy?

Both stay at the starting energyEuler's energy climbs steadily; symplectic Euler's wobbles in a narrow bandSymplectic Euler's energy climbs; Euler's stays flat
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.

06

Run both solvers

Explore
Python
import 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)
R
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 hh and run again: both errors shrink, but only Euler's keeps growing with time. Add a damping term to p˙\dot p 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.

  1. 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
    Python
    q, p = 1.0, 0.0
    for _ in range(500):
        q, p = euler(q, p, 0.1)
    energy_euler = energy(q, p)
    R
    s <- c(1, 0)
    for (i in 1:500) s <- euler(s[1], s[2], 0.1)
    energy_euler <- energy(s[1], s[2])
  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
    Python
    def 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)
    R
    max_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)
  3. 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
    Python
    ratio = drift_01 / max_drift(0.05, 1000)
    R
    ratio <- 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?

How sure?

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.

0.10

Time between solver steps. One spring period is 2π ≈ 6.28.

200

How many steps to run.

1.0

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 first; the figure appears when you commit.

Make your prediction to see the result.

07

Two kinds of error

Read

When a trained Hamiltonian network's rollout drifts, there are two suspects. Modeling error: HθH_\theta 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 HH 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.

08

What runs here

Read
09

Check: Hamiltonian dynamics

Checkpoint

Check 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 H=12kq2+p2/(2m)H = \tfrac12 k q^2 + p^2/(2m), what is q˙\dot q?

Show the answer

Answer: a

q˙=∂H/∂p=p/m\dot q = \partial H / \partial p = p/m, and p˙=−∂H/∂q=−kq\dot p = -\partial H / \partial q = -kq.

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 q˙=p\dot q = p, p˙=−q\dot p = -q. 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.

10

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