Algorithm Search⌘K

Algorithmadvanced

Weighted histogram analysis method

Also called WHAM.

Combines the biased histograms of umbrella sampling windows into one unbiased free energy profile by solving self-consistent equations.

Time
O(I K B) worst
Space
O(K B) extra
Where
B = the number of bins; I = the number of iterations; K = the number of windows
Properties
consistentdeterministiciterativenot randomizednot unbiased
Origin
Shankar Kumar, John M. Rosenberg, Djamal Bouzida, Robert H. Swendsen, Peter A. Kollman, 1992

The weighted histogram analysis method (WHAM) combines the histograms of the KK windows of umbrella sampling into one free energy profile along a collective variable. Each window kk has a known bias wk(s)w_k(s) and an unknown free energy fkf_k, which is the constant that the simple join of neighbouring windows tries to guess. WHAM finds all fkf_k and the unbiased bin probabilities p(b)p(b) together, from two coupled equations, and weights every window's counts in every bin by how much information they carry. The solution is the maximum likelihood estimate of pp given the histograms, and the minimum of one convex function of the fkf_k, so it is unique. The classic solver is a fixed-point iteration, simple but sometimes slow. For two states with no bins, the same equations give the Bennett acceptance ratio; for many states with no bins they give MBAR.

In plain words

Umbrella sampling gives many small pieces of a free energy curve, each seen through its own known spring. Each piece is correct only up to an unknown shift up or down.

WHAM finds all the shifts at once. It makes a guess for the true curve, uses it to predict what each simulation should have seen, and corrects the shifts until the predictions agree with the counts. Where several simulations saw the same region, it trusts each one in proportion to how many samples it put there.

The result does not depend on the order of the pieces, and it uses all the data in every region.

The problem

The input is, for each window k=1,…,Kk = 1, \dots, K, the histogram nk(b)n_k(b) over bins b=1,…,Bb = 1, \dots, B of a collective variable, the number of samples Nk=∑bnk(b)N_k = \sum_b n_k(b), the bias wk(b)w_k(b) at the bin centres, and β=1/(kBT)\beta = 1/(k_B T). Let n(b)=∑knk(b)n(b) = \sum_k n_k(b). The output is the unbiased probabilities p(b)p(b), with ∑bp(b)=1\sum_b p(b) = 1, and the window free energies fkf_k, which solve

p(b)=n(b)∑kNk eβ(fk−wk(b)),e−βfk=∑bp(b) e−βwk(b).p(b) = \frac{n(b)}{\sum_k N_k\, e^{\beta (f_k - w_k(b))}}, \qquad e^{-\beta f_k} = \sum_b p(b)\, e^{-\beta w_k(b)}.

The profile is then F(b)=−β−1ln⁡p(b)F(b) = -\beta^{-1} \ln p(b), up to a constant. The first equation weights the counts of all windows in bin bb; the second says that fkf_k is the free energy of window kk in the unbiased distribution pp.

The algorithm

  1. WHAM(n_k(b), w_k(b), beta, tol)
  2. 1f_k ← 0 for every window k
  3. 2repeat
  4. 3for each bin b: p(b) ← n(b) / sum_k N_k exp(beta (f_k - w_k(b)))
  5. 4p ← p / sum_b p(b)
  6. 5for each window k: f_k ← -ln(sum_b p(b) exp(-beta w_k(b))) / beta
  7. 6until the largest change of any f_k is below tol
  8. 7return p, f

Line L3 is the first equation and line L5 the second. Line L4 fixes the free constant: the equations do not change when every fkf_k moves by the same amount and pp is scaled to match, so pp is normalized at each step. All sums are done in the log domain with the log-sum-exp trick, because e−βwk(b)e^{-\beta w_k(b)} spans hundreds of orders of magnitude for bins far from the centre of window kk. Empty bins get p(b)=0p(b) = 0.

The fixed points of this iteration are exactly the minimizers of the convex function

L(f)=∑bn(b)ln⁡∑kNk eβ(fk−wk(b))−β∑kNkfk,L(f) = \sum_b n(b) \ln \sum_k N_k\, e^{\beta (f_k - w_k(b))} - \beta \sum_k N_k f_k,

