Track: core · Prerequisites: Chapter 1, ODE integration (engnumeric)
This chapter builds and verifies the core algorithms for time integration: euler, velocity verlet, and symplectic shadow hamiltonians in plain Python and NumPy, checking every result against an exact statistical-mechanics limit or published benchmark.
import sys
from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt
REPO_ROOT = Path(__file__).resolve().parents[2] if "__file__" in globals() else Path("../..").resolve()
if str(REPO_ROOT) not in sys.path:
sys.path.insert(0, str(REPO_ROOT))
import engsim as es
from engsim.plotting import panel_label, use_style
use_style()
rng = np.random.default_rng(2026)2.1 Physical principles and governing equations¶
The Velocity Verlet integrator splits Hamiltonian evolution symmetrically into half-kick, drift, force evaluation, and half-kick:
Because Velocity Verlet is symplectic and time-reversible, it conserves a nearby shadow Hamiltonian with zero secular energy drift over long trajectories, whereas explicit Euler spirals outward exponentially.
2.2 Inside the algorithm¶
pos0, L0 = es.make_fcc_lattice(3, rho=0.72)
vel0 = es.init_velocities(len(pos0), T_target=1.2, rng=rng)
f_fn = lambda p, L: es.lj_forces_all_pairs(p, L, rc=2.5, shifted=True)
def run_nve_drift(dt: float, n_steps: int) -> tuple[np.ndarray, float]:
p, v = pos0.copy(), vel0.copy()
f, u, _ = f_fn(p, L0)
E = np.zeros(n_steps)
for k in range(n_steps):
p, v, f, u, _, _ = es.velocity_verlet_step(p, v, f, dt, L0, f_fn)
E[k] = 0.5 * float(np.sum(v * v)) + u
return E, float(np.std(E))2.3 Checks¶
# 1. Verify O(dt^2) energy fluctuation scaling across dt = [0.002, 0.004, 0.008]
dts = np.array([0.002, 0.004, 0.008])
stds = []
for dt_v in dts:
E_tr, s_e = run_nve_drift(float(dt_v), n_steps=int(0.4 / dt_v))
stds.append(s_e)
stds = np.array(stds)
slope = float(np.polyfit(np.log(dts), np.log(stds), 1)[0])
print(f"Velocity Verlet energy-fluctuation scaling slope = {slope:.2f} (expected 2.00)")
assert 1.7 <= slope <= 2.3
# 2. Exact Time-Reversibility Test (25 steps forward, flip v -> -v, 25 steps back)
p, v = pos0.copy(), vel0.copy()
f, u, _ = f_fn(p, L0)
for _ in range(25):
p, v, f, u, _, _ = es.velocity_verlet_step(p, v, f, 0.005, L0, f_fn)
v = -v
for _ in range(25):
p, v, f, u, _, _ = es.velocity_verlet_step(p, v, f, 0.005, L0, f_fn)
rev_err = float(np.max(np.abs(es.minimum_image(p - pos0, L0))))
print(f"Time-reversal position error after 50 steps = {rev_err:.2e}")
assert rev_err < 1e-10
# 3. Diagnostic Figure: Euler vs Velocity Verlet on 1D Harmonic Oscillator & O(dt^2) scaling
t_ho = np.arange(0, 400) * 0.05
x_e, v_e = 1.0, 0.0
E_euler, E_vv = [], []
x_v, v_v = 1.0, 0.0
for _ in t_ho:
x_e_new = x_e + 0.05 * v_e; v_e = v_e - 0.05 * x_e; x_e = x_e_new
E_euler.append(0.5 * (x_e**2 + v_e**2))
v_h = v_v - 0.025 * x_v; x_v = x_v + 0.05 * v_h; v_v = v_h - 0.025 * x_v
E_vv.append(0.5 * (x_v**2 + v_v**2))
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.8, 4.1))
ax1.plot(t_ho, E_euler, "r--", label="Explicit Euler")
ax1.plot(t_ho, E_vv, "b-", label="Velocity Verlet")
ax1.set_xlabel("Time t [tau]"); ax1.set_ylabel("Total Energy E(t) [eps]")
ax1.set_title("(a) Symplectic Conservation vs Euler Drift"); panel_label(ax1, "(a)")
ax2.loglog(dts, stds, "bo-", label="Velocity Verlet std(E)")
ax2.loglog(dts, stds[0] * (dts / dts[0])**2, "k--", label="O(dt^2) reference")
ax2.set_xlabel("Timestep log10(dt)"); ax2.set_ylabel("Energy Fluctuation std(E)")
ax2.set_title("(b) Second-Order Shadow Hamiltonian Scaling"); panel_label(ax2, "(b)")
plt.show()Velocity Verlet energy-fluctuation scaling slope = 2.05 (expected 2.00)
Time-reversal position error after 50 steps = 8.88e-16

Figure 2.1. (a) Primary physical or dynamical observable computed from scratch in engsim. (b) Quantitative verification against the analytical or benchmark reference.
2.4 What to trust¶
Numerical predictions are verified to the stated tolerances against exact analytical limits (
engsim.reference).Finite-size effects (, periodic image interactions) and timestep truncation () should always be checked before comparing against bulk experimental data.
Summary¶
The algorithm is implemented transparently in pure NumPy without hidden black-box routines.
All core physical invariants (conservation laws, ensemble variance, or scaling exponents) are verified quantitatively in code.
Exercises¶
Momentum conservation: Verify that total linear momentum stays zero to over 200 Velocity Verlet steps.
Stability threshold: Find the maximum stable timestep for a 1D harmonic oscillator () under Velocity Verlet (exact theoretical limit ).
Shadow energy: Verify that is conserved to on the harmonic oscillator.
Worked solutions are provided in 02_solutions.ipynb.
Suggested references¶
D. Frenkel and B. Smit, Understanding Molecular Simulation (3rd ed., Academic Press, 2023).
M. P. Allen and D. J. Tildesley, Computer Simulation of Liquids (2nd ed., Oxford University Press, 2017).