Track: core · Prerequisites: Part I (Chapters 1–4), statistical mechanics
This chapter builds and verifies the core algorithms for velocity rescaling, berendsen, and bussi–donadio–parrinello (csvr) thermostats 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)5.1 Physical principles and governing equations¶
In the canonical () ensemble, total kinetic energy is not constant — it follows a Gamma / distribution with exact mean and variance:
The Berendsen thermostat rescales velocities deterministically toward , collapsing (failing the canonical ensemble). Bussi–Donadio–Parrinello (CSVR) draws the target kinetic energy stochastically from the exact distribution with relaxation time .
5.2 Inside the algorithm¶
T_target = 1.2
v_ber = es.init_velocities(64, T_target, rng=rng)
v_csvr = v_ber.copy()
K_ber, K_csvr = [], []
for _ in range(1800):
v_ber = es.berendsen_thermostat(v_ber, T_target, dt=0.01, tau_T=0.1)
v_csvr = es.bussi_csvr_thermostat(v_csvr, T_target, dt=0.01, tau_T=0.1, rng=rng)
K_ber.append(0.5 * float(np.sum(v_ber**2)))
K_csvr.append(0.5 * float(np.sum(v_csvr**2)))5.3 Checks¶
var_exact = es.reference.canonical_ke_variance_exact(64, T_target)
mean_exact = 0.5 * (3 * 63) * T_target
print(f"Exact NVT: <K>={mean_exact:.2f}, Var(K)={var_exact:.2f}")
print(f"Bussi CSVR: <K>={np.mean(K_csvr[300:]):.2f}, Var(K)={np.var(K_csvr[300:]):.2f}")
print(f"Berendsen: <K>={np.mean(K_ber[300:]):.2f}, Var(K)={np.var(K_ber[300:]):.2e}")
assert np.isclose(np.mean(K_csvr[300:]), mean_exact, rtol=0.08)
assert np.var(K_csvr[300:]) > 0.6 * var_exact
assert np.var(K_ber[300:]) < 1e-5 * var_exact
t_steps = np.arange(len(K_csvr)) * 0.01
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.8, 4.1))
ax1.plot(t_steps[:500], K_csvr[:500], "b-", label="Bussi CSVR")
ax1.plot(t_steps[:500], K_ber[:500], "r--", label="Berendsen")
ax1.axhline(mean_exact, color="k")
ax1.set_xlabel("Time t [tau]"); ax1.set_ylabel("Kinetic Energy K(t) [eps]")
ax1.set_title("(a) Canonical Fluctuations: CSVR vs Berendsen"); panel_label(ax1, "(a)")
bins = np.linspace(mean_exact - 4*np.sqrt(var_exact), mean_exact + 4*np.sqrt(var_exact), 25)
hist_c, edges_c = np.histogram(K_csvr[300:], bins=bins, density=True)
centers_c = 0.5 * (edges_c[:-1] + edges_c[1:])
gauss_ref = np.exp(-0.5 * ((centers_c - mean_exact)**2) / var_exact) / np.sqrt(2*np.pi*var_exact)
ax2.plot(centers_c, gauss_ref, "k-", label="Exact Canonical")
ax2.plot(centers_c, hist_c, "bo", label="CSVR Histogram")
ax2.set_xlabel("Kinetic Energy K [eps]"); ax2.set_ylabel("Probability Density P(K)")
ax2.set_title("(b) Exact NVT Kinetic Distribution"); panel_label(ax2, "(b)")
plt.show()Exact NVT: <K>=113.40, Var(K)=136.08
Bussi CSVR: <K>=113.13, Var(K)=117.40
Berendsen: <K>=113.40, Var(K)=2.02e-28

Figure 5.1. (a) Primary physical or dynamical observable computed from scratch in engsim. (b) Quantitative verification against the analytical or benchmark reference.
5.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¶
Tau independence of CSVR variance: Verify that
bussi_csvr_thermostatreproduces for both and .Coupled LJTS NVT-CSVR fluid: Couple
bussi_csvr_thermostattovelocity_verlet_stepon a 108-atom LJTS fluid and verify mean temperature convergence.Heat capacity error under Berendsen: Show how suppressing biases the Lebowitz fluctuation formula for .
Worked solutions are provided in 05_solutions.ipynb.
Suggested references¶
G. Bussi, D. Donadio, and M. Parrinello, J. Chem. Phys. 126, 014101 (2007).
B. Leimkuhler and C. Matthews, Molecular Dynamics: With Deterministic and Stochastic Numerical Methods (Springer, 2015).