Skip to content

Tutorial T02: Canonical Thermostat Accuracy ​

Finite-timestep discretization errors in canonical () thermostats can bias configurational averages, virial pressures, and kinetic energy fluctuations well before an integrator loses numerical stability. This tutorial audits the canonical integrators and thermostats in ParticleDynamics v1.2.0 at Float64 precision on a dense 3D anharmonic Lennard-Jones liquid against two standard statistical-mechanics benchmarks:

  1. 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-step CSVR, and full-step NoseHooverChain, alongside software parity checks (BAOAB vs. BAOABFast), on-the-fly dU/dq first-law tracking, and a high-friction discrete-time stability diagnostic.

  2. 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 :gromacs 4th-order SY5 and :lammps MTTK propagators) via BathExchangeObservable.

Trajectory Visualization ​

Studio Fresnel snapshot of the canonical Lennard-Jones liquid colored by atomic kinetic energy

_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   particles in reduced Lennard-Jones units ( ,  ,  ,  ) at Float64 precision:

  • State point: reduced number density   (cubic periodic box    ), target temperature   ( ), kinetic degrees of freedom   .

  • Smooth pair potential: LennardJones with vdw_modifier = :force_switch, switch_distance = 2.0, and cutoff = 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    for CSVR (interval = 1) and NoseHooverChain (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:

julia
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:

julia
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 and tracks Bussi's effective energy    across every writer flush.


Results & Quantitative Verification ​

Part 1: Configurational Accuracy vs. Kinetic Temperature Bias ​

Timestep Accuracy Audit on the Dense 3D Lennard-Jones Liquid

In a dense anharmonic liquid, the Velocity Verlet discrete shadow Hamiltonian couples full-step kinetic temperature and configurational sampling through the fluid's Einstein frequency :

where   is determined independently from the canonical mean-square force (Hessian trace identity). (Note: in the recorded dataset plotted above,    was estimated by fitting BAOAB's own curve rather than independently from , which is circular as a validation of the shadow curve; run.jl and analyze.jl have since been updated to log forces during the   reference run and test non-circularly against the force-derived on fresh runs.)

Across the   timestep sweep (   ,   production per run, 8-block SEMs):

  • BAOAB and BAOABFast (Leimkuhler–Matthews splitting ): At  , BAOAB's configurational potential-energy difference from the   reference is      (, statistically consistent with zero), and BAOABFast gives    (). Note that at   and   precision, these runs test the absence of leading harmonic configurational bias rather than high-friction fourth-order superconvergence (which requires large and much tighter statistical error bars to resolve).

  • BAOA (): Because  , BAOA is the half-kick leapfrog conjugate of BAOAB (  ). It samples the same unbiased configurational ensemble (    , at  ) while recording velocities immediately after the Ornstein–Uhlenbeck O step, keeping kinetic temperature consistent with (  , ).

  • VelocityVerlet with Langevin (Grønbech-Jensen/Farago GJF): At  , GJF also keeps configurational bias statistically consistent with zero (    , at  ) with the same full-step shadow depression.

  • Half-step CSVR vs. full-step NoseHooverChain: ParticleDynamics v1.2.0 applies CSVR to the half-step leapfrog velocity   (matching GROMACS v-rescale), eliminating harmonic configurational bias (    , at  ). Conversely, NoseHooverChain thermostats the full-step kinetic energy to  , inducing configurational overheating     (   ). Using the canonical configurational heat capacity extracted from CSVR energy fluctuations (   at           ), linear response predicts

    agreeing within with the measured NHC overheating bias of    ( above zero;    or in configurational virial).

  • Mechanical pressure bias from full-step : Although BAOAB, BAOABFast, VV_GJF, and CSVR preserve the configurational virial at  , 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 StochasticCellRescaling does in ParticleDynamics), 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() ( , half-step )   ()    (, )
VelocityVerlet() GJF ( )   ()    (, )
CSVR(kT=1, tau=0.5) (half-step)   ()    (, )
NoseHooverChain(:gromacs) (full-step)   ()    (, )

(All and uncertainties are combined 8-block SEMs . In the recorded table, per-run 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 ​

Canonical Distribution & Conserved Effective Energy Audit

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) and BAOABFast() (track_thermo=false) agree to     and    after 200 steps. BAOABFast() leaves st.dq, st.dU, and bath.heat identically 0.0, while BAOAB() accumulates per-step heat so   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 autocorrelation in the inset of Panel (d) is a discrete-time integrator stability diagnostic, not a physical fluid transport observable. For a free Brownian particle, BAOAB has damping factor     whereas VelocityVerlet() (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    for BAOAB and for GJF, closely explaining the measured liquid values and . GJF's sign reversal at   is an integrator defect and is reported via report_diagnostic (DIAG), not scored as a validation pass.

Table 2: Software Parity Checks (CHECK) & High-Friction Stability Diagnostic (DIAG) ​

ItemMeasured ValueReference / TheoryClassification
BAOAB vs. BAOABFast (200 steps,  )   CHECK_OK
BAOAB vs. BAOABFast (200 steps,  ) CHECK_OK
BAOAB raw , (50 steps) ,   (tracking active)CHECK_OK
BAOABFast raw , , , , (tracking skipped)CHECK_OK
BAOAB first-law residual   (2,000 steps)  (vs   )Drift  CHECK_OK
High-friction ( ) BAOAB Harmonic Lyapunov (free )DIAG
High-friction ( ) VV (GJF) Harmonic Lyapunov (Padé sign-flip defect)DIAG

Part 3: Canonical Kinetic Distribution & Effective-Energy Drift (CSVR & NHC) ​

Panels (a)–(c) of Figure 2 evaluate Bussi, Donadio & Parrinello (2007) on -step (   ) Float64 trajectories at   and   (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.jl now 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 (:gromacs SY5 and :lammps MTTK). Note that the dimensionless ratio is 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 :    for CSVR,    for NHC(:gromacs), and    for NHC(:lammps). For fresh runs, run.jl now also records a matched- () microcanonical NVE baseline (trace_nve.csv) so analyze.jl compares directly against .

Table 3: Canonical Distribution & Conserved-Quantity Drift (Δt = 0.002, τ = 0.5, T_prod = 400 τ_LJ, d = 1536) ​

Thermostat () () () (, diag.) ()
Analytical Canonical / Ref.  —
CSVR(kT=1, tau=0.5)  ()  ()   
NoseHooverChain(:gromacs)  ()  ()   
NoseHooverChain(:lammps)  ()  ()   

Choosing a Thermostat in Practice ​

Use caseRecommended choiceWhy
Large-timestep configurational NVT samplingBAOABFast() or half-step CSVR()Eliminates leading harmonic configurational bias at large ; BAOABFast() skips dU/dq overhead; half-step CSVR weakly perturbs dynamics and provides drift auditing
Large-timestep biomolecular NPT samplingBAOABFast() or CSVR() + StochasticCellRescaling or MonteCarloBarostatBecause full-step is depressed by , avoid feeding full-step into a virial barostat; use the target ideal-gas term (as StochasticCellRescaling does), half-step velocities (BAOA), or an energy-based MC barostat
Stochastic thermodynamics, work/heat & entropy productionBAOAB() (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 avoids the Padé sign-flip defect of VelocityVerlet() (GJF)
Deterministic extended-system NVT with minimal driftNoseHooverChain(; propagator=:gromacs) or :lammpsLow linear drift ( ); pair with conservative timesteps ( ) to prevent full-step configurational overheating

Running This Tutorial ​

bash
# 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.py

References ​

  1. B. Leimkuhler and C. Matthews, "Rational Construction of Stochastic Numerical Methods for Molecular Sampling," Appl. Math. Res. Express 2013(1), 34–56 (2013).

  2. B. Leimkuhler and C. Matthews, "Robust and efficient configurational molecular sampling via Langevin dynamics," J. Chem. Phys. 138, 174102 (2013).

  3. N. Grønbech-Jensen and O. Farago, "A simple and effective Verlet-type algorithm for simulating Langevin dynamics," Mol. Phys. 111, 983–991 (2013).

  4. G. Bussi, D. Donadio, and M. Parrinello, "Canonical sampling through velocity rescaling," J. Chem. Phys. 126, 014101 (2007).

  5. 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).

ParticleDynamics v1.2.0 · GPU-native molecular dynamics in pure Julia · MIT License