(Claim 2), which also gives a stopping test and a faster solver: Newton's method or a quasi-Newton method on LL.

Example

The data are those of the umbrella sampling page: U(x)=8(x2−1)2U(x) = 8(x^2 - 1)^2, s=xs = x, kBT=1k_B T = 1, 17 harmonic windows at −1.6,−1.4,…,1.6-1.6, -1.4, \dots, 1.6 with κ=50\kappa = 50, 20000 Metropolis samples per window, and 32 bins on [−1.6,1.6][-1.6, 1.6]. The exact barrier at the bin centres is 7.884 and the exact asymmetry F(−0.95)−F(0.95)F(-0.95) - F(0.95) is 0.

method and seed iterations barrier F(0.05)−F(0.95)F(0.05) - F(0.95) asymmetry largest error, U<9U < 9
simple join, seed 1 7.787 −0.195-0.195 0.263
WHAM, seed 1 1026 7.777 −0.155-0.155 0.207
WHAM, seed 2 983 7.883 0.055 0.303

With tol =10−10= 10^{-10} the iteration took about 0.2 s. WHAM is only slightly better than the simple join on this easy one-dimensional case; its advantage is that it needs no order of joins and uses all overlaps at once, which matters for many windows, for two-dimensional grids and for windows of different temperatures.

Exact histograms. With nk(b)=NkPk(b)n_k(b) = N_k P_k(b) set to the exact biased bin probabilities, the iteration recovered pp to 1.5×10−141.5 \times 10^{-14} in 326 iterations. This checks the equations without sampling noise.

Bin width. Against the exact bin free energies (seed 1, tol 10−810^{-8}), the root mean square error was 0.227 with 16 bins, 0.090 with 32, 0.074 with 64 and 0.077 with 128. With wide bins the bias evaluated at the bin centre is a poor value for the whole bin; with narrow bins the counts per bin are small and the statistical error stops the gain.

Correctness

