Tutorial T02: Canonical Thermostat Accuracy
Finite-timestep discretization errors in canonical (ParticleDynamics v1.2.0 at Float64 precision on a dense 3D anharmonic Lennard-Jones liquid against two standard statistical-mechanics benchmarks:
Leimkuhler & Matthews (2013) (Appl. Math. Res. Express 2013, 34–56; J. Chem. Phys. 138, 174102) and Grønbech-Jensen & Farago (2013) (Mol. Phys. 111, 983–991): separating configurational sampling bias from kinetic-temperature discretization bias across
BAOAB,BAOABFast,BAOA,VelocityVerlet(GJF Langevin), half-stepCSVR, and full-stepNoseHooverChain, alongside software parity checks (BAOABvs.BAOABFast), on-the-flydU/dqfirst-law tracking, and a high-friction discrete-time stability diagnostic.Bussi, Donadio & Parrinello (2007) (J. Chem. Phys. 126, 014101): testing the canonical kinetic energy distribution (mean
and variance with ) and monitoring the linear drift of the effective energy and Nosé–Hoover chain extended Hamiltonian(both :gromacs4th-order SY5 and:lammpsMTTK propagators) viaBathExchangeObservable.
Trajectory Visualization

_Path-traced Fresnel studio snapshot (tutorials/render_snapshots.py --targets T02) of the dense 3D anharmonic Lennard-Jones liquid (N = 512, \rho^_ = 0.80, T^* = 1.00$) colored by instantaneous per-particle kinetic energy$\frac{1}{2} m v_i^2 across the canonical Maxwell–Boltzmann distribution.*
Physical Model & Benchmark Setup
All runs simulate a dense 3D liquid of Float64 precision:
State point: reduced number density
(cubic periodic box ), target temperature ( ), kinetic degrees of freedom .Smooth
pair potential: LennardJoneswithvdw_modifier = :force_switch,switch_distance = 2.0, andcutoff = 2.5. Because, , and vanish continuously at , cutoff-crossing impulses are eliminated, ensuring that timestep biases and effective-energy drift reflect integrator discretization rather than truncation noise.Coupling parameters: Langevin friction
for the main timestep sweep (plus a high-friction discrete stability diagnostic at , ); global thermostat relaxation time forCSVR(interval = 1) andNoseHooverChain(chain_length = 5,substeps = 5).
ParticleDynamics v1.2.0 API Walkthrough
1. Smooth Force-Switched LJ & All Six Canonical Propagators
Each canonical scheme is selected declaratively inside Integrator while sharing the same ParticleSystem, CellList, and Float64 state:
using ParticleDynamics
allp = Group(:all, AllSelection())
lj = LennardJones(
epsilon=1.0,
sigma=1.0,
cutoff=2.5,
vdw_modifier=:force_switch,
switch_distance=2.0,
pairs=:neighborlist,
neighborlist=CellList(buffer=0.4, capacity=128, rebuild_interval=10),
)
# Stochastic Langevin schemes
int_baoab = Integrator(dt=0.004, scheme=BAOAB(), forces=[lj], methods=[Langevin(allp; gamma=1.0, kT=1.0)])
int_fast = Integrator(dt=0.004, scheme=BAOABFast(), forces=[lj], methods=[Langevin(allp; gamma=1.0, kT=1.0)])
int_baoa = Integrator(dt=0.004, scheme=BAOA(), forces=[lj], methods=[Langevin(allp; gamma=1.0, kT=1.0)])
int_gjf = Integrator(dt=0.004, scheme=VelocityVerlet(), forces=[lj], methods=[Langevin(allp; gamma=1.0, kT=1.0)])
# Global canonical thermostats on ConstantVolume Velocity Verlet
# Pass nstcomm=0 here to audit the unprojected d = 3N canonical distribution and strict H_tilde conservation
# (v1.2.0 defaults to nstcomm=100, subtracting D translational DOF for production runs)
int_csvr = Integrator(dt=0.002, forces=[lj], methods=[ConstantVolume(allp; thermostat=CSVR(kT=1.0, tau=0.5, interval=1, nstcomm=0))])
int_nhc_g = Integrator(dt=0.002, forces=[lj], methods=[ConstantVolume(allp; thermostat=NoseHooverChain(kT=1.0, tau=0.5, chain_length=5, substeps=5, propagator=:gromacs, nstcomm=0))])
int_nhc_l = Integrator(dt=0.002, forces=[lj], methods=[ConstantVolume(allp; thermostat=NoseHooverChain(kT=1.0, tau=0.5, chain_length=5, substeps=5, propagator=:lammps, nstcomm=0))])2. Zero-Disk Sampling with InMemoryWriter & BathExchangeObservable
Rather than writing large intermediate text tables during multi-run sweeps, attach ThermodynamicObservable, BathExchangeObservable, and PressureObservable directly to an InMemoryWriter and read typed column vectors via recorded_data:
thermo = ThermodynamicObservable(allp; name=:thermo)
bath = BathExchangeObservable(name=:bath)
press = PressureObservable(name=:press)
mem = InMemoryWriter(
every=100,
observables=[
thermo => [:temperature, :kinetic_energy, :potential_energy, :total_energy, :virial],
bath => [:heat, :temperature_error, :extended_hamiltonian],
press => [:pressure, :volume],
],
)
sim = Simulation(
sys_eq;
groups=Groups(allp),
observables=[thermo, bath, press],
writers=[mem],
precision=Float64,
seed=5001,
integrator=int_csvr,
)
run!(sim, Stage(:eq, steps=10_000; progress=false))
empty!(mem)
run!(sim, Stage(:prod, steps=200_000; reset_observables=true, reset_step=0, progress=false))
data = recorded_data(mem)
dof = kinetic_dof(state(sim)) # 1536 (= 3N for unconstrained 3D liquid)Passing reset_observables=true, reset_step=0 on the production Stage zeroes the GPU bath-exchange accumulators (st.dq, st.dU, and CSVR/NHC cumulative_energy_exchange_per_bath) together with the workflow interval ledger, so data.bath.extended_hamiltonian starts cleanly at
Results & Quantitative Verification
Part 1: Configurational Accuracy vs. Kinetic Temperature Bias

In a dense anharmonic liquid, the Velocity Verlet discrete shadow Hamiltonian couples full-step kinetic temperature
where BAOAB's own run.jl and analyze.jl have since been updated to log forces during the
Across the
BAOABandBAOABFast(Leimkuhler–Matthews splitting): At ,BAOAB's configurational potential-energy difference from the reference is (, statistically consistent with zero), and BAOABFastgives (). Note that at and precision, these runs test the absence of leadingharmonic configurational bias rather than high-friction fourth-order superconvergence (which requires large and much tighter statistical error bars to resolve). BAOA(): Because ,BAOAis the half-kick leapfrog conjugate ofBAOAB( ). It samples the same unbiased configurational ensemble ( ,at ) while recording velocities immediately after the Ornstein–UhlenbeckOstep, keeping kinetic temperature consistent with( ,). VelocityVerletwithLangevin(Grønbech-Jensen/Farago GJF): At , GJF also keeps configurational bias statistically consistent with zero ( ,at ) with the same full-stepshadow depression. Half-step
CSVRvs. full-stepNoseHooverChain:ParticleDynamics v1.2.0appliesCSVRto the half-step leapfrog velocity (matching GROMACSv-rescale), eliminating harmonic configurational bias ( ,at ). Conversely,NoseHooverChainthermostats the full-step kinetic energy to , inducing configurational overheating ( ). Using the canonical configurational heat capacity extracted fromCSVRenergy fluctuations ( at ), linear response predictsagreeing within
with the measured NHC overheating bias of (above zero; orin configurational virial). Mechanical pressure bias from full-step
: Although BAOAB,BAOABFast,VV_GJF, andCSVRpreserve the configurational virialat , the standard full-step mechanical pressure inherits the ideal-gas depression . Consequently,sits below across these schemes (e.g.,CSVR: , ,; VV_GJF:; BAOAB:). In large-timestep NPT simulations, barostats should not couple to biased full-step ; instead use the target ideal-gas term (as StochasticCellRescalingdoes inParticleDynamics), half-step velocities, or a Monte Carlo barostat.
Table 1: Timestep Accuracy on the Dense 3D Force-Switched LJ Liquid (N = 512, ρ* = 0.80, T* = 1.00, Float64)
Reference canonical baseline (BAOAB,
| Integrator / Thermostat | |||||
|---|---|---|---|---|---|
BAOAB() ( | |||||
BAOABFast() ( | |||||
BAOA() ( | |||||
VelocityVerlet() GJF ( | |||||
CSVR(kT=1, tau=0.5) (half-step) | |||||
NoseHooverChain(:gromacs) (full-step) |
(All P^_$SEMs are propagated in quadrature from the recorded virial and$T_{\text{kin}}$SEMs as$\sqrt{\sigma_{W/3V}^2 + (\rho^_\sigma_T)^2}$and combined with$\text{SE}(P^__{\text{ref}}) = 0.0144$for$z$; `run.jl` and `analyze.jl` now log and report direct block SEMs on$P^_ for fresh runs.)
Part 2: Software Parity Checks (BAOAB/BAOABFast) & High-Friction Stability Diagnostic

Panel (d) of Figure 2 separates software/API verification checks from a high-friction discrete-time integrator stability diagnostic:
Trajectory parity & zero-overhead fast path (software checks): Starting from the identical equilibrated liquid configuration and RNG seed at
,BAOAB()(track_thermo=true) andBAOABFast()(track_thermo=false) agree to and after 200 steps.BAOABFast()leavesst.dq,st.dU, andbath.heatidentically0.0, whileBAOAB()accumulates per-step heatso varies by over 2,000 steps (compared to canonical thermal energy fluctuations ). These are software/API regression checks (verify_check), kept distinct from physical validation tallies.High-friction discrete-time stability diagnostic (
, , ): The one-step velocity autocorrelationin the inset of Panel (d) is a discrete-time integrator stability diagnostic, not a physical fluid transport observable. For a free Brownian particle, BAOABhas damping factor whereasVelocityVerlet()(GJF) has Padé factor . In the interacting liquid ( ), conservative restoring forces pull the one-step velocity autocorrelation further negative: solving the discrete-time harmonic Lyapunov equation predicts forBAOABandfor GJF, closely explaining the measured liquid values and . GJF's sign reversal at is an integrator defect and is reported viareport_diagnostic(DIAG), not scored as a validation pass.
Table 2: Software Parity Checks (CHECK) & High-Friction Stability Diagnostic (DIAG)
| Item | Measured Value | Reference / Theory | Classification |
|---|---|---|---|
BAOAB vs. BAOABFast | CHECK_OK | ||
BAOAB vs. BAOABFast | CHECK_OK | ||
BAOAB raw | CHECK_OK | ||
BAOABFast raw | CHECK_OK | ||
BAOAB first-law residual | Drift | CHECK_OK | |
High-friction (BAOAB | Harmonic Lyapunov | DIAG | |
High-friction (VV (GJF) | Harmonic Lyapunov | DIAG |
Part 3: Canonical Kinetic Distribution & Effective-Energy Drift (CSVR & NHC)
Panels (a)–(c) of Figure 2 evaluate Bussi, Donadio & Parrinello (2007) on Float64 trajectories at kinetic_dof == 3N = 1536, verified as a software check):
Canonical
distribution: In Panel (a), all three thermostats match the analytical canonical mean within ( CSVR: ,; NHC(:gromacs): ,; NHC(:lammps): ,). For the variance ratio , CSVR( ,) and NHC(:lammps)( ,) agree within , whereas NHC(:gromacs)sits at ( ,). Rather than masking this behind a wide gate, analyze.jlnow evaluates explicit-scores and flags deviations; for deterministic Nosé–Hoover chains over 8 blocks of , slow chain-mode correlations can underestimate the 8-block SEM and yield mild finite-horizon variance scatter.Effective-energy drift
vs. fluctuation ratio: Panels (b) and (c) display (CSVR) and( :gromacsSY5 and:lammpsMTTK). Note that the dimensionless ratiois primarily driven by the canonical thermal energy fluctuations ( at ) rather than serving as an independent conservation quality metric. The physically meaningful conservation metric is the explicit linear drift per particle: forCSVR, forNHC(:gromacs), and forNHC(:lammps). For fresh runs,run.jlnow also records a matched-( ) microcanonical NVE baseline ( trace_nve.csv) soanalyze.jlcomparesdirectly against .
Table 3: Canonical Distribution & Conserved-Quantity Drift (Δt = 0.002, τ = 0.5, T_prod = 400 τ_LJ, d = 1536)
| Thermostat | ||||||
|---|---|---|---|---|---|---|
| Analytical Canonical / Ref. | — | |||||
CSVR(kT=1, tau=0.5) | ||||||
NoseHooverChain(:gromacs) | ||||||
NoseHooverChain(:lammps) |
Choosing a Thermostat in Practice
| Use case | Recommended choice | Why |
|---|---|---|
| Large-timestep configurational NVT sampling | BAOABFast() or half-step CSVR() | Eliminates leading BAOABFast() skips dU/dq overhead; half-step CSVR weakly perturbs dynamics and provides |
| Large-timestep biomolecular NPT sampling | BAOABFast() or CSVR() + StochasticCellRescaling or MonteCarloBarostat | Because full-step StochasticCellRescaling does), half-step velocities (BAOA), or an energy-based MC barostat |
| Stochastic thermodynamics, work/heat & entropy production | BAOAB() (track_thermo=true) | On-the-fly dU/dq tracking in BathExchangeObservable satisfying the discrete stochastic first law |
| High-friction / near-overdamped Langevin ( | BAOAB() / BAOABFast() | Exact positive OU damping VelocityVerlet() (GJF) |
| Deterministic extended-system NVT with minimal drift | NoseHooverChain(; propagator=:gromacs) or :lammps | Low |
Running This Tutorial
# Quick GPU smoke check (post-JIT compute ~30 s)
TUTORIAL_FAST=1 julia --project tutorials/T02_thermostat_accuracy/run.jl
TUTORIAL_FAST=1 julia --project tutorials/T02_thermostat_accuracy/analyze.jl
# Full production validation run & 300-DPI figure regeneration
julia --project tutorials/T02_thermostat_accuracy/run.jl
julia --project tutorials/T02_thermostat_accuracy/analyze.jl
python3 tutorials/T02_thermostat_accuracy/plot.pyReferences
B. Leimkuhler and C. Matthews, "Rational Construction of Stochastic Numerical Methods for Molecular Sampling," Appl. Math. Res. Express 2013(1), 34–56 (2013).
B. Leimkuhler and C. Matthews, "Robust and efficient configurational molecular sampling via Langevin dynamics," J. Chem. Phys. 138, 174102 (2013).
N. Grønbech-Jensen and O. Farago, "A simple and effective Verlet-type algorithm for simulating Langevin dynamics," Mol. Phys. 111, 983–991 (2013).
G. Bussi, D. Donadio, and M. Parrinello, "Canonical sampling through velocity rescaling," J. Chem. Phys. 126, 014101 (2007).
G. J. Martyna, M. L. Klein, and M. Tuckerman, "Nosé–Hoover chains: The canonical ensemble via continuous dynamics," J. Chem. Phys. 97, 2635–2643 (1992).