Algorithm Search⌘K

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
Properties
randomizednot iterativerandomizednot unbiased
Origin
John G. Kirkwood, 1935

Thermodynamic integration (TI) computes the free energy difference ΔA=A1−A0\Delta A = A_1 - A_0 of two states by joining them with a family of potentials UλU_\lambda, λ∈[0,1]\lambda \in [0, 1], and integrating the derivative of the free energy along the path. Kirkwood (1935) showed that this derivative is a canonical average, dA/dλ=⟨∂Uλ/∂λ⟩λdA/d\lambda = \langle \partial U_\lambda / \partial \lambda \rangle_\lambda (a theorem). The method samples a few values of λ\lambda, takes the mean of ∂U/∂λ\partial U / \partial \lambda 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 Uλ(x)U_\lambda(x), differentiable in λ\lambda, with U0U_0 and U1U_1 the two end states, a sampler of the canonical ensemble of each UλU_\lambda, the inverse temperature β=1/(kBT)\beta = 1/(k_B T) and a quadrature rule with nodes λj∈[0,1]\lambda_j \in [0, 1] and weights aja_j. The output is an estimate of

ΔA=A1−A0=∫01⟨∂Uλ∂λ⟩λdλ,Aλ=−kBTln⁡∫e−βUλ(x) dx,\Delta A = A_1 - A_0 = \int_0^1 \Bigl\langle \frac{\partial U_\lambda}{\partial \lambda} \Bigr\rangle_\lambda d\lambda, \qquad A_\lambda = -k_B T \ln \int e^{-\beta U_\lambda(x)}\,dx,

and its statistical error. The common linear path is Uλ=(1−λ)U0+λU1U_\lambda = (1 - \lambda) U_0 + \lambda U_1, with ∂U/∂λ=U1−U0\partial U / \partial \lambda = U_1 - U_0.

The algorithm

  1. TI(nodes lambda_1..lambda_K, weights a_1..a_K, SAMPLE, DUDL, N)
  2. 1total ← 0; var ← 0
  3. 2for j ← 1 to K do
  4. 3draw N samples x_i of the state lambda_j with SAMPLE
  5. 4g_j ← mean of DUDL(lambda_j, x_i); s_j ← its standard error
  6. 5total ← total + a_j g_j; var ← var + (a_j s_j)²
  7. 6return (total, sqrt(var))

The nodes are independent runs, so their errors add in quadrature on line L5. For a correlated chain, sjs_j 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 [0,1][0, 1].

Example

Harmonic wells, quadrature only. Let Uλ=(1+λ)x2/2U_\lambda = (1 + \lambda) x^2 / 2 at kBT=1k_B T = 1, from k0=1k_0 = 1 to k1=2k_1 = 2. Then ∂U/∂λ=x2/2\partial U / \partial \lambda = x^2 / 2 and ⟨x2⟩λ=1/(1+λ)\langle x^2 \rangle_\lambda = 1 / (1 + \lambda), so the integrand is g(λ)=0.5/(1+λ)g(\lambda) = 0.5 / (1 + \lambda) and ΔA=12ln⁡2=0.346574\Delta A = \frac12 \ln 2 = 0.346574. With the exact means at the nodes:

rule nodes value error
trapezoid, 2 intervals 0, 0.5, 1 0.354167 7.59×10−37.59 \times 10^{-3}
trapezoid, 4 intervals 5 0.348512 1.94×10−31.94 \times 10^{-3}
trapezoid, 8 intervals 9 0.347061 4.87×10−44.87 \times 10^{-4}
Simpson, 2 intervals 0, 0.5, 1 0.347222 6.49×10−46.49 \times 10^{-4}
Simpson, 4 intervals 5 0.346627 5.34×10−55.34 \times 10^{-5}
Gauss-Legendre, 1 node 0.5 0.333333 −1.32×10−2-1.32 \times 10^{-2}
Gauss-Legendre, 2 nodes 0.211325, 0.788675 0.346154 −4.20×10−4-4.20 \times 10^{-4}
Gauss-Legendre, 3 nodes 0.112702, 0.5, 0.887298 0.346561 −1.27×10−5-1.27 \times 10^{-5}

