Skip to content

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:

  1. 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 work reverses sign and the 2nd-order cumulant approximation fails due to non-Gaussian barrier-crossing tails.

  2. 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 ​

Studio Fresnel snapshot of GPU-parallel optical-trap pulling across the asymmetric double-well landscape

Path-traced Fresnel studio snapshot (tutorials/render_snapshots.py --targets T03) illustrating the asymmetric double-well potential and parallel ensembles of particles pulled across the   forward barrier by the translating harmonic optical trap .


1. Physical Model & Theoretical Background ​

We consider a strongly underdamped inertial Langevin particle of mass   moving in reduced units ( ,   , length scale  ) under an asymmetric quartic double-well background potential coupled to a linearly translating harmonic optical trap:

With  ,  ,  ,  , and Langevin friction   :

  • 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 potential retains a   residual barrier. As the trap translates linearly from    to    over duration at 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   and evolves under BAOAB Langevin dynamics ( ,  ,  ). Across discrete protocol step  , the time-centered trapezoidal work increment matching BAOAB's symmetric 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    (and the workflow BathExchangeObservable reports the heat dissipated into the bath,   ). In continuous time, the stochastic first law gives   . In discrete time ( ), however, any finite-timestep splitting such as BAOAB introduces a nonzero shadow-work residual (Sivak, Chodera & Crooks 2013):

Consequently, Jarzynski's equality holds in discrete time only up to this integrator shadow-work error (here    , well below the   statistical uncertainty of the   ensembles).

While the 2nd Law dictates that the average dissipated work     grows monotonically with pulling velocity , the Jarzynski equality relates the exponential work average to :

Two important statistical properties govern practical estimation:

  1. Non-Gaussian breakdown of the 2nd-order cumulant: Truncating at second order,   , is exact only for Gaussian and becomes biased once barrier crossing generates skewness  .

  2. 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.jl therefore also reports the sub-ensemble scaling shift   alongside to monitor finite-sample bias directly.

Hummer–Szabo (2001) Equilibrium PMF Reconstruction ​

Using snapshots recorded at   slices along the pulling coordinate  , the unbiased equilibrium potential of mean force    is reconstructed across all slices via the Hummer–Szabo weighted estimator:

The normalization factor   is obtained directly from the nonequilibrium trajectories without prior knowledge of .


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   particles therefore integrates independent nonequilibrium pulling trajectories in parallel on the GPU, completing trajectories across four pulling speeds in of RTX 3090 pulling time.

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:

julia
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) = false

Inside enqueue_external_forces!(p, run, energy, virial), two lightweight CUDA kernels are launched through NL._device_if_valid!:

  1. _moving_trap_dw_kernel! reads s = state[NL.DN_STEP], evaluates on-device, writes f[1][i] (with f[2][i] = f[3][i] = 0) and optional energy[i], and accumulates the trapezoidal work increment into p.work[i] whenever step_start < s <= step_start + n_pull and s > last_step[1].

  2. _advance_last_step_kernel! updates p.last_step[1] = s with a single thread, guaranteeing race-free idempotency if evaluate_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:

julia
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  . During Stage 2, every 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 ​

Nonequilibrium work distributions and Jarzynski free-energy estimators across pulling speeds

Panel (a) shows the nonequilibrium work distributions across   GPU trajectories per pulling velocity:

  • 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) ​

ProtocolVelocity () ()Skew ()  (, )Kish Shadow Work   Pull Time
Slow120.00.0250  ()  (, )22,296 5.37 s
Moderate60.00.0500  ()  (, )8,536 2.69 s
Fast30.00.1000  ()  (, )2,640 1.50 s
Very fast18.00.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   , and 128- vs 256-point quadrature agreement   . Bootstrap SEs use 1,000 resamples and closely match 8-block SEMs  , though neither captures systematic positive finite-sample exponential bias.)


Hummer–Szabo (2001) Equilibrium PMF Reconstruction ​

Hummer-Szabo PMF reconstruction and cumulative work dissipation along the pulling coordinate

Panel (a) shows the Hummer–Szabo (2001) reconstruction of the equilibrium double-well PMF over    (54 bins,  , 8 independent sub-ensemble blocks for SEM bands). Across all four speeds, the reconstructed PMF reproduces both asymmetric wells and the barrier peak (   ,   ) within the   validation band (residual strip below Panel (a)), with maximum error growing monotonically with from   (slow) to   (very fast) as rare-event sampling near the barrier becomes harder.

Panel (b) compares the cumulative mean work and time-dependent Jarzynski free energy against along the trap center    . The mean work tracks closely in the initial left well (  ), then diverges upward across the shaded barrier-crossing zone (   ) where nonequilibrium barrier escape generates dissipation, while recovers .

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 ​

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

Files ​

  • tutorials/T03_jarzynski_free_energy/run.jl: GPU simulation with custom MovingTrapDoubleWell <: 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 ​

  1. C. Jarzynski, Nonequilibrium Equality for Free Energy Differences, Phys. Rev. Lett. 78, 2690–2693 (1997).

  2. G. Hummer and A. Szabo, Free energy reconstruction from nonequilibrium single-molecule pulling experiments, Proc. Natl. Acad. Sci. USA 98, 3658–3661 (2001).

  3. G. Hummer and A. Szabo, Free energy surfaces from single-molecule force spectroscopy, Acc. Chem. Res. 38, 504–513 (2005).

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

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

  6. B. Leimkuhler and C. Matthews, Rational construction of stochastic numerical methods for molecular sampling, Appl. Math. Res. Express 2013, 34–56 (2013).

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