Algorithmcore
Thermodynamic integration
Computes a free energy difference by integrating the ensemble average of dU/dlambda over a coupling parameter lambda from 0 to 1.
- Time
- O(K N) worst
- Space
- O(N + K) extra
- Where
- K = the number of quadrature nodes; N = the number of samples per node
- Model
- Real RAM
- Properties
- randomizednot iterativerandomizednot unbiased
- Evidence
- Proof sketchCode in 1 languages
- Origin
- John G. Kirkwood, 1935
Thermodynamic integration (TI) computes the free energy difference of two states by joining them with a family of potentials , , and integrating the derivative of the free energy along the path. Kirkwood (1935) showed that this derivative is a canonical average, (a theorem). The method samples a few values of , takes the mean of at each, and applies a quadrature rule. It belongs with free energy perturbation, the Bennett acceptance ratio and the Jarzynski equality: FEP and BAR use the energy differences between neighbouring states, TI uses derivatives at the states, and Jarzynski uses the work along switching paths. TI has no exponential average, so it does not depend on rare samples, but it adds a quadrature error.
In plain words
To find the height difference between two towns, you can walk from one to the other and add up the small rises and falls on the way. Thermodynamic integration does this for free energy.
The path is a slow change of the system from the first state to the second, controlled by a dial. At a few settings of the dial, a simulation measures how fast the energy changes when the dial moves a little. The average of that rate is the slope of the free energy at that setting. A standard rule for the area under a curve then adds up the slopes over the whole path.
There are two errors: the noise of each simulation, and the error of the area rule when it uses too few settings or the curve bends sharply.
The problem
The input is a family of potentials , differentiable in , with and the two end states, a sampler of the canonical ensemble of each , the inverse temperature and a quadrature rule with nodes and weights . The output is an estimate of
and its statistical error. The common linear path is , with .
The algorithm
TI(nodes lambda_1..lambda_K, weights a_1..a_K, SAMPLE, DUDL, N)- 1
total ← 0; var ← 0 - 2
for j ← 1 to K do - 3
draw N samples x_i of the state lambda_j with SAMPLE - 4
g_j ← mean of DUDL(lambda_j, x_i); s_j ← its standard error - 5
total ← total + a_j g_j; var ← var + (a_j s_j)² - 6
return (total, sqrt(var))
The nodes are independent runs, so their errors add in quadrature on line L5. For a correlated chain, on line L4 must come from block averages or an estimate of the autocorrelation time. The returned error is statistical only; the quadrature error is separate and must be judged by refining the rule. The tests use the composite trapezoidal rule, the composite Simpson rule and Gauss-Legendre nodes on .
Example
Harmonic wells, quadrature only. Let at , from to . Then and , so the integrand is and . With the exact means at the nodes:
| rule | nodes | value | error |
|---|---|---|---|
| trapezoid, 2 intervals | 0, 0.5, 1 | 0.354167 | |
| trapezoid, 4 intervals | 5 | 0.348512 | |
| trapezoid, 8 intervals | 9 | 0.347061 | |
| Simpson, 2 intervals | 0, 0.5, 1 | 0.347222 | |
| Simpson, 4 intervals | 5 | 0.346627 | |
| Gauss-Legendre, 1 node | 0.5 | 0.333333 | |
| Gauss-Legendre, 2 nodes | 0.211325, 0.788675 | 0.346154 | |
| Gauss-Legendre, 3 nodes | 0.112702, 0.5, 0.887298 | 0.346561 |
By hand, the trapezoid with two intervals is . Halving the interval divides the trapezoid error by 4 and the Simpson error by about 12 here (16 in the limit), as their orders 2 and 4 predict.
Harmonic wells, sampled. Three Gauss-Legendre nodes with exact normal draws per node (seed 1):
| estimate | error bar | error | |
|---|---|---|---|
| 100 | 0.32963 | 0.0272 | |
| 1000 | 0.34545 | 0.0089 | |
| 10000 | 0.34552 | 0.0029 |
The quadrature error, , is far below the statistical error, so here more samples help and more nodes would not.
A quartic well with Metropolis sampling. Let at . A direct quadrature of the two partition functions gives . A random-walk Metropolis chain of 20000 steps per node, with error bars from 20 batch means (seed 2):
| rule | estimate | error bar | quadrature error alone |
|---|---|---|---|
| Gauss-Legendre, 3 nodes | 0.0042 | ||
| Gauss-Legendre, 5 nodes | 0.0030 | ||
| trapezoid, 4 intervals | 0.01287 |
The last column uses the exact means at the nodes. The integrand is 0.25 at , 0.0822 at 0.1, at 0.5 and at 1: it falls steeply near , where the quartic term first cuts off the tails of the Gaussian. The trapezoid with five nodes misses this bend by 0.013, about four times the statistical error.
Correctness
The proof in proofs/correctness.md shows:
- Kirkwood's identity. , so is the integral of the average over .
- Curvature. . On the linear path the first term is 0, so is concave and the integrand never increases along the path.
- The estimator. With independent runs at the nodes, the output is an unbiased estimate of the quadrature sum , its variance is , and it converges to that sum as .
- Total error. The error is the quadrature error of the rule on plus a statistical error of order . The rule of order gives a quadrature error for a smooth .
- The harmonic example: the exact integrand and .
Proof: Kirkwood's identity, the concavity of A along a linear path, and the error of the estimatorfull
Let , , be a family of potentials with finite and positive, and . Write and . Assume that is twice differentiable in and that , , and are bounded, uniformly for in a neighbourhood of each point, by integrable functions of . Then derivatives in may be taken under the integral sign (dominated convergence).
Claim 1 (Kirkwood's identity). , and therefore
Proof. . So . The derivative is continuous in under the same domination, so the fundamental theorem of calculus gives the integral.
Claim 2 (curvature).
On the linear path the first term is 0, so is concave in and is non-increasing.
Proof. Differentiate :
where the last term comes from by Claim 1. The last two terms are . On the linear path and the variance is at least 0.
Claim 3 (the estimator). Let the run at node give , the mean of over samples, with (exact draws, or a stationary chain started in equilibrium) and the runs independent. Then the output has and . With independent draws and at the nodes, with probability 1 and .
Proof. Linearity of expectation, independence of the runs for the variance of the sum, the law of large numbers at each node, and for independent draws.
Lines L4 and L5 estimate by and add , which is the plug-in form of this variance. With batch means, estimates the variance of a correlated mean instead.
Claim 4 (total error).
where is the quadrature error of the rule on , a fixed number, and has mean 0 and standard deviation . If is on , the composite trapezoidal rule with intervals has ; if is , the composite Simpson rule has ; the -point Gauss-Legendre rule is exact when is a polynomial of degree at most .
Proof. The split is an identity, by Claim 1, and Claim 3 gives the mean and variance of . The quadrature bounds are the standard error bounds of these rules on an interval of length 1, proved on the pages of the trapezoidal rule, the Simpson rule and Gaussian quadrature.
Claim 5 (the harmonic example). For in one dimension, and .
Proof. and is normal with variance in state , so . Its integral over is , which equals with , , the ratio of the Gaussian partition functions .
The integrand here is decreasing, as Claim 2 requires, since with and . It is also convex, so the trapezoidal rule overestimates the integral, as the example on the page shows.
Complexity
nodes with samples each cost evaluations of plus steps of the sampler, which dominate. The extra space is for the samples of one node, or with running sums, and for the means. For a target error , the statistical part needs samples in total, and the quadrature part needs nodes for a smooth integrand (a theorem for a fixed smooth integrand; the constants depend on the path).
Properties
- No exponential average. Each node needs only a plain mean, so the result does not depend on rare samples, unlike FEP.
- Biased by the quadrature, not by the sampling. For a fixed rule, the estimator is unbiased for the quadrature sum; the quadrature error is a deterministic bias.
- Needs derivatives. The code must supply ; on the linear path it is .
- Path-independent result, path-dependent cost. does not depend on the path, but the smoothness of the integrand and the variance at each node do.
- Monotone integrand on the linear path (Claim 2), which helps to spot errors: a mean that rises along the path is noise or a sampling failure.
Variants and improvements
- Nonlinear paths. Paths such as , or soft-core potentials for atoms that appear or vanish, remove singularities of the integrand at the ends. The choice of path is a choice.
- Quadrature. Gauss-Legendre nodes avoid the end points, where the integrand may be singular; adaptive placement puts more nodes where the integrand bends.
- Slow growth. One run that changes slowly during the simulation integrates on the fly. It has a hysteresis error unless the change is very slow; the Jarzynski equality turns finite-speed runs into an exact estimate.
- Other parameters. The same identity with temperature or volume as the parameter gives the Gibbs-Helmholtz route and integration of the pressure; integration from an Einstein crystal (Frenkel and Ladd 1984) gives absolute free energies of solids.
- Combining with BAR. The same runs give both the derivatives and the energy differences between neighbouring nodes, so TI and BAR can be compared on the same data.
When to use it
Use TI when is cheap and smooth along the path, for example for alchemical changes with soft-core potentials, for changes of temperature or density, and for absolute free energies from a reference system. It is robust when the end states overlap poorly, since each node needs only local sampling. Prefer BAR or MBAR on the same windows when the integrand has sharp features that need too many nodes, or when derivatives are not available.
Pitfalls
- Too few nodes where the integrand bends, as in the quartic example with the trapezoid.
- Singular end points. When atoms vanish with a linear path, can diverge at or 1; use soft-core paths or Gauss nodes.
- Correlated samples. The plain standard error is too small for a Markov chain; use batch means.
- Hidden slow modes. If a slow motion of the system does not relax at a node, the mean at that node is wrong with a small error bar. Run forward and backward along and compare.
- Ignoring the quadrature error. The error bar returned by the method is statistical only.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/thermodynamic-integration/. The authors are listed in prov/G0H3ZS.jsonl.
"""Thermodynamic integration (Kirkwood 1935).
A family of potentials U_lambda, lambda in [0, 1], joins state 0 to state 1.
The derivative of the free energy along the path is a canonical average,
dA / dlambda = < dU_lambda / dlambda >_lambda,
so A_1 - A_0 is the integral of this average over [0, 1]. The method samples a
few values of lambda, takes the mean of dU/dlambda at each one, and applies a
quadrature rule. The result has two errors: the statistical error of the
means and the quadrature error of the rule.
The sampler is an input. A Metropolis sampler and the batch-means error for
its correlated samples are included for the tests.
Cost: (number of nodes) times (samples per node) evaluations of dU/dlambda,
plus the cost of the sampler.
"""
import math
from typing import Callable, Sequence
def trapezoid_rule(k: int) -> tuple[list[float], list[float]]:
"""Nodes and weights of the composite trapezoid rule with k intervals on [0, 1]."""
if k < 1:
raise ValueError("need k >= 1")
nodes = [i / k for i in range(k + 1)]
weights = [1.0 / k] * (k + 1)
weights[0] = weights[-1] = 0.5 / k
return nodes, weights
def simpson_rule(k: int) -> tuple[list[float], list[float]]:
"""Nodes and weights of the composite Simpson rule with k (even) intervals on [0, 1]."""
if k < 2 or k % 2:
raise ValueError("need an even k >= 2")
nodes = [i / k for i in range(k + 1)]
weights = [(4 if i % 2 else 2) / (3 * k) for i in range(k + 1)]
weights[0] = weights[-1] = 1 / (3 * k)
return nodes, weights
def _legendre(n: int, x: float) -> tuple[float, float]:
"""P_n(x) and its derivative, by the three-term recurrence."""
p_prev, p = 1.0, x
for j in range(2, n + 1):
p_prev, p = p, ((2 * j - 1) * x * p - (j - 1) * p_prev) / j
return p, n * (x * p - p_prev) / (x * x - 1)
def gauss_legendre_rule(n: int) -> tuple[list[float], list[float]]:
"""Nodes and weights of the n-point Gauss-Legendre rule, mapped to [0, 1]."""
if n < 1:
raise ValueError("need n >= 1")
pts = []
for i in range(1, n + 1):
x = math.cos(math.pi * (i - 0.25) / (n + 0.5))
for _ in range(100):
p, dp = _legendre(n, x)
dx = p / dp
x -= dx
if abs(dx) < 1e-15:
break
_, dp = _legendre(n, x)
# weight 2 / ((1 - x^2) P_n'(x)^2) on [-1, 1], halved for [0, 1]
pts.append((0.5 * (1 - x), 1.0 / ((1 - x * x) * dp * dp)))
pts.sort()
return [p[0] for p in pts], [p[1] for p in pts]
def mean_and_error(values: Sequence[float], batches: int = 1) -> tuple[float, float]:
"""Mean and standard error. With batches > 1, the error uses batch means
(for correlated samples); with batches = 1, it assumes independent samples."""
n = len(values)
mean = sum(values) / n
if batches <= 1:
var = sum((v - mean) ** 2 for v in values) / (n - 1)
return mean, math.sqrt(var / n)
b = n // batches
means = [sum(values[i * b:(i + 1) * b]) / b for i in range(batches)]
m = sum(means) / batches
var = sum((x - m) ** 2 for x in means) / (batches - 1)
return mean, math.sqrt(var / batches)
def thermodynamic_integration(nodes: Sequence[float], weights: Sequence[float],
sample: Callable, dudl: Callable, n: int, rng,
batches: int = 1) -> tuple[float, float, list[float]]:
"""A_1 - A_0 by quadrature of the mean of dU/dlambda.
sample(lam, n, rng) returns n configurations of the state lam (independent
or a correlated chain), dudl(lam, x) is dU_lam / dlam at x. Returns the
estimate, its statistical standard error and the means at the nodes.
"""
total, var, means = 0.0, 0.0, [] # @line L1
for lam, w in zip(nodes, weights): # @line L2
xs = sample(lam, n, rng) # @line L3
g, s = mean_and_error([dudl(lam, x) for x in xs], batches) # @line L4
total += w * g # @line L5
var += (w * s) ** 2 # @line L5
means.append(g)
return total, math.sqrt(var), means # @line L6
def metropolis(u: Callable, beta: float, x0: float, step: float, n: int,
rng, burn: int = 1000) -> list[float]:
"""A random walk Metropolis chain in one dimension for the density exp(-beta u)."""
x, ux = x0, u(x0)
out = []
for i in range(burn + n):
y = x + step * (2 * rng.random() - 1)
uy = u(y)
if uy <= ux or rng.random() < math.exp(-beta * (uy - ux)):
x, ux = y, uy
if i >= burn:
out.append(x)
return out
test_thermodynamic_integration.py 111 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/thermodynamic-integration/. The authors are listed in prov/G0H3ZS.jsonl.
import math
import random
import pytest
from thermodynamic_integration import (
gauss_legendre_rule,
mean_and_error,
metropolis,
simpson_rule,
thermodynamic_integration,
trapezoid_rule,
)
EXACT = 0.5 * math.log(2.0) # k from 1 to 2 at kT = 1
def exact_mean(lam):
# U_lam = (1 + lam) x^2 / 2, so dU/dlam = x^2 / 2 and <x^2> = 1 / (1 + lam).
return 0.5 / (1.0 + lam)
def quad(rule, f):
return sum(w * f(x) for x, w in zip(*rule))
def test_rules_are_exact_on_polynomials():
for deg in range(2):
assert quad(trapezoid_rule(3), lambda x: x ** deg) == pytest.approx(1 / (deg + 1), abs=1e-14)
for deg in range(4):
assert quad(simpson_rule(2), lambda x: x ** deg) == pytest.approx(1 / (deg + 1), abs=1e-14)
for n in range(1, 7):
for deg in range(2 * n):
assert quad(gauss_legendre_rule(n), lambda x: x ** deg) == pytest.approx(1 / (deg + 1), abs=1e-13)
# degree 2n is not integrated exactly
assert abs(quad(gauss_legendre_rule(n), lambda x: x ** (2 * n)) - 1 / (2 * n + 1)) > 1e-9
def test_gauss_legendre_two_points():
nodes, weights = gauss_legendre_rule(2)
assert nodes == pytest.approx([0.5 - 0.5 / math.sqrt(3), 0.5 + 0.5 / math.sqrt(3)], abs=1e-14)
assert weights == pytest.approx([0.5, 0.5], abs=1e-14)
def test_hand_values_of_quadrature_on_exact_means():
assert quad(trapezoid_rule(2), exact_mean) == pytest.approx(0.354167, abs=1e-6)
assert quad(simpson_rule(2), exact_mean) == pytest.approx(0.347222, abs=1e-6)
assert quad(gauss_legendre_rule(2), exact_mean) == pytest.approx(0.346154, abs=1e-6)
def test_observed_order_of_trapezoid_and_simpson():
e = [abs(quad(trapezoid_rule(k), exact_mean) - EXACT) for k in (2, 4, 8, 16)]
for a, b in zip(e, e[1:]):
assert math.log2(a / b) == pytest.approx(2.0, abs=0.2)
e = [abs(quad(simpson_rule(k), exact_mean) - EXACT) for k in (2, 4, 8, 16)]
for a, b in zip(e[1:], e[2:]):
assert math.log2(a / b) == pytest.approx(4.0, abs=0.2)
def gauss_sample(lam, n, rng):
return [rng.gauss(0.0, 1.0 / math.sqrt(1.0 + lam)) for _ in range(n)]
def test_sampled_harmonic_ti_matches_exact():
rule = gauss_legendre_rule(3)
est, se, means = thermodynamic_integration(*rule, gauss_sample, lambda lam, x: 0.5 * x * x,
10000, random.Random(1))
quad_err = abs(quad(rule, exact_mean) - EXACT)
assert quad_err < 2e-5
assert abs(est - EXACT) < 4 * se + quad_err
for lam, g in zip(rule[0], means):
assert g == pytest.approx(exact_mean(lam), abs=0.03)
def quartic(lam, x):
return (1 - lam) * 0.5 * x * x + lam * 0.25 * x ** 4
def reference_quartic():
h = 0.001
z = [h * sum(math.exp(-quartic(lam, -8 + i * h)) for i in range(16001)) for lam in (0.0, 1.0)]
return -math.log(z[1] / z[0])
def test_metropolis_quartic_against_partition_function_quadrature():
ref = reference_quartic()
assert ref == pytest.approx(-0.022510, abs=1e-6)
def sample(lam, n, rng):
return metropolis(lambda x: quartic(lam, x), 1.0, 0.0, 2.0, n, rng)
est, se, _ = thermodynamic_integration(*gauss_legendre_rule(5), sample,
lambda lam, x: 0.25 * x ** 4 - 0.5 * x * x,
20000, random.Random(2), batches=20)
# 5-point Gauss-Legendre leaves a quadrature error of about 2.3e-4 here.
assert abs(est - ref) < 4 * se + 5e-4
def test_metropolis_samples_the_gaussian():
xs = metropolis(lambda x: 0.5 * x * x, 1.0, 0.0, 2.5, 40000, random.Random(3))
m, se = mean_and_error([x * x for x in xs], batches=20)
assert abs(m - 1.0) < 4 * se
def test_bad_rule_arguments():
with pytest.raises(ValueError):
simpson_rule(3)
with pytest.raises(ValueError):
trapezoid_rule(0)
History
Kirkwood (1935) introduced the coupling parameter in his theory of fluid mixtures: it switches on the interaction of one molecule with the rest, and the free energy change is an integral of the mean coupling energy. The identity became a simulation method when Monte Carlo and molecular dynamics could compute the averages. Thermodynamic integration over temperature and density had long been used in thermodynamics, and Frenkel and Ladd (1984) used integration from an Einstein crystal for the free energy of solids.
References
- John G. Kirkwood, Statistical mechanics of fluid mixtures, Journal of Chemical Physics 3(5), 1935, 300-313, the coupling parameter and the free energy as an integral over it of an average of the coupling energy
- Daan Frenkel and Berend Smit, Understanding Molecular Simulation, From Algorithms to Applications, second edition, Academic Press, 2002, the chapter on free energies, the section on thermodynamic integration
- Tony Lelièvre, Mathias Rousset and Gabriel Stoltz, Free Energy Computations, A Mathematical Perspective, Imperial College Press, 2010, the treatment of thermodynamic integration for alchemical transitions
- Christophe Chipot and Andrew Pohorille (eds.), Free Energy Calculations, Theory and Applications in Chemistry and Biology, Springer Series in Chemical Physics 86, Springer, 2007, the chapter on thermodynamic integration
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag G0H3ZS Edit this page History Report an error Markdown