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
- Model
- Real RAM
- Properties
- consistentdeterministiciterativenot randomizednot unbiased
- Evidence
- Proof sketchCode in 1 languages
- 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 windows of umbrella sampling into one free energy profile along a collective variable. Each window has a known bias and an unknown free energy , which is the constant that the simple join of neighbouring windows tries to guess. WHAM finds all and the unbiased bin probabilities 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 given the histograms, and the minimum of one convex function of the , 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 , the histogram over bins of a collective variable, the number of samples , the bias at the bin centres, and . Let . The output is the unbiased probabilities , with , and the window free energies , which solve
The profile is then , up to a constant. The first equation weights the counts of all windows in bin ; the second says that is the free energy of window in the unbiased distribution .
The algorithm
WHAM(n_k(b), w_k(b), beta, tol)- 1
f_k ← 0 for every window k - 2
repeat - 3
for each bin b: p(b) ← n(b) / sum_k N_k exp(beta (f_k - w_k(b))) - 4
p ← p / sum_b p(b) - 5
for each window k: f_k ← -ln(sum_b p(b) exp(-beta w_k(b))) / beta - 6
until the largest change of any f_k is below tol - 7
return 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 moves by the same amount and is scaled to match, so is normalized at each step. All sums are done in the log domain with the log-sum-exp trick, because spans hundreds of orders of magnitude for bins far from the centre of window . Empty bins get .
The fixed points of this iteration are exactly the minimizers of the convex function
(Claim 2), which also gives a stopping test and a faster solver: Newton's method or a quasi-Newton method on .
Example
The data are those of the umbrella sampling page: , , , 17 harmonic windows at with , 20000 Metropolis samples per window, and 32 bins on . The exact barrier at the bin centres is 7.884 and the exact asymmetry is 0.
| method and seed | iterations | barrier | asymmetry | largest error, |
|---|---|---|---|---|
| simple join, seed 1 | 7.787 | 0.263 | ||
| WHAM, seed 1 | 1026 | 7.777 | 0.207 | |
| WHAM, seed 2 | 983 | 7.883 | 0.055 | 0.303 |
With tol 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 set to the exact biased bin probabilities, the iteration recovered to in 326 iterations. This checks the equations without sampling noise.
Bin width. Against the exact bin free energies (seed 1, tol ), 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:
- Maximum likelihood. If the counts of each window are multinomial with the biased bin probabilities , the WHAM equations are the conditions for the maximum of the likelihood over .
- The convex function. A point is a fixed point of lines L3 to L5 if and only if it is a stationary point of .
- Uniqueness. If every and the biases are finite, is convex, it does not change when all 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 is unique.
- 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 windows and bins, counts with for every , finite biases , and . Let and . Let , which is not empty. For write
Claim 1 (maximum likelihood). Model the counts of window as independent draws from the bin probabilities with , for an unknown in the simplex. At any maximizer of the likelihood with on , the WHAM equations hold:
Proof. Up to a constant, the log-likelihood is . If a bin with has mass , set it to 0 and divide the rest by . The first term grows by , and each changes by , so changes by . So a maximizer puts on bins outside , which agrees with the first equation. On , with a Lagrange multiplier for , the stationarity condition is
Multiply by and sum over : the left side gives , so . Define by , which is the second equation. Then the condition reads , the first equation.
Claim 2 (fixed points and the convex function). is a fixed point of lines L3 to L5 if and only if and the of line L3 already sums to 1. Every stationary point is mapped in one step to a fixed point on the same line .
Proof. , where is the unnormalized of line L3. For every ,
Let . Lines L4 and L5 map to with .
If , then for every , so and . Moving every by multiplies every by and so and by ; hence has , and by the invariance of Claim 3. So a stationary point is a fixed point exactly when , and one step maps any stationary point to the point of its line with . This proves the direction "stationary implies fixed" in that normalized sense: the stationary points with are fixed points.
Conversely, let . Then for every . Put this in : , so , and then .
Claim 3 (uniqueness). is convex and for every . For every that is not a multiple of , is strictly convex and tends to as . Hence has a minimizer, the set of minimizers is exactly one line , and the normalized of the WHAM equations is unique.
Proof. Invariance: , so the first term grows by and the second falls by .
Convexity: is a log-sum-exp of affine functions of . With , so that , its Hessian is , so
where . All because and the biases are finite, so this variance is 0 only if is constant. Since is not empty, the second derivative along is positive when is not a multiple of , which gives strict convexity along such lines.
Growth: as , , so . The bracket is positive when is not constant, because is an average of the with positive weights , times . The case is the same with .
Existence and uniqueness: restrict to the subspace , which meets each line once. On , is continuous, strictly convex, and tends to along every ray, so (a convex function that grows along every ray of a finite-dimensional space is coercive) it has exactly one minimizer on . By the invariance, the minimizers in are . By Claim 2, exactly one of them has , and its normalized is the same for every point of the line, since the scaling of cancels in the normalization.
Claim 4 (exact data). Let be a probability vector with on every bin, , and suppose exactly. Then solves the WHAM equations, so by Claim 3 WHAM returns .
Proof. , which is the first equation. The second holds by the definition of .
The counts in Claim 4 need not be integers: the equations and 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 directly, for example with Newton's method and a line search, which converges for a strictly convex coercive function.
Complexity
Each iteration costs exponentials and logarithms, so iterations cost . The extra space is for the bias table. The number of iterations depends on the overlap of the windows: when it is poor, the iteration moves the slowly, and hundreds or thousands of iterations are common, as in the example. Newton's method on costs 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 and finite biases.
- Maximum likelihood for independent samples in each window; for correlated samples it is still consistent, and 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 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 converge much faster than the fixed-point iteration.
- Error bars by bootstrap over blocks of each window, or from the Hessian of .
- 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. 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 over the range each window covers.
- Stopping too early. A tolerance on the change of per step can stop a slowly converging iteration far from the solution; check the gradient of 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 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.
# 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
- 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
- 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
- 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.
| 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 53HG7A Edit this page History Report an error Markdown