By hand, the trapezoid with two intervals is 14g(0)+12g(0.5)+14g(1)=0.125+0.166667+0.0625=0.354167\frac14 g(0) + \frac12 g(0.5) + \frac14 g(1) = 0.125 + 0.166667 + 0.0625 = 0.354167. 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 NN exact normal draws per node (seed 1):

NN estimate error bar error
100 0.32963 0.0272 −0.0169-0.0169
1000 0.34545 0.0089 −0.0011-0.0011
10000 0.34552 0.0029 −0.0011-0.0011

The quadrature error, 1.3×10−51.3 \times 10^{-5}, is far below the statistical error, so here more samples help and more nodes would not.

A quartic well with Metropolis sampling. Let Uλ=(1−λ)x2/2+λx4/4U_\lambda = (1 - \lambda) x^2 / 2 + \lambda x^4 / 4 at kBT=1k_B T = 1. A direct quadrature of the two partition functions gives ΔA=−0.022510\Delta A = -0.022510. 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.026796-0.026796 0.0042 −0.00212-0.00212
Gauss-Legendre, 5 nodes −0.026466-0.026466 0.0030 −0.00023-0.00023
trapezoid, 4 intervals −0.011124-0.011124 0.01287

The last column uses the exact means at the nodes. The integrand ⟨x4/4−x2/2⟩λ\langle x^4/4 - x^2/2 \rangle_\lambda is 0.25 at λ=0\lambda = 0, 0.0822 at 0.1, −0.0489-0.0489 at 0.5 and −0.088-0.088 at 1: it falls steeply near λ=0\lambda = 0, 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:

  1. Kirkwood's identity. dAλ/dλ=⟨∂Uλ/∂λ⟩λdA_\lambda / d\lambda = \langle \partial U_\lambda / \partial \lambda \rangle_\lambda, so ΔA\Delta A is the integral of the average over [0,1][0, 1].
  2. Curvature. d2A/dλ2=⟨∂2U/∂λ2⟩λ−β varλ(∂U/∂λ)d^2 A / d\lambda^2 = \langle \partial^2 U / \partial \lambda^2 \rangle_\lambda - \beta\, \mathrm{var}_\lambda(\partial U / \partial \lambda). On the linear path the first term is 0, so A(λ)A(\lambda) is concave and the integrand never increases along the path.
  3. The estimator. With independent runs at the nodes, the output is an unbiased estimate of the quadrature sum ∑jajg(λj)\sum_j a_j g(\lambda_j), its variance is ∑jaj2var(gˉj)\sum_j a_j^2 \mathrm{var}(\bar g_j), and it converges to that sum as N→∞N \to \infty.
  4. Total error. The error is the quadrature error of the rule on gg plus a statistical error of order N−1/2N^{-1/2}. The rule of order pp gives a quadrature error O(K−p)O(K^{-p}) for a smooth gg.
  5. The harmonic example: the exact integrand 0.5/(1+λ)0.5/(1+\lambda) and ΔA=12ln⁡2\Delta A = \frac12 \ln 2.
Proof: Kirkwood's identity, the concavity of A along a linear path, and the error of the estimatorfull