The proof in proofs/correctness.md shows:

  1. Maximum likelihood. If the counts of each window are multinomial with the biased bin probabilities p(b)e−βwk(b)/∑b′p(b′)e−βwk(b′)p(b) e^{-\beta w_k(b)} / \sum_{b'} p(b') e^{-\beta w_k(b')}, the WHAM equations are the conditions for the maximum of the likelihood over pp.
  2. The convex function. A point ff is a fixed point of lines L3 to L5 if and only if it is a stationary point of LL.
  3. Uniqueness. If every Nk>0N_k > 0 and the biases are finite, LL is convex, it does not change when all fkf_k move by the same amount, and it is strictly convex and grows without bound in every other direction. So it has a minimizer, unique up to that shift, and the normalized pp is unique.
  4. Exact data. If the histograms equal their expected values, the true bin probabilities solve the equations.

The proof does not show that the plain iteration converges for every input, and the number of iterations is a measurement.

Proof: The WHAM equations as maximum likelihood and as the minimum of a convex function, and the uniqueness of the solutionfull

Fix KK windows and BB bins, counts nk(b)≥0n_k(b) \ge 0 with Nk=∑bnk(b)>0N_k = \sum_b n_k(b) > 0 for every kk, finite biases wk(b)w_k(b), and β>0\beta > 0. Let n(b)=∑knk(b)n(b) = \sum_k n_k(b) and N=∑kNk=∑bn(b)N = \sum_k N_k = \sum_b n(b). Let B={b:n(b)>0}\mathcal B = \{b : n(b) > 0\}, which is not empty. For f∈RKf \in \mathbb R^K write

Db(f)=∑kNk eβ(fk−wk(b)),L(f)=∑b∈Bn(b)ln⁡Db(f)−β∑kNkfk.D_b(f) = \sum_k N_k\, e^{\beta (f_k - w_k(b))}, \qquad L(f) = \sum_{b \in \mathcal B} n(b) \ln D_b(f) - \beta \sum_k N_k f_k.

Claim 1 (maximum likelihood). Model the counts of window kk as NkN_k independent draws from the bin probabilities qk(b)=p(b)e−βwk(b)/ck(p)q_k(b) = p(b) e^{-\beta w_k(b)} / c_k(p) with ck(p)=∑b′p(b′)e−βwk(b′)c_k(p) = \sum_{b'} p(b') e^{-\beta w_k(b')}, for an unknown pp in the simplex. At any maximizer of the likelihood with p(b)>0p(b) > 0 on B\mathcal B, the WHAM equations hold:

p(b)=n(b)∑kNk eβ(fk−wk(b)),e−βfk=∑bp(b) e−βwk(b).p(b) = \frac{n(b)}{\sum_k N_k\, e^{\beta (f_k - w_k(b))}}, \qquad e^{-\beta f_k} = \sum_b p(b)\, e^{-\beta w_k(b)}.

Proof. Up to a constant, the log-likelihood is ℓ(p)=∑k∑bnk(b)ln⁡qk(b)=∑bn(b)ln⁡p(b)−∑kNkln⁡ck(p)+const\ell(p) = \sum_k \sum_b n_k(b) \ln q_k(b) = \sum_b n(b) \ln p(b) - \sum_k N_k \ln c_k(p) + \text{const}. If a bin b0b_0 with n(b0)=0n(b_0) = 0 has mass ϵ>0\epsilon > 0, set it to 0 and divide the rest by 1−ϵ1 - \epsilon. The first term grows by −Nln⁡(1−ϵ)-N \ln(1 - \epsilon), and each ln⁡ck\ln c_k changes by ln⁡(1−ϵe−βwk(b0)/ck)−ln⁡(1−ϵ)\ln(1 - \epsilon e^{-\beta w_k(b_0)} / c_k) - \ln(1 - \epsilon), so ℓ\ell changes by −∑kNkln⁡(1−ϵe−βwk(b0)/ck)>0-\sum_k N_k \ln(1 - \epsilon e^{-\beta w_k(b_0)} / c_k) > 0. So a maximizer puts p(b)=0p(b) = 0 on bins outside B\mathcal B, which agrees with the first equation. On B\mathcal B, with a Lagrange multiplier μ\mu for ∑bp(b)=1\sum_b p(b) = 1, the stationarity condition is

n(b)p(b)−∑kNke−βwk(b)ck(p)=μ.\frac{n(b)}{p(b)} - \sum_k N_k \frac{e^{-\beta w_k(b)}}{c_k(p)} = \mu.

Multiply by p(b)p(b) and sum over bb: the left side gives N−∑kNk=0N - \sum_k N_k = 0, so μ=0\mu = 0. Define fkf_k by e−βfk=ck(p)e^{-\beta f_k} = c_k(p), which is the second equation. Then the condition reads n(b)/p(b)=∑kNkeβfke−βwk(b)n(b) / p(b) = \sum_k N_k e^{\beta f_k} e^{-\beta w_k(b)}, the first equation. □\square

Claim 2 (fixed points and the convex function). ff is a fixed point of lines L3 to L5 if and only if ∇L(f)=0\nabla L(f) = 0 and the pp of line L3 already sums to 1. Every stationary point is mapped in one step to a fixed point on the same line f+c1f + c\mathbf 1.

Proof. ∂L/∂fk=βNkeβfk∑br(b)e−βwk(b)−βNk\partial L / \partial f_k = \beta N_k e^{\beta f_k} \sum_{b} r(b) e^{-\beta w_k(b)} - \beta N_k, where r(b)=n(b)/Db(f)r(b) = n(b) / D_b(f) is the unnormalized pp of line L3. For every ff,

∑kNkeβfk∑br(b)e−βwk(b)=∑br(b)Db(f)=∑bn(b)=N.(∗)\sum_k N_k e^{\beta f_k} \sum_b r(b) e^{-\beta w_k(b)} = \sum_b r(b) D_b(f) = \sum_b n(b) = N. \qquad (*)

Let z=∑br(b)z = \sum_b r(b). Lines L4 and L5 map ff to f′f' with e−βfk′=z−1∑br(b)e−βwk(b)e^{-\beta f'_k} = z^{-1} \sum_b r(b) e^{-\beta w_k(b)}.

If ∇L(f)=0\nabla L(f) = 0, then eβfk∑br(b)e−βwk(b)=1e^{\beta f_k} \sum_b r(b) e^{-\beta w_k(b)} = 1 for every kk, so e−βfk′=z−1e−βfke^{-\beta f'_k} = z^{-1} e^{-\beta f_k} and f′=f+β−1(ln⁡z) 1f' = f + \beta^{-1} (\ln z)\, \mathbf 1. Moving every fkf_k by cc multiplies every DbD_b by eβce^{\beta c} and so rr and zz by e−βce^{-\beta c}; hence f′f' has z=1z = 1, and ∇L(f′)=0\nabla L(f') = 0 by the invariance of Claim 3. So a stationary point is a fixed point exactly when z=1z = 1, and one step maps any stationary point to the point of its line with z=1z = 1. This proves the direction "stationary implies fixed" in that normalized sense: the stationary points with z=1z = 1 are fixed points.

Conversely, let f′=ff' = f. Then eβfk∑br(b)e−βwk(b)=ze^{\beta f_k} \sum_b r(b) e^{-\beta w_k(b)} = z for every kk. Put this in (∗)(*): ∑kNkz=N\sum_k N_k z = N, so z=1z = 1, and then ∂L/∂fk=βNk(z−1)=0\partial L / \partial f_k = \beta N_k (z - 1) = 0. □\square

Claim 3 (uniqueness). LL is convex and L(f+c1)=L(f)L(f + c \mathbf 1) = L(f) for every cc. For every vv that is not a multiple of 1\mathbf 1, t↦L(f+tv)t \mapsto L(f + t v) is strictly convex and tends to +∞+\infty as t→±∞t \to \pm\infty. Hence LL has a minimizer, the set of minimizers is exactly one line {f∗+c1}\{f^* + c \mathbf 1\}, and the normalized pp of the WHAM equations is unique.

Proof. Invariance: Db(f+c1)=eβcDb(f)D_b(f + c\mathbf 1) = e^{\beta c} D_b(f), so the first term grows by βc∑bn(b)=βcN\beta c \sum_b n(b) = \beta c N and the second falls by βc∑kNk=βcN\beta c \sum_k N_k = \beta c N.

Convexity: ln⁡Db(f)\ln D_b(f) is a log-sum-exp of affine functions of ff. With πk(b)=Nkeβ(fk−wk(b))/Db(f)\pi_k(b) = N_k e^{\beta(f_k - w_k(b))} / D_b(f), so that ∑kπk(b)=1\sum_k \pi_k(b) = 1, its Hessian is β2(diag(π(b))−π(b)π(b)T)\beta^2 (\mathrm{diag}(\pi(b)) - \pi(b) \pi(b)^T), so

vT∇2L(f) v=β2∑b∈Bn(b) varπ(b)(v)≥0,v^T \nabla^2 L(f)\, v = \beta^2 \sum_{b \in \mathcal B} n(b)\, \mathrm{var}_{\pi(b)}(v) \ge 0,

where varπ(b)(v)=∑kπk(b)vk2−(∑kπk(b)vk)2\mathrm{var}_{\pi(b)}(v) = \sum_k \pi_k(b) v_k^2 - (\sum_k \pi_k(b) v_k)^2. All πk(b)>0\pi_k(b) > 0 because Nk>0N_k > 0 and the biases are finite, so this variance is 0 only if vv is constant. Since B\mathcal B is not empty, the second derivative along vv is positive when vv is not a multiple of 1\mathbf 1, which gives strict convexity along such lines.

Growth: as t→+∞t \to +\infty, ln⁡Db(f+tv)=βtmax⁡kvk+O(1)\ln D_b(f + tv) = \beta t \max_k v_k + O(1), so L(f+tv)=βt (Nmax⁡kvk−∑kNkvk)+O(1)L(f + tv) = \beta t\,(N \max_k v_k - \sum_k N_k v_k) + O(1). The bracket is positive when vv is not constant, because ∑kNkvk\sum_k N_k v_k is an average of the vkv_k with positive weights Nk/NN_k / N, times NN. The case t→−∞t \to -\infty is the same with −v-v.

Existence and uniqueness: restrict LL to the subspace H={f:∑kfk=0}H = \{f : \sum_k f_k = 0\}, which meets each line f+c1f + c \mathbf 1 once. On HH, LL is continuous, strictly convex, and tends to +∞+\infty along every ray, so (a convex function that grows along every ray of a finite-dimensional space is coercive) it has exactly one minimizer f∗f^* on HH. By the invariance, the minimizers in RK\mathbb R^K are f∗+c1f^* + c \mathbf 1. By Claim 2, exactly one of them has z=1z = 1, and its p(b)=n(b)/Db(f∗)p(b) = n(b) / D_b(f^*) normalized is the same for every point of the line, since the scaling of rr cancels in the normalization. □\square

Claim 4 (exact data). Let p∘p^\circ be a probability vector with p∘(b)>0p^\circ(b) > 0 on every bin, e−βfk∘=∑bp∘(b)e−βwk(b)e^{-\beta f^\circ_k} = \sum_b p^\circ(b) e^{-\beta w_k(b)}, and suppose nk(b)=Nk p∘(b)e−β(wk(b)−fk∘)n_k(b) = N_k\, p^\circ(b) e^{-\beta (w_k(b) - f^\circ_k)} exactly. Then (p∘,f∘)(p^\circ, f^\circ) solves the WHAM equations, so by Claim 3 WHAM returns p∘p^\circ.

Proof. n(b)=p∘(b)∑kNkeβ(fk∘−wk(b))=p∘(b)Db(f∘)n(b) = p^\circ(b) \sum_k N_k e^{\beta (f^\circ_k - w_k(b))} = p^\circ(b) D_b(f^\circ), which is the first equation. The second holds by the definition of f∘f^\circ. □\square

The counts in Claim 4 need not be integers: the equations and LL are defined for real nonnegative counts, which is how the code checks the equations on exact data.

Remark (no claim about the iteration). Claims 2 and 3 show that the iteration can only stop at the right answer. They do not show that it converges, or how fast. The iteration counts on the page are measurements. A safe solver minimizes LL directly, for example with Newton's method and a line search, which converges for a strictly convex coercive function.

Complexity

Each iteration costs O(KB)O(K B) exponentials and logarithms, so II iterations cost O(IKB)O(I K B). The extra space is O(KB)O(K B) for the bias table. The number of iterations depends on the overlap of the windows: when it is poor, the iteration moves the fkf_k slowly, and hundreds or thousands of iterations are common, as in the example. Newton's method on LL costs O(K2B+K3)O(K^2 B + K^3) per step and usually converges in a few steps.

Properties

  • One profile, no order. All windows enter at once, with no chain of joins.
  • Unique solution up to the shared constant, for any data with all Nk>0N_k > 0 and finite biases.
  • Maximum likelihood for independent samples in each window; for correlated samples it is still consistent, and NkN_k can be replaced by an effective number of samples.
  • Bins. It works on a histogram, so the bin width adds a discretization error; MBAR removes the bins.
  • Works for any biases and temperatures in the form e−βk(U+wk)e^{-\beta_k (U + w_k)} when the energies are histogrammed too.

Variants and improvements

  • MBAR. The binless form, with one "bin" per sample (Shirts and Chodera 2008); it reduces to BAR for two states.
  • Multiple temperatures. The original multiple histogram method of Ferrenberg and Swendsen (1989) combined runs at different temperatures to get the density of states.
  • Newton and quasi-Newton solvers on the convex function LL converge much faster than the fixed-point iteration.
  • Error bars by bootstrap over blocks of each window, or from the Hessian of LL.
  • Two or more collective variables. The equations are the same with bins on a grid.

When to use it

Use WHAM to analyse umbrella sampling, replica exchange or multiple-temperature runs whenever the data can be put on a histogram of one or two variables. For high-dimensional data, or to avoid the bin error, use MBAR. Before WHAM, check that the windows overlap: WHAM always returns an answer, even for windows that share no bins, and the answer is then not reliable.

Pitfalls

  • Poor overlap. The solution is unique even when the windows barely overlap, but it is then fixed by a few counts in the tails and has a large error.
  • Underflow and overflow. e−βwk(b)e^{-\beta w_k(b)} is tiny far from the window centre; compute in the log domain.
  • Bin width. The bias is taken at the bin centre; the bin width must be small next to kBT/(κ∣s−sk∣)k_B T / (\kappa |s - s_k|) over the range each window covers.
  • Stopping too early. A tolerance on the change of ff per step can stop a slowly converging iteration far from the solution; check the gradient of LL as well.
  • Correlated samples. The likelihood assumes independent samples; the profile is still fine, but naive error bars are too small.
  • Samples outside the bins must be dropped from NkN_k too, or every window is counted with too many samples.

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.

weighted_histogram_analysis_method.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/weighted-histogram-analysis-method/. The authors are listed in prov/53HG7A.jsonl.
"""Weighted histogram analysis method (Kumar et al. 1992), one coordinate.

Window k has N_k samples, the histogram n_k(b) over bins b, and the bias
w_k(b) at the bin centres. WHAM finds the unbiased bin probabilities p(b) and
the window free energies f_k from the two coupled equations

    p(b) = sum_k n_k(b) / sum_k N_k exp(beta (f_k - w_k(b))),
    exp(-beta f_k) = sum_b p(b) exp(-beta w_k(b)).

The solution is the minimum of the convex function

    L(f) = sum_b n(b) ln sum_k N_k exp(beta (f_k - w_k(b))) - beta sum_k N_k f_k,

with n(b) = sum_k n_k(b). L does not change when every f_k moves by the same
constant, so p is normalised to sum 1 to fix that constant.

The plain fixed-point iteration below is the classic one. It can be slow when
windows overlap poorly; its speed here is a measurement, not a bound.
"""

import math
from typing import Callable, Sequence


def _logsumexp(xs: Sequence[float]) -> float:
    m = max(xs)
    if m == -math.inf:
        return m
    return m + math.log(sum(math.exp(x - m) for x in xs))


def wham(counts: Sequence[Sequence[float]], bias: Sequence[Sequence[float]], beta: float,
         tol: float = 1e-10, max_iter: int = 100000) -> tuple[list[float], list[float], int]:
    """Return (p, f, iterations). counts[k][b] = n_k(b), bias[k][b] = w_k(b)."""
    nwin, nbins = len(counts), len(counts[0])
    big_n = [sum(c) for c in counts]
    if min(big_n) <= 0:
        raise ValueError("every window needs samples")
    log_n = [math.log(x) for x in big_n]
    total = [sum(counts[k][b] for k in range(nwin)) for b in range(nbins)]
    f = [0.0] * nwin                                                    # @line L1
    for it in range(1, max_iter + 1):                                   # @line L2
        log_p = []
        for b in range(nbins):                                          # @line L3
            if total[b] == 0:
                log_p.append(-math.inf)
                continue
            den = _logsumexp([log_n[k] + beta * (f[k] - bias[k][b]) for k in range(nwin)])
            log_p.append(math.log(total[b]) - den)                      # @line L3
        z = _logsumexp(log_p)
        log_p = [x - z for x in log_p]                                  # @line L4
        new_f = [-_logsumexp([lp - beta * bias[k][b] for b, lp in enumerate(log_p)]) / beta
                 for k in range(nwin)]                                  # @line L5
        change = max(abs(a - c) for a, c in zip(new_f, f))
        f = new_f
        if change < tol:                                                # @line L6
            break
    p = [math.exp(x) for x in log_p]
    return p, f, it                                                     # @line L7


def objective(f: Sequence[float], counts: Sequence[Sequence[float]],
              bias: Sequence[Sequence[float]], beta: float) -> float:
    """The convex function L(f) whose minimum solves the WHAM equations."""
    nwin, nbins = len(counts), len(counts[0])
    big_n = [sum(c) for c in counts]
    val = -beta * sum(n * fk for n, fk in zip(big_n, f))
    for b in range(nbins):
        nb = sum(counts[k][b] for k in range(nwin))
        if nb:
            val += nb * _logsumexp([math.log(big_n[k]) + beta * (f[k] - bias[k][b])
                                    for k in range(nwin)])
    return val


def free_energy_profile(p: Sequence[float], beta: float) -> list:
    """F(b) = -kT ln p(b), shifted so that the minimum is 0; None for empty bins."""
    vals = [(-math.log(x) / beta) if x > 0 else None for x in p]
    m = min(v for v in vals if v is not None)
    return [v - m if v is not None else None for v in vals]


# Sampling helpers for the tests: biased Metropolis windows on s = x.

def double_well(height: float) -> Callable[[float], float]:
    return lambda x: height * (x * x - 1.0) ** 2


def metropolis(u: Callable[[float], float], beta: float, x0: float, step: float,
               n: int, rng, burn: int = 500) -> list[float]:
    x, ux = x0, u(x0)
    out = []
    for i in range(burn + n):
        y = x + step * (2.0 * rng.random() - 1.0)
        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


def histogram(values: Sequence[float], lo: float, hi: float, nbins: int) -> list[int]:
    counts = [0] * nbins
    width = (hi - lo) / nbins
    for v in values:
        b = int((v - lo) // width)
        if 0 <= b < nbins:
            counts[b] += 1
    return counts
test_weighted_histogram_analysis_method.py 116 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/weighted-histogram-analysis-method/. The authors are listed in prov/53HG7A.jsonl.
import math
import random

import pytest

from weighted_histogram_analysis_method import (
    double_well,
    free_energy_profile,
    histogram,
    metropolis,
    objective,
    wham,
)

LO, HI, NB = -1.6, 1.6, 32
WIDTH = (HI - LO) / NB
CENTERS = [LO + (b + 0.5) * WIDTH for b in range(NB)]
U = double_well(8.0)


def true_bin_probabilities():
    p = [math.exp(-U(s)) for s in CENTERS]
    z = sum(p)
    return [x / z for x in p]


def windows(spacing, kappa):
    cs = [LO + spacing * k for k in range(int(round((HI - LO) / spacing)) + 1)]
    return cs, [[0.5 * kappa * (s - c) ** 2 for s in CENTERS] for c in cs]


def test_expected_histograms_give_the_true_distribution():
    # Each window gets the exact expected counts N_k p(b) e^{-w_k(b)} / Z_k.
    pt = true_bin_probabilities()
    cs, bias = windows(0.4, 50.0)
    counts = []
    for wk in bias:
        q = [x * math.exp(-w) for x, w in zip(pt, wk)]
        z = sum(q)
        counts.append([1000.0 * x / z for x in q])
    p, f, _ = wham(counts, bias, 1.0, tol=1e-13)
    assert max(abs(a - b) for a, b in zip(p, pt)) < 1e-12
    # f_k is -kT ln of the biased partition function, relative to the normalised p.
    for fk, wk in zip(f, bias):
        assert fk == pytest.approx(-math.log(sum(x * math.exp(-w) for x, w in zip(pt, wk))), abs=1e-10)


def test_one_window_reduces_to_unbiasing():
    bias = [[0.5 * 20.0 * (s - 0.3) ** 2 for s in CENTERS]]
    rng = random.Random(3)
    counts = [[rng.randint(1, 50) for _ in CENTERS]]
    p, _, _ = wham(counts, bias, 1.0)
    q = [n * math.exp(w) for n, w in zip(counts[0], bias[0])]
    z = sum(q)
    assert p == pytest.approx([x / z for x in q], rel=1e-9)


def test_zero_bias_gives_the_pooled_histogram():
    rng = random.Random(4)
    counts = [[rng.randint(0, 9) for _ in CENTERS] for _ in range(3)]
    p, f, _ = wham(counts, [[0.0] * NB] * 3, 1.0)
    pooled = [sum(c[b] for c in counts) for b in range(NB)]
    total = sum(pooled)
    assert p == pytest.approx([x / total for x in pooled], abs=1e-12)
    assert f == pytest.approx([0.0, 0.0, 0.0], abs=1e-12)


def test_solution_minimises_the_convex_objective():
    rng = random.Random(5)
    cs, bias = windows(0.4, 50.0)
    counts = [histogram(metropolis(lambda x, c=c: U(x) + 25.0 * (x - c) ** 2, 1.0, c, 0.3, 2000, rng),
                        LO, HI, NB) for c in cs]
    _, f, _ = wham(counts, bias, 1.0, tol=1e-12)
    base = objective(f, counts, bias, 1.0)
    # The objective does not change when every f_k moves by the same constant.
    assert objective([x + 1.7 for x in f], counts, bias, 1.0) == pytest.approx(base, rel=1e-12)
    # The gradient is zero at the solution.
    h = 1e-5
    for k in range(len(f)):
        up = list(f)
        dn = list(f)
        up[k] += h
        dn[k] -= h
        grad = (objective(up, counts, bias, 1.0) - objective(dn, counts, bias, 1.0)) / (2 * h)
        assert abs(grad) < 1e-3
    # Any other point that is not a constant shift has a larger value.
    for _ in range(20):
        g = [x + rng.gauss(0.0, 0.3) for x in f]
        assert objective(g, counts, bias, 1.0) > base


def test_double_well_profile_against_exact():
    rng = random.Random(1)
    cs, bias = windows(0.2, 50.0)
    counts = [histogram(metropolis(lambda x, c=c: U(x) + 25.0 * (x - c) ** 2, 1.0, c, 0.3, 20000, rng),
                        LO, HI, NB) for c in cs]
    p, _, _ = wham(counts, bias, 1.0, tol=1e-8)
    f = free_energy_profile(p, 1.0)
    # The exact free energy of each bin, -ln of the integral of e^{-U} over the bin.
    exact = []
    for b in range(NB):
        a = LO + b * WIDTH
        exact.append(-math.log(sum(math.exp(-U(a + (i + 0.5) * WIDTH / 100)) for i in range(100)) * WIDTH / 100))
    pairs = [(v, e) for v, e, s in zip(f, exact, CENTERS) if U(s) < 9.0]
    assert all(v is not None for v, _ in pairs)
    off = sum(e - v for v, e in pairs) / len(pairs)
    assert max(abs(v + off - e) for v, e in pairs) < 0.4
    assert f[16] - f[25] == pytest.approx(exact[16] - exact[25], abs=0.3)  # barrier, 0.05 against 0.95
    assert abs(f[6] - f[25]) < 0.35  # the two wells, -0.95 against 0.95


def test_window_without_samples_raises():
    with pytest.raises(ValueError):
        wham([[1, 2], [0, 0]], [[0.0, 0.0], [0.0, 0.0]], 1.0)

History

Ferrenberg and Swendsen (1989) introduced the multiple histogram method to combine Monte Carlo runs at several temperatures. Kumar, Rosenberg, Bouzida, Swendsen and Kollman (1992) extended it to biased runs such as umbrella sampling windows and to free energies along a coordinate, and gave the equations in their present form. Later work wrote WHAM as a maximum likelihood problem and as the minimum of a convex function, and Shirts and Chodera (2008) removed the bins with MBAR.

References

  1. Shankar Kumar, John M. Rosenberg, Djamal Bouzida, Robert H. Swendsen and Peter A. Kollman, The weighted histogram analysis method for free-energy calculations on biomolecules. I. The method, Journal of Computational Chemistry 13(8), 1992, 1011-1021, the WHAM equations for the unbiased probabilities and the window free energies, and their iterative solution
  2. Michael R. Shirts and John D. Chodera, Statistically optimal analysis of samples from multiple equilibrium states, Journal of Chemical Physics 129, 124105, 2008, the MBAR estimating equations and their relation to WHAM in the limit of narrow bins
  3. Johannes Kästner, Umbrella sampling, Wiley Interdisciplinary Reviews, Computational Molecular Science 1(6), 2011, 932-942, the use of WHAM to combine the windows of umbrella sampling

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