Algorithmcore
Umbrella sampling
Adds biasing potentials that restrain a collective variable in overlapping windows so rare regions are sampled, and removes the bias afterwards.
- Time
- O(K n + K B) worst
- Space
- O(K B) extra
- Where
- B = the number of histogram bins; K = the number of windows; n = the number of samples per window
- Model
- Real RAM
- Properties
- consistentrandomizednot iterativeparallelrandomizednot unbiased
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Glenn M. Torrie, John P. Valleau, 1977
Umbrella sampling computes the free energy profile along a collective variable when ordinary sampling never crosses the barriers between the low regions of . It runs separate simulations, called windows. Window adds a bias , usually a harmonic spring , that holds near the centre , so each window samples a narrow range of , including the high-energy ones. In each window the bias is known exactly, so it can be removed from the window histogram, which leaves on that range up to an unknown constant. The constants come from the overlap of neighbouring windows. This page uses a simple join of neighbours; the weighted histogram analysis method (WHAM) is the standard way to combine all windows at once. It is a form of importance sampling with a chosen, non-physical sampling distribution (Torrie and Valleau 1977).
In plain words
Some molecular events, such as a bond breaking or a protein changing shape, need the system to climb over a high hill of energy. An ordinary simulation stays in a valley and almost never makes that climb.
Umbrella sampling puts a spring on the system that holds one chosen quantity near a chosen value. One simulation is held at the bottom of the valley, the next a little higher up the hill, and so on over the top. Each simulation sees only its own small piece of the hill.
The spring changes what each simulation sees, but its effect is known exactly, so it can be taken away afterwards. The pieces overlap, which tells us how to fit them together into the full shape of the hill.
The problem
The input is a potential , a collective variable , the inverse temperature , window centres , a spring constant , and bins on an interval of . The target is the free energy profile
on the bins. In window the sampled density is proportional to , and its marginal in is up to a constant factor, so
with one unknown constant per window (Claim 1 of the proof).
The algorithm
UMBRELLA(U, s_1..s_K, kappa, beta, bins)- 1
for k ← 1 to K do ▷ the windows are independent - 2
sample x from exp(-beta (U(x) + kappa/2 (s(x) - s_k)^2)), by Monte Carlo or MD - 3
n_k(b) ← number of samples with s(x) in bin b - 4
F_k(b) ← -ln(n_k(b)) / beta - w_k(centre of b) on bins with enough counts - 5
F ← F_1 - 6
for k ← 2 to K do c ← mean of F(b) - F_k(b) over the bins defined in both - 7
merge F_k + c into F, as a count-weighted mean on shared bins - 8
return F - min F
Lines L1 to L4 are the sampling; the windows can run in parallel. Line L4 uses only bins with enough samples (50 in the code here), because of a small count is noisy and biased. Lines L5 to L7 fix the constants: each new window is shifted to agree on average with the profile so far on the bins they share. Line L8 sets the lowest point to 0, since is defined only up to a constant.
The spacing of the windows must let each pair of neighbours share several well-sampled bins. With a harmonic bias the width of window is about when , so a spacing of one or two such widths is usual.
Example
Take the double well with and , so the exact profile is , with minima at and a barrier of at 0. A plain Metropolis chain started at with step 0.3 did not reach once in 50000 steps.
With 17 windows centred at , , 20000 Metropolis samples per window with step 0.3 and 32 bins on (seed 1):
| quantity | umbrella sampling | exact at the bin centres |
|---|---|---|
| barrier, | 7.787 | 7.884 |
| asymmetry, | 0 | |
| largest error on bins with | 0.263 |
The barrier is within . The asymmetry error comes from the 16 joins: each shift has a small error, and these errors add up from the left end to the right end. Other seeds gave barrier errors below and asymmetry errors from 0.1 to 0.25. With only 3000 samples per window and a count threshold of 10, the largest error was 0.247, so the join and the bin width, not the number of samples, limit the result here.
Correctness
The proof in proofs/correctness.md shows:
- Unbiasing a window. The marginal of in window is up to a constant, so equals up to a constant, for every bias that depends on only through .
- Consistency of one window. As the number of samples grows, line L4 converges to averaged over the bin, up to a constant, with a bin error at most the variation of across the bin.
- The join. If each window profile is exact up to its constant on the shared bins, lines L5 to L8 return exactly up to a global constant; with errors in the windows, the error of the joined profile is bounded by a sum of window errors along the chain of joins.
Proof: Unbiasing of a window, the bin error, and the join of the windowsfull
Let be a potential with finite and positive, a measurable collective variable, and the density of when has density ; assume is continuous and positive on the interval of interest. Define . Window samples the density proportional to , where is continuous and is finite.
Claim 1 (unbiasing a window). The density of in window is . Hence
with independent of .
Proof. For a bounded measurable , . So . Take of both sides and rearrange.
The proof uses only that the bias depends on through . A bias on another variable would change the conditional distribution of given , and the identity would fail.
Claim 2 (one window, many samples). Let bin be an interval with centre and half-width , and define the bin free energy . Let . If the samples of window come from an ergodic chain with stationary density , then with probability 1, as ,
For the harmonic bias , .
Proof. By the ergodic theorem , which is positive, and is continuous on . By Claim 1, , and on the factor lies between and . So
with . Subtract . For the harmonic bias, , and .
Taking instead of , as line L4 does, only adds the constant to every bin of the window, which is absorbed into the window constant. Thus each window profile converges to the bin free energy up to a constant, with an error that is small when the bins are narrow compared with .
Claim 3 (the join). Let , for in a set of bins, be the window profiles of line L4, and suppose with constants and errors . Suppose that for each the set shares at least one bin with . Then lines L5 to L8 return a profile with
where is the profile before line L8, on every bin covered by some window. In particular, if all errors are 0, the output is exactly on the covered bins.
Proof. Induction on . Let be the profile after window is merged, and claim with . For , and . At step the shift is , where is the shared set, which is not empty by assumption. So with . Line L7 sets each bin either to this value or to a weighted mean of it and , whose error is at most ; a weighted mean with nonnegative weights has error at most the larger of the two. This gives the bound for . Line L8 subtracts the same number from every bin.
The bound of Claim 3 is a worst case. Window errors of random sign add more like a random walk, so the error between the two ends of a chain of windows grows roughly like , which matches the asymmetry error of the example on the page. WHAM avoids the order of joins by solving for all constants at once.
Remark (the example). In the example , so and up to a constant. The bin free energy differs from by at most the variation of over the bin, which is why the page compares with at the bin centres on bins where the variation is small.
Complexity
Sampling costs energy evaluations per window, so in total, and this term dominates in practice. The histograms cost and the join . The windows are independent and run in parallel. The extra space is for the histograms. The number of windows needed grows with the length of the path in divided by the window width, and the statistical error of at a point grows roughly with the square root of the number of joins between it and the reference point.
Properties
- Exact unbiasing. The bias is removed exactly in each window; the only errors are statistical, the bin width, and the join.
- Any bias that depends only on can be used; the harmonic spring is the common choice.
- Parallel. The windows need no communication.
- Depends on the collective variable. It gives along ; if a slow motion is not described by , each window can stay stuck in one valley of the hidden motion and the profile is wrong.
- Consistent, not unbiased. The log of a histogram count is biased for finite counts.
Variants and improvements
- WHAM and MBAR. The weighted histogram analysis method combines all windows with weights of least variance and needs no order of joins; MBAR does the same without bins.
- Umbrella integration. Estimate the mean force in each window from the mean and variance of , and integrate it; this needs no overlap between histograms (Kästner 2011).
- Replica exchange umbrella sampling. Run the windows in parallel and swap configurations between neighbouring windows, as in parallel tempering, to relax hidden slow motions.
- Adaptive biases. Metadynamics and Wang-Landau sampling build a bias that flattens the profile during the run instead of using fixed windows.
- Multidimensional windows. Biases on two or three collective variables give a free energy surface, at a cost that grows with the number of windows on the grid.
When to use it
Use umbrella sampling when a good collective variable is known, the path between the states along it is clear, and the barrier is too high for plain sampling. It is robust and simple, and with WHAM or MBAR it is a standard tool for potentials of mean force, for example along a distance in ligand unbinding or along a reaction coordinate in a QM/MM study. For many collective variables, or when the path is not known, adaptive methods such as metadynamics are often easier.
Pitfalls
- Too little overlap. Neighbouring windows must share well-sampled bins; check the histograms of all windows on one plot.
- Springs that are too stiff or too soft. A stiff spring gives narrow windows and needs many of them; a soft one does not hold the system on a steep part of .
- Hidden slow motions. If each window samples only one of two valleys orthogonal to , the profile depends on the starting configuration; compare runs from different starts.
- Equilibration. Each window starts from a configuration that may be far from its biased equilibrium; discard the first part of each run.
- Bin width. Evaluating the bias at the bin centre adds an error up to the change of across the bin, which is largest far from the window centre.
- Jacobian terms. For a distance or an angle, contains the entropy of the volume element, such as for a distance in three dimensions; this is part of , not an error.
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/umbrella-sampling/. The authors are listed in prov/H90CB5.jsonl.
"""Umbrella sampling (Torrie and Valleau 1977) on a one-dimensional coordinate.
Each window k adds the bias w_k(s) = (kappa / 2) (s - s_k)^2 to the potential
and samples exp(-beta (U + w_k)). In window k the free energy is known up to a
constant from the biased histogram,
F(b) = -kT ln n_k(b) - w_k(b) + c_k,
and the constants c_k are fixed by asking neighbouring windows to agree on the
bins they share. This file uses that simple join (a least-squares match on the
shared bins). WHAM is the better way to combine the windows; see the WHAM page.
The coordinate is s = x here, so the exact free energy profile is U itself,
which the tests use.
"""
import math
from typing import Callable, Sequence
def double_well(height: float) -> Callable[[float], float]:
"""U(x) = height (x^2 - 1)^2, minima at x = -1 and x = 1, barrier height at x = 0."""
return lambda x: height * (x * x - 1.0) ** 2
def harmonic_bias(center: float, kappa: float) -> Callable[[float], float]:
return lambda s: 0.5 * kappa * (s - center) ** 2
def metropolis(u: Callable[[float], float], beta: float, x0: float, step: float,
n: int, rng, burn: int = 500) -> list[float]:
"""Random walk Metropolis chain for the density exp(-beta u)."""
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
def bin_centers(lo: float, hi: float, nbins: int) -> list[float]:
width = (hi - lo) / nbins
return [lo + (b + 0.5) * width for b in range(nbins)]
def unbias(counts: Sequence[int], bias: Callable[[float], float], centers: Sequence[float],
beta: float, min_count: int = 50) -> list:
"""-kT ln n(b) - w(b) on bins with at least min_count samples, None elsewhere."""
return [(-math.log(c) / beta - bias(s)) if c >= min_count else None
for c, s in zip(counts, centers)]
def join_windows(profiles: Sequence[list], counts: Sequence[Sequence[int]]) -> list:
"""Join window profiles, in order along s, into one profile with minimum 0."""
f = list(profiles[0]) # @line L5
weight = [c if p is not None else 0 for p, c in zip(f, counts[0])]
for prof, cnt in zip(profiles[1:], counts[1:]): # @line L6
shared = [b for b, (a, p) in enumerate(zip(f, prof)) if a is not None and p is not None]
if not shared:
raise ValueError("neighbouring windows share no bins")
shift = sum(f[b] - prof[b] for b in shared) / len(shared) # @line L6
for b, p in enumerate(prof): # @line L7
if p is None:
continue
p += shift
if f[b] is None:
f[b], weight[b] = p, cnt[b]
else: # count-weighted mean
f[b] = (weight[b] * f[b] + cnt[b] * p) / (weight[b] + cnt[b])
weight[b] += cnt[b]
m = min(v for v in f if v is not None)
return [v - m if v is not None else None for v in f] # @line L8
def umbrella_sampling(u: Callable[[float], float], centers_s: Sequence[float], kappa: float,
beta: float, n: int, step: float, lo: float, hi: float, nbins: int,
rng) -> tuple[list, list[list[int]]]:
"""Free energy profile on the bins of [lo, hi], and the window histograms."""
centers = bin_centers(lo, hi, nbins)
profiles, all_counts = [], []
for s_k in centers_s: # @line L1
w = harmonic_bias(s_k, kappa)
xs = metropolis(lambda x: u(x) + w(x), beta, s_k, step, n, rng) # @line L2
counts = histogram(xs, lo, hi, nbins) # @line L3
profiles.append(unbias(counts, w, centers, beta)) # @line L4
all_counts.append(counts)
return join_windows(profiles, all_counts), all_counts
test_umbrella_sampling.py 80 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/umbrella-sampling/. The authors are listed in prov/H90CB5.jsonl.
import math
import random
import pytest
from umbrella_sampling import (
bin_centers,
double_well,
harmonic_bias,
histogram,
join_windows,
metropolis,
umbrella_sampling,
unbias,
)
def test_histogram_and_bin_centers():
assert histogram([0.05, 0.15, 0.17, 0.99, 1.2, -0.1], 0.0, 1.0, 10) == [1, 2, 0, 0, 0, 0, 0, 0, 0, 1]
assert bin_centers(0.0, 1.0, 4) == pytest.approx([0.125, 0.375, 0.625, 0.875])
def test_unbias_recovers_profile_from_exact_counts():
# Counts proportional to exp(-(F + w)) give back F up to one constant.
centers = bin_centers(-1.0, 1.0, 20)
f = [math.sin(3 * s) for s in centers]
w = harmonic_bias(0.3, 5.0)
counts = [1e5 * math.exp(-(fb + w(s))) for fb, s in zip(f, centers)]
prof = unbias(counts, w, centers, 1.0)
shifts = [p - fb for p, fb in zip(prof, f)]
assert max(shifts) - min(shifts) < 1e-12
def test_unbias_drops_sparse_bins():
centers = bin_centers(0.0, 1.0, 3)
prof = unbias([100, 3, 0], lambda s: 0.0, centers, 1.0, min_count=10)
assert prof[1] is None and prof[2] is None
assert prof[0] == pytest.approx(-math.log(100))
def test_join_removes_window_constants_exactly():
true = [0.0, 1.0, 3.0, 2.0, 0.5, 1.5]
a = [v + 7.0 for v in true[:4]] + [None, None]
b = [None, None] + [v - 2.0 for v in true[2:]]
joined = join_windows([a, b], [[100] * 6, [100] * 6])
assert joined == pytest.approx(true)
def test_join_needs_shared_bins():
with pytest.raises(ValueError):
join_windows([[0.0, None], [None, 0.0]], [[100, 0], [0, 100]])
def test_plain_sampling_is_trapped_in_one_well():
# Barrier of 8 kT: a plain chain started at x = -1 does not cross in 50000 steps.
xs = metropolis(double_well(8.0), 1.0, -1.0, 0.3, 50000, random.Random(2))
assert max(xs) < 0.0
def test_double_well_profile_against_exact():
u = double_well(8.0)
lo, hi, nb = -1.6, 1.6, 32
windows = [-1.6 + 0.2 * k for k in range(17)]
f, counts = umbrella_sampling(u, windows, 50.0, 1.0, 20000, 0.3, lo, hi, nb, random.Random(1))
centers = bin_centers(lo, hi, nb)
# Every bin below 9 kT has enough samples, including the barrier top.
assert all(v is not None for v, s in zip(f, centers) if u(s) < 9.0)
assert min(v for v in f if v is not None) == 0.0
# Here s = x, so the exact profile is U up to a constant.
pairs = [(v, u(s)) for v, s in zip(f, centers) if u(s) < 9.0]
off = sum(e - v for v, e in pairs) / len(pairs)
assert max(abs(v + off - e) for v, e in pairs) < 0.4
i0, im, ip = 16, 6, 25 # bins centred at 0.05, -0.95 and 0.95
assert centers[i0] == pytest.approx(0.05) and centers[im] == pytest.approx(-0.95)
assert centers[ip] == pytest.approx(0.95)
barrier = f[i0] - f[ip]
assert barrier == pytest.approx(u(centers[i0]) - u(centers[ip]), abs=0.4)
assert abs(f[im] - f[ip]) < 0.4
History
Torrie and Valleau (1977) used sampling distributions that are not physical but cover the important regions of two states at once, and reweighted the samples to compute free energy differences; the distribution that spans both states gave the name. The use of many harmonic windows along a coordinate, combined with WHAM (Kumar and co-workers 1992), became the standard method for potentials of mean force in biomolecular simulation. Kästner (2011) reviews the method and its analysis.
References
- Glenn M. Torrie and John P. Valleau, Nonphysical sampling distributions in Monte Carlo free-energy estimation, umbrella sampling, Journal of Computational Physics 23(2), 1977, 187-199, the biased sampling distribution and the reweighting of its samples to the unbiased ensemble
- Johannes Kästner, Umbrella sampling, Wiley Interdisciplinary Reviews, Computational Molecular Science 1(6), 2011, 932-942, the review of harmonic window biases, the choice of force constant and window spacing, and the ways to combine windows
- 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 combination of the biased histograms of many umbrella windows into one free energy profile
- Daan Frenkel and Berend Smit, Understanding Molecular Simulation, From Algorithms to Applications, second edition, Academic Press, 2002, the chapter on free energy calculations, the section on umbrella sampling
Where this leads
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 H90CB5 Edit this page History Report an error Markdown