Let Uλ(x)U_\lambda(x), λ∈[0,1]\lambda \in [0, 1], be a family of potentials with Zλ=∫e−βUλ(x) dxZ_\lambda = \int e^{-\beta U_\lambda(x)}\,dx finite and positive, and Aλ=−β−1ln⁡ZλA_\lambda = -\beta^{-1} \ln Z_\lambda. Write ⟨f⟩λ=Zλ−1∫f e−βUλ dx\langle f \rangle_\lambda = Z_\lambda^{-1} \int f\, e^{-\beta U_\lambda}\,dx and U′=∂Uλ/∂λU' = \partial U_\lambda / \partial \lambda. Assume that Uλ(x)U_\lambda(x) is twice differentiable in λ\lambda and that e−βUλe^{-\beta U_\lambda}, ∣U′∣e−βUλ|U'| e^{-\beta U_\lambda}, (U′)2e−βUλ(U')^2 e^{-\beta U_\lambda} and ∣∂2Uλ/∂λ2∣ e−βUλ|\partial^2 U_\lambda / \partial \lambda^2|\, e^{-\beta U_\lambda} are bounded, uniformly for λ\lambda in a neighbourhood of each point, by integrable functions of xx. Then derivatives in λ\lambda may be taken under the integral sign (dominated convergence).

Claim 1 (Kirkwood's identity). dAλ/dλ=⟨U′⟩λdA_\lambda / d\lambda = \langle U' \rangle_\lambda, and therefore

A1−A0=∫01⟨U′⟩λ dλ.A_1 - A_0 = \int_0^1 \langle U' \rangle_\lambda\, d\lambda.

Proof. dZλ/dλ=∫−βU′ e−βUλ dx=−βZλ⟨U′⟩λdZ_\lambda / d\lambda = \int -\beta U'\, e^{-\beta U_\lambda}\,dx = -\beta Z_\lambda \langle U' \rangle_\lambda. So dAλ/dλ=−β−1Zλ−1 dZλ/dλ=⟨U′⟩λdA_\lambda / d\lambda = -\beta^{-1} Z_\lambda^{-1}\, dZ_\lambda / d\lambda = \langle U' \rangle_\lambda. The derivative is continuous in λ\lambda under the same domination, so the fundamental theorem of calculus gives the integral. □\square

Claim 2 (curvature).

d2Aλdλ2=⟨∂2Uλ∂λ2⟩λ−β varλ(U′).\frac{d^2 A_\lambda}{d\lambda^2} = \Bigl\langle \frac{\partial^2 U_\lambda}{\partial \lambda^2} \Bigr\rangle_\lambda - \beta\, \mathrm{var}_\lambda(U').

On the linear path Uλ=(1−λ)U0+λU1U_\lambda = (1 - \lambda) U_0 + \lambda U_1 the first term is 0, so AλA_\lambda is concave in λ\lambda and g(λ)=⟨U1−U0⟩λg(\lambda) = \langle U_1 - U_0 \rangle_\lambda is non-increasing.

Proof. Differentiate ⟨U′⟩λ=Zλ−1∫U′e−βUλ dx\langle U' \rangle_\lambda = Z_\lambda^{-1} \int U' e^{-\beta U_\lambda}\,dx:

ddλ⟨U′⟩λ=⟨∂2Uλ∂λ2⟩λ−β⟨(U′)2⟩λ+β⟨U′⟩λ2,\frac{d}{d\lambda} \langle U' \rangle_\lambda = \Bigl\langle \frac{\partial^2 U_\lambda}{\partial \lambda^2} \Bigr\rangle_\lambda - \beta \langle (U')^2 \rangle_\lambda + \beta \langle U' \rangle_\lambda^2,

where the last term comes from dZλ−1/dλ=βZλ−1⟨U′⟩λd Z_\lambda^{-1} / d\lambda = \beta Z_\lambda^{-1} \langle U' \rangle_\lambda by Claim 1. The last two terms are −β varλ(U′)-\beta\, \mathrm{var}_\lambda(U'). On the linear path ∂2U/∂λ2=0\partial^2 U / \partial \lambda^2 = 0 and the variance is at least 0. □\square

Claim 3 (the estimator). Let the run at node λj\lambda_j give gˉj\bar g_j, the mean of U′(λj,xi)U'(\lambda_j, x_i) over NN samples, with E[gˉj]=g(λj)E[\bar g_j] = g(\lambda_j) (exact draws, or a stationary chain started in equilibrium) and the runs independent. Then the output T=∑jajgˉjT = \sum_j a_j \bar g_j has E[T]=Q=∑jajg(λj)E[T] = Q = \sum_j a_j g(\lambda_j) and var(T)=∑jaj2var(gˉj)\mathrm{var}(T) = \sum_j a_j^2 \mathrm{var}(\bar g_j). With independent draws and varλ(U′)<∞\mathrm{var}_\lambda(U') < \infty at the nodes, T→QT \to Q with probability 1 and var(T)=∑jaj2varλj(U′)/N\mathrm{var}(T) = \sum_j a_j^2 \mathrm{var}_{\lambda_j}(U') / N.

Proof. Linearity of expectation, independence of the runs for the variance of the sum, the law of large numbers at each node, and var(gˉj)=varλj(U′)/N\mathrm{var}(\bar g_j) = \mathrm{var}_{\lambda_j}(U') / N for independent draws. □\square

Lines L4 and L5 estimate var(gˉj)\mathrm{var}(\bar g_j) by sj2s_j^2 and add aj2sj2a_j^2 s_j^2, which is the plug-in form of this variance. With batch means, sj2s_j^2 estimates the variance of a correlated mean instead.

Claim 4 (total error).

T−ΔA=(Q−ΔA)+(T−Q),T - \Delta A = (Q - \Delta A) + (T - Q),

where Q−ΔAQ - \Delta A is the quadrature error of the rule on gg, a fixed number, and T−QT - Q has mean 0 and standard deviation var(T)=O(N−1/2)\sqrt{\mathrm{var}(T)} = O(N^{-1/2}). If gg is C2C^2 on [0,1][0, 1], the composite trapezoidal rule with KK intervals has ∣Q−ΔA∣≤max⁡∣g′′∣/(12K2)|Q - \Delta A| \le \max|g''| / (12 K^2); if gg is C4C^4, the composite Simpson rule has ∣Q−ΔA∣≤max⁡∣g(4)∣/(180K4)|Q - \Delta A| \le \max|g^{(4)}| / (180 K^4); the nn-point Gauss-Legendre rule is exact when gg is a polynomial of degree at most 2n−12n - 1.

Proof. The split is an identity, ΔA=∫01g\Delta A = \int_0^1 g by Claim 1, and Claim 3 gives the mean and variance of T−QT - Q. 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. □\square

Claim 5 (the harmonic example). For Uλ=(1+λ)x2/2U_\lambda = (1 + \lambda) x^2 / 2 in one dimension, g(λ)=1/(2β(1+λ))g(\lambda) = 1 / (2\beta (1 + \lambda)) and ΔA=(2β)−1ln⁡2\Delta A = (2\beta)^{-1} \ln 2.

Proof. U′=x2/2U' = x^2/2 and xx is normal with variance 1/(β(1+λ))1/(\beta(1 + \lambda)) in state λ\lambda, so g(λ)=1/(2β(1+λ))g(\lambda) = 1/(2\beta(1+\lambda)). Its integral over [0,1][0, 1] is (2β)−1ln⁡2(2\beta)^{-1} \ln 2, which equals −β−1ln⁡k0/k1-\beta^{-1} \ln \sqrt{k_0 / k_1} with k0=1k_0 = 1, k1=2k_1 = 2, the ratio of the Gaussian partition functions 2π/(βk)\sqrt{2\pi / (\beta k)}. □\square

The integrand gg here is decreasing, as Claim 2 requires, since Uλ=(1−λ)U0+λU1U_\lambda = (1 - \lambda) U_0 + \lambda U_1 with U0=x2/2U_0 = x^2/2 and U1=x2U_1 = x^2. It is also convex, so the trapezoidal rule overestimates the integral, as the example on the page shows.

Complexity

KK nodes with NN samples each cost KNK N evaluations of ∂U/∂λ\partial U / \partial \lambda plus KNK N steps of the sampler, which dominate. The extra space is O(N)O(N) for the samples of one node, or O(1)O(1) with running sums, and O(K)O(K) for the means. For a target error ε\varepsilon, the statistical part needs NK=O(ε−2)N K = O(\varepsilon^{-2}) samples in total, and the quadrature part needs K=O(ε−1/p)K = O(\varepsilon^{-1/p}) 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 ∂U/∂λ\partial U / \partial \lambda; on the linear path it is U1−U0U_1 - U_0.
  • Path-independent result, path-dependent cost. ΔA\Delta A 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 Uλ=(1−λ)kU0+λkU1U_\lambda = (1 - \lambda)^k U_0 + \lambda^k U_1, 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 λ\lambda 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 ∂U/∂λ\partial U / \partial \lambda 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, ⟨∂U/∂λ⟩\langle \partial U / \partial \lambda \rangle can diverge at λ=0\lambda = 0 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 λ\lambda 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.

thermodynamic_integration.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example