fhat. GitHub Workspace

Störmer–Verlet (leapfrog)

Stable long-time simulation of conservative mechanical systems.

errorO(h2)cost1 f / stepsymplectic · reversible · explicit

Also known as velocity Verlet, position Verlet, kick-drift-kick, drift-kick-drift

Full skillv0.1.5Example

Use with your agent

Use the fhat method "stormer-verlet" (https://fhat.dev/methods/stormer-verlet/SKILL.md) for this problem. Check first whether it applies.

1. What this solves

You want to follow a system of particles or bodies that move under forces derived from a potential energy, such as planets around a star, atoms in a molecule or masses on springs, for many oscillations or orbits. A general-purpose solver lets the total energy creep up or down over a long run, so the simulation slowly stops being physical. Störmer–Verlet keeps the energy error small and bounded for very long times, at the cost of one force evaluation per step.

In technical terms: it is a second-order, explicit, symplectic and time-reversible integrator for separable Hamiltonians H(q,p)=12p⊤M−1p+V(q)H(q,p) = \tfrac12 p^\top M^{-1} p + V(q). It exactly conserves linear and angular momentum when the forces do.

2. When to use

  • Equations of motion q˙=M−1p\dot q = M^{-1}p, p˙=F(q)=−∇V(q)\dot p = F(q) = -\nabla V(q): the force depends on positions only, masses are constant, and there is no explicit time dependence.
  • Long runs where qualitative correctness matters (energy, phase-space structure, conserved momenta): molecular dynamics in the NVE ensemble, celestial mechanics, lattice and spring models.
  • A fixed step size hh is acceptable. For a fastest oscillation of angular frequency ω\omega, stability requires hω<2h\omega < 2; in practice use hω≲0.5h\omega \lesssim 0.5 or smaller for accuracy.
  • Moderate accuracy is enough: the error is O(h2)O(h^2).

3. When not to use (and what to use instead)

Situation Use instead
Force depends on velocity (friction, drag, magnetic forces, thermostats) A general ODE solver such as dormand-prince-rk45, or a splitting designed for that term (for example a Langevin splitting)
You need much higher accuracy per unit of work on a smooth problem yoshida4 (fourth order, still symplectic)
Stiff problem: very fast modes you do not need to resolve An implicit method such as backward-euler or implicit-midpoint
Non-separable Hamiltonian, e.g. position-dependent mass implicit-midpoint (symplectic for any Hamiltonian)
Adaptive step sizes or output at arbitrary times, over a short or moderate run dormand-prince-rk45
Output at arbitrary times over a long run where energy must stay bounded Keep Verlet at a fixed step and interpolate between steps, or choose hh so that the output times fall on the step grid. Do not change hh from step to step: that destroys the long-time energy behaviour.
Holonomic constraints (fixed bond lengths, rigid molecules) A constrained variant such as RATTLE or SHAKE, or SETTLE for rigid water (not in this library)

4. Algorithm

Let hh be the step size, MM the diagonal mass matrix and F(q)=−∇V(q)F(q) = -\nabla V(q).

Kick-drift-kick (velocity Verlet), the usual form:

pn+1/2=pn+h2F(qn),qn+1=qn+h M−1pn+1/2,pn+1=pn+1/2+h2F(qn+1).p_{n+1/2} = p_n + \tfrac{h}{2} F(q_n),\qquad q_{n+1} = q_n + h\, M^{-1} p_{n+1/2},\qquad p_{n+1} = p_{n+1/2} + \tfrac{h}{2} F(q_{n+1}).

Keep F(qn+1)F(q_{n+1}) for the first kick of the next step, so each step costs one force evaluation (plus one at the start).

Drift-kick-drift (position Verlet):

qn+1/2=qn+h2M−1pn,pn+1=pn+hF(qn+1/2),qn+1=qn+1/2+h2M−1pn+1.q_{n+1/2} = q_n + \tfrac{h}{2} M^{-1} p_n,\qquad p_{n+1} = p_n + h F(q_{n+1/2}),\qquad q_{n+1} = q_{n+1/2} + \tfrac{h}{2} M^{-1} p_{n+1}.

Both forms are second order, symplectic and time-reversible. They are conjugate to each other (they differ only by a half drift or half kick at the start and end of a run), so their long-time behaviour is the same. Choose KDK when you want positions and momenta (and forces) at the same time points; DKD is natural when forces are wanted at midpoints. Running with −h-h integrates backwards.

5. Parameters

Parameter How to choose it
Step size hh Set by the fastest motion: start near h≈0.05h \approx 0.05–0.10.1 of the shortest period and confirm with the energy check in section 7. Halving hh divides errors by about 4.
Form (KDK or DKD) Equivalent accuracy. KDK is the common choice in molecular dynamics.
Output interval Output every rr steps without changing hh; output does not affect the trajectory.

6. Applying it to your own code

  • Store momenta, p=Mvp = Mv, or equivalently velocities with v+=h2F/mv \mathrel{+}= \tfrac{h}{2} F/m in the kicks. Repeat each atom's mass over its x,y,zx, y, z coordinates.
  • The force must be −∇V-\nabla V for a single potential VV, with consistent units. Check the sign: a wrong sign makes the system fly apart.
  • Evaluate the force once per step (reuse the force from the end of the previous KDK step). The force routine is usually the only expensive part.
  • reference/stormer_verlet.py shows the exact update order in a few lines; translate the arithmetic directly to NumPy, JAX, PyTorch, C++ or Fortran. Nothing else in the file is essential.
  • When you write code using this method, add the comment stormer-verlet v0.1.5, Hairer, Lubich & Wanner (2006).

7. Verification

Step 1: check your implementation against this skill. Do this after porting and before using the results. Show the output to the user.

  • Get the files: put checks/check_port.py and checks/cases.json in the same folder (the script reads cases.json from beside itself). Through MCP, fetch both with get_file; or download and unpack the skill's zip.

  • Python: create port_adapter.py in your working directory with SCHEMES = ("kdk",) (or the forms you implemented) and a function integrate(q0, p0, h, n_steps, mass, force, scheme) that calls your code and returns the final (q, p) with canonical momenta. Then run it from the directory that contains port_adapter.py, with the Python environment in which your code works:

    python <folder-with-the-check-files>/check_port.py
    

    It compares your results with fixed cases computed by the reference implementation (only rounding differences are allowed), and checks convergence order 2, bounded energy over 1,000 periods (unit mass) and on two springs with different masses, and returning to the start after integrating with −h-h.

  • Other languages: run each case in checks/cases.json with your code (problems, initial states, step sizes and step counts are given there) and compare q and p with expected within tol.

A failed fixed case almost always means a porting mistake: force sign, half versus full kicks, a missing kick, momentum used as velocity, or KDK and DKD mixed up.

Step 2: check the method on your own problem.

  1. Convergence order. Integrate to a fixed time with hh, h/2h/2, h/4h/4, compared with a much finer run or an exact solution. The error ratio should approach 4, an observed order near 2.
  2. Energy. Record H(q,p)H(q,p) every step over a long run. The error should oscillate around a constant level proportional to h2h^2, with no systematic growth. Compare the maximum error over the first and last tenth of the run.
  3. Reversibility. Integrate NN steps, flip the sign of the momenta, integrate NN more steps and flip back. You should return to the initial state up to rounding error.
  4. Conserved momenta. If the forces conserve total linear or angular momentum, those should stay constant to rounding error.

8. Failure signatures

Symptom Likely cause
Observed order near 1 Velocity-dependent force used inside the kicks, or the force is evaluated at the wrong position. verify/check_negative.py shows the velocity-dependent case.
Energy grows steadily Step size changed during the run, or a non-conservative force.
Energy jumps, then the run blows up Step size above the stability limit hω<2h\omega < 2 for the fastest mode, or particles getting too close (singular potential).
System expands or collapses immediately Force sign error (F=+∇VF = +\nabla V), or mixing velocities and momenta with non-unit masses.
Results depend on output frequency Output code modifies the state, or the force is recomputed inconsistently.

9. Files and commands

Run from this folder with uv and Python 3.11 or newer; only the standard library is used.

uv run examples/harmonic.py
uv run examples/kepler.py
uv run verify/check_order.py
uv run verify/check_energy.py
uv run verify/check_reversibility.py
uv run verify/check_negative.py
uv run verify/check_cases.py
  • reference/stormer_verlet.py: KDK and DKD steps and a fixed-step driver.
  • examples/: harmonic oscillator convergence table and a 100-period Kepler orbit; expected output in *.expected.txt.
  • checks/: for checking your implementation. cases.json holds fixed cases; check_port.py runs them and the property checks through port_adapter.py; make_cases.py regenerates cases.json from the reference implementation.
  • verify/: evidence for the claims in this file, run on the reference implementation: convergence order, long-time energy and angular momentum, reversibility and cost, the failure for velocity-dependent forces, and that the fixed cases catch five typical porting mistakes.

10. Sources

Evidence

Output of the verification scripts, run on the reference implementation of version 0.1.5 when this page was built.

Passed verify/check_order.py: Global error at a fixed time converges at order 2 for KDK and DKD (harmonic oscillator, Kepler orbit, non-unit masses).
PASS harmonic oscillator, KDK: orders 1.998, 1.999, 2.000, 2.000 (expected in (1.9, 2.1))
PASS harmonic oscillator, DKD: orders 2.001, 2.000, 2.000, 2.000 (expected in (1.9, 2.1))
PASS Kepler one period, KDK: orders 2.001, 2.000, 2.000 (expected in (1.9, 2.1))
PASS Kepler one period, DKD: orders 1.999, 2.000, 2.000 (expected in (1.9, 2.1))
PASS oscillator with masses (2, 0.5): orders 2.003, 2.001, 2.000 (expected in (1.9, 2.1))
Passed verify/check_energy.py: Energy error stays bounded over 10,000 oscillator periods and 1,000 Kepler orbits while a non-symplectic second-order method drifts; angular momentum is conserved to rounding.
PASS harmonic, Verlet, 10,000 periods: max energy error first 100 periods 1.250e-03, last 100 periods 1.250e-03
PASS contrast, explicit midpoint, 1,000 periods: energy error grows from 8.504e-02 to 1.905e+00
PASS Kepler, 1,000 periods: max relative energy error first 100 periods 2.689e-03, last 100 periods 2.689e-03
PASS Kepler, 1,000 periods: max angular momentum change 3.5e-14 (rounding only)
Passed verify/check_reversibility.py: Momentum-flip and negative-step round trips return to the start within 1e-10; output frequency does not change the trajectory; one force evaluation per step.
PASS KDK: momentum-flip round trip over 2000 steps returns to start within 2.5e-12
PASS KDK: forward then negative step returns to start within 2.5e-12
PASS DKD: momentum-flip round trip over 2000 steps returns to start within 1.4e-12
PASS DKD: forward then negative step returns to start within 1.4e-12
PASS output every 1 and every 300 steps give identical states at shared steps
PASS KDK: 500 steps used 501 force evaluations (expected 501)
PASS DKD: 500 steps used 500 force evaluations (expected 500)
Passed verify/check_negative.py: A velocity-dependent force inside the kicks drops the method to first order, the failure documented in SKILL.md.
PASS damped oscillator with a naive velocity-dependent kick: orders 1.019, 1.010, 1.005 (first order, as documented)
Passed verify/check_cases.py: checks/cases.json matches the reference implementation; the reference and an independent correct port pass checks/check_port.py; five typical porting mistakes are each caught by the fixed cases.
PASS checks/cases.json equals the output of checks/make_cases.py
PASS reference implementation passes all 16 port checks
PASS a correct independent port (lists, force recomputed each step) passes
PASS broken port caught by the fixed cases: force sign flipped (F = +grad V) (fails 8 of 8)
PASS broken port caught by the fixed cases: momentum used as velocity (mass ignored) (fails 2 of 8)
PASS broken port caught by the fixed cases: full kicks instead of half kicks (fails 4 of 8)
PASS broken port caught by the fixed cases: second half kick missing (fails 4 of 8)
PASS broken port caught by the fixed cases: KDK and DKD swapped (fails 8 of 8)

The methods shown are examples. More research methods are coming.