Tutorial T03: Nonequilibrium Work & Free Energy Reconstruction via the Jarzynski Equality
This tutorial implements a native-Julia, CUDA-graph-capturable AbstractExternalPotential in ParticleDynamics v1.2.0, combines it with BAOAB Langevin dynamics and on-the-fly work/heat tracking (ExternalPotentialForce, BathExchangeObservable), and runs GPU ensemble parallelization to test two results of nonequilibrium statistical mechanics:
Jarzynski (1997) (Phys. Rev. Lett. 78, 2690–2693): estimating an equilibrium Helmholtz free energy difference
within from irreversible finite-time pulling across an asymmetric double-well barrier, even when the mean workreverses sign and the 2nd-order cumulant approximation fails due to non-Gaussian barrier-crossing tails. Hummer & Szabo (2001) (Proc. Natl. Acad. Sci. USA 98, 3658–3661): reconstructing the equilibrium potential of mean force
across both wells and the barrier peak within from irreversible pulling trajectories.
Trajectory Visualization

Path-traced Fresnel studio snapshot (tutorials/render_snapshots.py --targets T03) illustrating the asymmetric double-well potential
1. Physical Model & Theoretical Background
We consider a strongly underdamped inertial Langevin particle of mass
With
Asymmetric double well
: Solving yields:shallow left well at
( , curvature , angular frequency ),barrier peak at
( ), giving a forward barrier and a reverse barrier ,deeper right well at
( , curvature , angular frequency ).
Strongly underdamped regime: Because
and while , the oscillator quality factors are and ( ). Inertia is significant in both wells (and even larger with the harmonic trap added).Soft-to-moderate optical trap (
): Near , the combined potentialretains a residual barrier. As the trap translates linearly from to over durationat constant velocity , barrier crossing produces mildly negatively skewed, non-Gaussian work distributions. Reference free energy: The equilibrium free energy difference between trap endpoints is computed to 15-digit numerical precision via 128-point Golub–Welsch Gauss–Legendre quadrature (cross-checked against 256 points to
):
Stochastic Thermodynamics, Discrete-Time Shadow Work & Finite-Sample Bias
Each trajectory starts in canonical equilibrium at BAOAB Langevin dynamics (B1–A1–O–A2–B2 splitting is:
With BAOAB(track_thermo=true), ParticleDynamics simultaneously accumulates the per-particle heat rate st.dq[i] absorbed from the thermal bath during each Ornstein–Uhlenbeck O-step, so BathExchangeObservable reports the heat dissipated into the bath, BAOAB introduces a nonzero
Consequently, Jarzynski's equality holds in discrete time only up to this integrator shadow-work error (here
While the 2nd Law dictates that the average dissipated work
Two important statistical properties govern practical estimation:
Non-Gaussian breakdown of the 2nd-order cumulant: Truncating at second order,
, is exact only for Gaussianand becomes biased once barrier crossing generates skewness .Positive finite-sample bias of
(Gore, Ritort & Bustamante 2003): Because is convex, Jensen's inequality implies that any finite-sample Jarzynski estimate is systematically biased upward, , whenever the rare low-work tail is undersampled (as measured by a falling Kish effective sample size , ). Bootstrap standard errors (SE_boot) measure sampling variance around the finite-sample mean but do not capture this systematic positive bias.analyze.jltherefore also reports the sub-ensemble scaling shift alongside to monitor finite-sample bias directly.
Hummer–Szabo (2001) Equilibrium PMF Reconstruction
Using snapshots
The normalization factor
2. ParticleDynamics v1.2.0 API Walkthrough
Single-Simulation GPU Ensemble Parallelization
Because the pulling trajectories are statistically independent, setting external_force_mode = :replace and needs_neighbor_list = false disables all inter-particle pair forces (NoPairs). A single ParticleDynamics GPU simulation of
Writing a Zero-Host-Callback, CUDA-Graph-Capturable Potential
To keep the entire pulling loop inside DeviceEngine CUDA graphs with zero host callbacks per step, we implement MovingTrapDoubleWell{T} <: AbstractExternalPotential and read the device-resident step counter run.neighbors.state[NL.DN_STEP] directly inside the GPU kernel:
using CUDA, ParticleDynamics
const NL = ParticleDynamics.NeighborLists
struct MovingTrapDoubleWell{T<:AbstractFloat} <: AbstractExternalPotential
Eb::T; a::T; c::T; k_trap::T
lambda0::T; lambda1::T
step_start::Int64; n_pull::Int64
work::CuVector{T} # on-the-fly Jarzynski work per trajectory
x_prev::CuVector{T} # previous x for trapezoidal increment
e_scratch::CuVector{T} # scratch buffer for external_energy hook
last_step::CuVector{Int64} # 1-element device guard against duplicate evals
enqueue_calls::Base.RefValue{Int}
end
# Declare native-Julia GPU-capturable :replace traits
ParticleDynamics.external_force_mode(::MovingTrapDoubleWell) = :replace
ParticleDynamics.is_device_capturable(::MovingTrapDoubleWell) = true
ParticleDynamics.needs_neighbor_list(::MovingTrapDoubleWell) = false
ParticleDynamics.provides_virial(::MovingTrapDoubleWell) = falseInside enqueue_external_forces!(p, run, energy, virial), two lightweight CUDA kernels are launched through NL._device_if_valid!:
_moving_trap_dw_kernel!readss = state[NL.DN_STEP], evaluates on-device, writesf[1][i](withf[2][i] = f[3][i] = 0) and optionalenergy[i], and accumulates the trapezoidal work increment intop.work[i]wheneverstep_start < s <= step_start + n_pullands > last_step[1]._advance_last_step_kernel!updatesp.last_step[1] = swith a single thread, guaranteeing race-free idempotency ifevaluate_configuration!is invoked outside stepping.
We also implement ParticleDynamics.external_energy(p, st) as a read-only GPU energy evaluation and check its consistency (\le 1.6 \times 10^{-16} relative error) against total_potential_energy(st) via verify_check.
Composing with the Workflow Simulation & BAOAB
Attaching the custom potential to a Simulation takes a single ExternalPotentialForce(pot) entry alongside BAOAB(track_thermo=true) and BathExchangeObservable:
all_particles = Group(:all, AllSelection())
sim = Simulation(
system;
groups=Groups(all_particles),
integrator=Integrator(
dt=0.005,
scheme=BAOAB(track_thermo=true),
forces=[ExternalPotentialForce(pot)],
methods=[Langevin(all_particles; gamma=0.8, kT=1.0)],
),
observables=[
ThermodynamicObservable(all_particles; name=:thermo),
BathExchangeObservable(; name=:bath),
],
precision=Float64,
seed=seed,
state=st_init, # O(M) cell-list state (spatial_reorder=false, nonbonded=:none)
)
prepare!(sim)Running n_equil = 2001 equilibration steps (1 + 100 × 20) warms and caches both the single-step and K = 20 batched CUDA graphs while step_many! pulling chunk has a stride divisible by 20, so the entire pulling protocol executes with 0 host enqueue_external_forces! callbacks (verified as a software check via verify_check).
3. Production Results & Quantitative Validation
Work Distributions, 2nd Law & Jarzynski Equality

Panel (a) shows the nonequilibrium work distributions
As pulling speed increases by
( ), the distribution shifts rightward (mean work rises from to , reversing sign even though the thermodynamic transition is downhill at ), broadens ( ), and develops mild negative skewness ( ).Physically, the negative-work tail (
) arises from early barrier crossers: trajectories that thermally cross from the left well into the lower-energy right well before the trap drives them strongly past the barrier, so (whereas trajectories that lag late in the left well experience a larger restoring force and populate the positive high-work tail).Rare trajectories with
carry the largest exponential weights and control the convergence of .
Panel (b) contrasts three estimators against the Gauss–Legendre reference
Mean work
(2nd Law): rises monotonically above , with dissipated work increasing from to .2nd-order cumulant
: stays close near equilibrium ( error at ), then diverges systematically as non-Gaussianity grows, reaching a bias of at .Jarzynski estimator
: remains statistically consistent with across all four speeds ( and ). At the fastest speed ( ), Kish effective sample size drops to ( of ) and sits ( ) above , consistent with both sampling variance and the onset of positive finite-sample exponential bias (Gore, Ritort & Bustamante 2003).
Table 1: Jarzynski Equality, 2nd Law, Cumulant Breakdown & Discrete Shadow Work (M = 65,536, ΔF_exact = −2.559248 k_B T)
| Protocol | Velocity | Skew | Kish | Shadow Work | Pull Time | ||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| Slow | 120.0 | 0.0250 | 22,296 | 5.37 s | |||||||
| Moderate | 60.0 | 0.0500 | 8,536 | 2.69 s | |||||||
| Fast | 30.0 | 0.1000 | 2,640 | 1.50 s | |||||||
| Very fast | 18.0 | 0.1667 | 641 | 0.97 s |
(Software/API checks separated via verify_check: all four runs confirmed used_cuda_graph = 1, enqueue_calls_delta = 0, external_energy relative parity BathExchangeObservable parity
Hummer–Szabo (2001) Equilibrium PMF Reconstruction

Panel (a) shows the Hummer–Szabo (2001) reconstruction of the equilibrium double-well PMF
Panel (b) compares the cumulative mean work
Table 2: Hummer–Szabo (2001) Equilibrium PMF Accuracy vs. Analytical U₀(x) (x ∈ [−1.35, 1.35])
| Protocol | Max Error | Barrier Region Error ( | RMSE ( | Target ( | |
|---|---|---|---|---|---|
| Slow ( | PASS | ||||
| Moderate ( | PASS | ||||
| Fast ( | PASS | ||||
| Very fast ( | PASS |
4. Running the Tutorial
# 1. Fast GPU smoke run (M = 512 trajectories x 4 speeds; ~2.2 s warm GPU execution)
TUTORIAL_FAST=1 julia --project tutorials/T03_jarzynski_free_energy/run.jl
TUTORIAL_FAST=1 julia --project tutorials/T03_jarzynski_free_energy/analyze.jl
# 2. Full production validation (M = 65,536 trajectories x 4 speeds = 262,144 trajectories)
julia --project tutorials/T03_jarzynski_free_energy/run.jl
julia --project tutorials/T03_jarzynski_free_energy/analyze.jl
# 3. Regenerate 300-DPI documentation figures
python3 tutorials/T03_jarzynski_free_energy/plot.pyFiles
tutorials/T03_jarzynski_free_energy/run.jl: GPU simulation with customMovingTrapDoubleWell <: AbstractExternalPotential.tutorials/T03_jarzynski_free_energy/analyze.jl: 128-point Gauss–Legendre quadrature, exact double-well extrema/frequencies, bootstrap & 8-block uncertainty analysis, finite-sample bias diagnostics, and Jarzynski/Hummer–Szabo validation checks.tutorials/T03_jarzynski_free_energy/plot.py: 300-DPI Matplotlib figure generator.
References
C. Jarzynski, Nonequilibrium Equality for Free Energy Differences, Phys. Rev. Lett. 78, 2690–2693 (1997).
G. Hummer and A. Szabo, Free energy reconstruction from nonequilibrium single-molecule pulling experiments, Proc. Natl. Acad. Sci. USA 98, 3658–3661 (2001).
G. Hummer and A. Szabo, Free energy surfaces from single-molecule force spectroscopy, Acc. Chem. Res. 38, 504–513 (2005).
J. Gore, F. Ritort, and C. Bustamante, Bias and error in estimates of equilibrium free-energy differences from nonequilibrium measurements, Proc. Natl. Acad. Sci. USA 100(22), 12564–12569 (2003).
D. A. Sivak, J. D. Chodera, and G. E. Crooks, Using nonequilibrium fluctuation theorems to understand and correct errors in equilibrium and nonequilibrium simulations of discrete Langevin dynamics, Phys. Rev. X 3, 011007 (2013).
B. Leimkuhler and C. Matthews, Rational construction of stochastic numerical methods for molecular sampling, Appl. Math. Res. Express 2013, 34–56 (2013).