Algorithmadvanced
Bennett acceptance ratio
Also called BAR method.
Estimates a free energy difference from samples of both end states by solving an equation for the minimum-variance estimate.
- Time
- O(b n) worst
- Space
- O(1) extra
- Where
- b = the number of bisection steps; n = the total number of samples of the two states
- Model
- Real RAM
- Properties
- consistentdeterministiciterativenot randomizednot unbiased
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Charles H. Bennett, 1976
The Bennett acceptance ratio (BAR) estimates the free energy difference of two states from samples of both states. Free energy perturbation uses one state and is poor in one of its two directions; BAR uses both directions at once with the weight that makes the large-sample variance smallest (Bennett 1976, a theorem). The estimate is the root of one equation in one unknown, which has exactly one root, so a bisection always finds it. In statistics the same estimator is the optimal case of bridge sampling (Meng and Wong 1996), and it is also the maximum likelihood estimate of given the energy differences (Shirts and co-workers 2003). With FEP, thermodynamic integration and the Jarzynski equality it forms the standard set of free energy methods; for many states, MBAR (Shirts and Chodera 2008) generalizes it.
In plain words
Free energy perturbation looks from one state towards the other. Looking from the first state works well in some cases, and looking from the second works well in others, but each view alone can miss what the other sees.
Bennett's method looks from both sides at once. For each snapshot of either state, it asks how much the energy would change in the other state. It then finds the one value of the free energy difference that makes the two sets of snapshots agree, in a balanced way that gives each snapshot a weight between zero and one. No single lucky snapshot can dominate.
The answer comes from a simple search: try a value, see which side is too large, and halve the interval.
The problem
The input is samples of the canonical ensemble of state 0 and samples of state 1, the energies and on both sets, and . Write the reduced differences
and the Fermi function . The output is the root of
and an error bar. The identity behind it holds for every weight function (Claim 1 of the proof), and the Fermi function comes from the weight of least variance (Claim 4).
The algorithm
BAR(w_F[1..n_0], w_R[1..n_1], beta) ▷ f(t) = 1 / (1 + e^t)- 1
M ← ln(n_1 / n_0) - 2
lo ← min(min_i w_F[i], min_j -w_R[j]) - 40; hi ← max(max_i w_F[i], max_j -w_R[j]) + 40 - 3
while hi - lo > tol do - 4
C ← (lo + hi) / 2 - 5
if sum_j f(w_R[j] + C) > sum_i f(w_F[i] - C) then lo ← C - 6
else hi ← C - 7
return ((lo + hi) / 2 - M) / beta
The left side of the equation decreases strictly in and the right side increases strictly, so their difference has exactly one sign change, and lines L3 to L6 keep the root inside . The bracket of line L2 holds whenever and are below (Claim 3). The function is computed as for , so it never overflows. Each test of line L5 costs . A Newton step on the same equation converges faster, but bisection cannot fail.
The error bar is the delta-method error at the root,
for independent samples. It is a large-sample estimate.
Example
By hand. One sample of each state, with at the state-0 sample and at the state-1 sample, at . Then , , , and the equation holds when , so and : the mean of the two energy differences. FEP from state 0 alone would give 1.0 and from state 1 alone 0.2.
Harmonic wells. and at , so . With exact samples of each state (seed 1):
| BAR | BAR error bar | FEP forward | FEP reverse | |
|---|---|---|---|---|
| 10 | 0.3303 | 0.0992 | 0.3565 | 0.3616 |
| 100 | 0.3214 | 0.0303 | 0.3100 | 0.3166 |
| 1000 | 0.3517 | 0.0103 | 0.3536 | 0.3345 |
Over 500 independent replicas (seed 4), the mean error and the spread of each estimate were:
| per state | BAR | FEP forward | FEP reverse |
|---|---|---|---|
| 20 | , spread 0.0719 | , spread 0.0886 | , spread 0.1997 |
| 200 | , spread 0.0232 | , spread 0.0278 | , spread 0.0817 |
BAR has the smallest spread, and the forward FEP spread at matches its theory value . The reverse FEP has infinite variance here, and its spread is the worst.
Poor overlap. A unit well moved by , with exactly and 1000 samples of each state (seed 1): BAR gives , forward FEP gives 0.851, and reverse FEP gives . The two FEP estimates each lean on the rare tail of the other state; BAR needs only the region between the states, where both have some samples.
Unequal sample sizes. With 3000 samples of state 0 and 300 of state 1 in the harmonic case (seed 5), BAR gives .
Correctness
The proof in proofs/correctness.md shows:
- The acceptance ratio identity. For every weight function for which the averages exist, .
- The Bennett equation. With the weight the identity becomes the expected form of the equation above, which holds at the true .
- One root and a valid bracket. The sample equation has exactly one root, it lies in the bracket of line L2, and bisection converges to it.
- Least variance. Among all weights, the large-sample relative variance of the ratio estimate is smallest for the weight of Claim 2 (by the Cauchy-Schwarz inequality).
- Symmetry and exact cases. Swapping the states changes the sign of the estimate exactly, a constant difference gives exactly, and one sample of each state gives the mean of the two differences.
The estimator is consistent. Like FEP it is biased for finite samples, but its bias and variance are much smaller when the states overlap poorly.
Proof: The acceptance ratio identity, the Bennett equation, its unique root and the optimal weightfull
Let and be potentials on the same space with finite and positive, and . Write , on state-0 samples, on state-1 samples, and .
Claim 1 (the acceptance ratio identity). For every measurable with finite and positive,
Proof. Both averages are integrals of the same function , divided by in the numerator and by in the denominator. Let be that integral. Then the ratio is .
Claim 2 (the Bennett equation). Let and . Then
Proof. Take , which satisfies the condition of Claim 1 because is integrable and positive. Note . Then
because . In the same way
Claim 1 gives . Multiply both sides by and rearrange.
The algorithm replaces the two averages by sample means. By the law of large numbers the sample equation tends to the equation of Claim 2, and Claim 3 shows that both have one root, so the estimate is consistent when the right side of the limit equation is strictly monotone, which it is by the same argument.
Claim 3 (one root and a valid bracket). Let for finite samples. Then is continuous and strictly decreasing, as and as , so has exactly one root . If , the root lies in with and , and the bisection of lines L3 to L6 returns a point within tol of it.
Proof. is continuous and strictly decreasing, so each decreases and each increases in , and is strictly decreasing. The limits follow from as and as . So has exactly one zero.
At , every , so each , and every , so each . Hence when , which holds under the assumption. In the same way when . By the intermediate value theorem the root lies in . Lines L5 and L6 keep , so the root stays in , and the width halves at each step until it is below tol.
Claim 4 (least variance). Let be the ratio of the two sample means of Claim 1 with independent samples of state 0 and of state 1, and let . To first order in and (the delta method), the relative variance of is
Among all for which these integrals are finite, this is smallest when , which is the weight of Claim 2.
Proof. Write and with . The sample means and are independent with variances and , where and . The delta method gives
So the relative variance is with as in the statement. By the Cauchy-Schwarz inequality, , so the first term is at least , which does not depend on , with equality exactly when is proportional to , that is where . Multiplying by the constant shows , the weight of Claim 2.
The optimal weight contains the unknown , so the algorithm solves for it self-consistently: the root of Claim 3 is the value at which the estimate of Claim 1 with that weight returns the same ratio that was put in. To first order in the self-consistent estimator has the same variance as the estimator with the exact optimal weight (Bennett 1976); this note does not prove that step. Substituting the weight of Claim 2 into the variance formula gives the error bar of the page, which uses the sample variances of and .
Claim 5 (symmetry and exact cases). (a) Exchanging the states, which maps to , maps the estimate to . (b) If everywhere, the estimate is . (c) With , the estimate is .
Proof. (a) Let be the root for the original data, so . For the exchanged data the equation is , which satisfies; by Claim 3 it is the root. The new estimate is . (b) Then and , and the equation with reads , so and , which gives the estimate . (c) The equation holds if and only if because is injective, so and .
The example on the page with and is case (c): the estimate is .
Complexity
Each evaluation of the equation costs , and bisection on a bracket of width needs steps, about 45 for double precision on the brackets here. So BAR costs time with , which is negligible next to the cost of the samples. The extra space is beyond the input arrays. Newton's method needs fewer evaluations but must be safeguarded.
Properties
- Uses both states. It needs samples of both end states of each window and the energy of the other state on each sample.
- Least asymptotic variance among acceptance ratio estimators (a theorem), and it never needs an exponential of a large positive number: each weight lies in .
- Antisymmetric. Swapping the roles of the states gives exactly , unlike FEP.
- Shift by a constant. Adding a constant to adds exactly to the estimate.
- Maximum likelihood. The same equation is the maximum likelihood estimate of from the two sets of energy differences (Shirts and co-workers 2003), which also gives its variance.
- Asymptotically optimal, not exactly unbiased. For small samples it is biased, though much less than FEP when the overlap is poor.
Variants and improvements
- MBAR. For states with samples of each, MBAR (Shirts and Chodera 2008) solves coupled equations and uses all samples in every free energy; for two states it is BAR. Its histogram form for a coordinate is close to WHAM.
- Nonequilibrium BAR. With forward and reverse work values from switching runs instead of energy differences, the same equation gives through the Crooks relation (Shirts and co-workers 2003).
- Bridge sampling. In statistics, bridge sampling with the optimal bridge and its iterative scheme (Meng and Wong 1996) is the same estimator for ratios of normalizing constants.
- Staging. For a long path, BAR is applied to each pair of neighbouring windows and the results are added, as in staged FEP.
When to use it
Use BAR whenever samples of both end states of a window are available, which is the usual case for staged alchemical calculations: it costs nothing extra over FEP, gives a smaller error and is robust. Prefer MBAR when many windows are coupled. If BAR and both FEP directions agree within their error bars, the overlap is good; if BAR is far from both, or its error bar is large, add windows.
Pitfalls
- No overlap at all. If no sample of either state falls in the region that both states visit, BAR returns a number with a large error bar; it cannot invent the missing region.
- Wrong sign convention. is on the state-1 samples; mixing it up with gives a wrong root with no warning.
- Correlated samples. The error bar assumes independent samples; subsample the chain or use block averages.
- Forgetting the term for unequal sample sizes.
- Overflow in . Computing directly overflows for large ; use the two-branch form.
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/bennett-acceptance-ratio/. The authors are listed in prov/Y2JYEC.jsonl.
"""Bennett acceptance ratio (Bennett 1976).
Input: the reduced energy differences w_F = beta (U_1 - U_0) at n_0 samples of
state 0, and w_R = beta (U_0 - U_1) at n_1 samples of state 1. With the Fermi
function f(t) = 1 / (1 + e^t) and the shift C, the estimate solves
sum_j f(w_R[j] + C) = sum_i f(w_F[i] - C),
a single equation with exactly one root, because the left side decreases and
the right side increases in C. Then beta (A_1 - A_0) = C - ln(n_1 / n_0).
The root is found by bisection on a bracket, so the method always converges.
Cost: Theta(n_0 + n_1) per evaluation of the equation, and about 60 bisection
steps for full double precision on the bracket.
"""
import math
from typing import Sequence
def fermi(t: float) -> float:
"""f(t) = 1 / (1 + e^t), computed without overflow."""
if t > 0:
e = math.exp(-t)
return e / (1.0 + e)
return 1.0 / (1.0 + math.exp(t))
def bar_residual(wf: Sequence[float], wr: Sequence[float], c: float) -> float:
"""sum_j f(w_R[j] + C) - sum_i f(w_F[i] - C); it decreases strictly in C."""
return sum(fermi(w + c) for w in wr) - sum(fermi(w - c) for w in wf)
def bar(wf: Sequence[float], wr: Sequence[float], beta: float = 1.0,
tol: float = 1e-12) -> float:
"""Estimate A_1 - A_0 from reduced forward and reverse energy differences."""
n0, n1 = len(wf), len(wr)
if n0 == 0 or n1 == 0:
raise ValueError("BAR needs samples of both states")
m = math.log(n1 / n0) # @line L1
# The root lies between min(w_F) - 40 and max(-w_R) + 40 (see the proof).
lo = min(min(wf), min(-w for w in wr)) - 40.0 # @line L2
hi = max(max(wf), max(-w for w in wr)) + 40.0 # @line L2
while hi - lo > tol * max(1.0, abs(lo), abs(hi)): # @line L3
mid = 0.5 * (lo + hi) # @line L4
if bar_residual(wf, wr, mid) > 0: # @line L5
lo = mid # @line L5
else:
hi = mid # @line L6
c = 0.5 * (lo + hi)
return (c - m) / beta # @line L7
def bar_error(wf: Sequence[float], wr: Sequence[float], beta: float, da: float) -> float:
"""Large-sample standard error of the BAR estimate da, for independent samples.
For any fixed C, beta dA = C + ln E_1[f(w_R + C)] - ln E_0[f(w_F - C)]; at the
root C the error adds the relative variances of the two independent means.
"""
n0, n1 = len(wf), len(wr)
c = beta * da + math.log(n1 / n0)
a = [fermi(w - c) for w in wf]
b = [fermi(w + c) for w in wr]
var = 0.0
for v in (a, b):
n = len(v)
mean = sum(v) / n
var += sum((x - mean) ** 2 for x in v) / (n - 1) / (n * mean * mean)
return math.sqrt(var) / beta
def fep_forward(wf: Sequence[float], beta: float = 1.0) -> float:
"""Exponential averaging from state 0 only, for comparison."""
m = min(wf)
s = sum(math.exp(-(w - m)) for w in wf)
return (m - math.log(s / len(wf))) / beta
def fep_reverse(wr: Sequence[float], beta: float = 1.0) -> float:
"""Exponential averaging from state 1 only, for comparison."""
return -fep_forward(wr, beta)
test_bennett_acceptance_ratio.py 131 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bennett-acceptance-ratio/. The authors are listed in prov/Y2JYEC.jsonl.
import math
import random
import pytest
from bennett_acceptance_ratio import (
bar,
bar_error,
bar_residual,
fep_forward,
fep_reverse,
fermi,
)
EXACT = 0.5 * math.log(2.0) # U_0 = x^2 / 2, U_1 = x^2, kT = 1
def harmonic(n0, n1, rng):
wf = [0.5 * rng.gauss(0.0, 1.0) ** 2 for _ in range(n0)]
wr = [-0.5 * rng.gauss(0.0, math.sqrt(0.5)) ** 2 for _ in range(n1)]
return wf, wr
def test_fermi_function():
assert fermi(0.0) == 0.5
assert fermi(800.0) == pytest.approx(0.0, abs=1e-300)
assert fermi(-800.0) == 1.0
assert fermi(1.3) + fermi(-1.3) == pytest.approx(1.0, abs=1e-15)
def test_one_sample_in_each_state_gives_the_mean_of_the_two_differences():
# U_1 - U_0 is 1.0 at the state-0 sample and 0.2 at the state-1 sample.
assert bar([1.0], [-0.2]) == pytest.approx(0.6, abs=1e-9)
def test_constant_difference_is_exact():
assert bar([1.7] * 5, [-1.7] * 3) == pytest.approx(1.7, abs=1e-9)
def test_swapping_the_states_changes_the_sign():
wf, wr = harmonic(50, 70, random.Random(7))
assert bar(wr, wf) == pytest.approx(-bar(wf, wr), abs=1e-9)
def test_root_solves_the_bennett_equation_and_residual_is_monotone():
wf, wr = harmonic(40, 60, random.Random(8))
da = bar(wf, wr)
c = da + math.log(60 / 40)
assert abs(bar_residual(wf, wr, c)) < 1e-7
cs = [-5 + 0.5 * i for i in range(21)]
rs = [bar_residual(wf, wr, x) for x in cs]
assert all(a > b for a, b in zip(rs, rs[1:]))
def test_harmonic_wells_against_exact_value():
wf, wr = harmonic(1000, 1000, random.Random(1))
da = bar(wf, wr)
se = bar_error(wf, wr, 1.0, da)
assert abs(da - EXACT) < 4 * se
assert se < 0.012
def test_unequal_sample_sizes():
wf, wr = harmonic(3000, 300, random.Random(5))
da = bar(wf, wr)
assert abs(da - EXACT) < 4 * bar_error(wf, wr, 1.0, da)
def test_temperature_scaling():
kT = 2.5
beta = 1.0 / kT
rng = random.Random(9)
# reduced differences beta * (U_1 - U_0) do not depend on kT for these wells
xs0 = [rng.gauss(0.0, math.sqrt(kT)) for _ in range(800)]
xs1 = [rng.gauss(0.0, math.sqrt(kT / 2)) for _ in range(800)]
wf = [beta * 0.5 * x * x for x in xs0]
wr = [-beta * 0.5 * x * x for x in xs1]
da = bar(wf, wr, beta)
assert abs(da - kT * EXACT) < 4 * bar_error(wf, wr, beta, da)
def test_lower_spread_than_either_one_sided_estimate():
rng = random.Random(4)
b, f, r = [], [], []
for _ in range(200):
wf, wr = harmonic(50, 50, rng)
b.append(bar(wf, wr))
f.append(fep_forward(wf))
r.append(fep_reverse(wr))
def sd(v):
m = sum(v) / len(v)
return math.sqrt(sum((x - m) ** 2 for x in v) / (len(v) - 1))
assert sd(b) < sd(f) < sd(r)
assert abs(sum(b) / len(b) - EXACT) < 4 * sd(b) / math.sqrt(len(b))
def test_error_formula_matches_spread_over_replicas():
rng = random.Random(6)
vals, ses = [], []
for _ in range(150):
wf, wr = harmonic(200, 200, rng)
da = bar(wf, wr)
vals.append(da)
ses.append(bar_error(wf, wr, 1.0, da))
m = sum(vals) / len(vals)
sd = math.sqrt(sum((x - m) ** 2 for x in vals) / (len(vals) - 1))
assert sum(ses) / len(ses) == pytest.approx(sd, rel=0.25)
def test_poor_overlap_bar_stays_near_truth_while_forward_fep_fails():
# Shift a unit well by a = 3; the exact answer is 0.
a = 3.0
rng = random.Random(1)
x0 = [rng.gauss(0.0, 1.0) for _ in range(1000)]
x1 = [a + rng.gauss(0.0, 1.0) for _ in range(1000)]
wf = [0.5 * (x - a) ** 2 - 0.5 * x * x for x in x0]
wr = [0.5 * x * x - 0.5 * (x - a) ** 2 for x in x1]
da = bar(wf, wr)
assert abs(da) < 4 * bar_error(wf, wr, 1.0, da)
assert fep_forward(wf) > 0.5
def test_empty_input_raises():
with pytest.raises(ValueError):
bar([], [1.0])
with pytest.raises(ValueError):
bar([1.0], [])
History
Bennett (1976) asked how to best combine Monte Carlo data from two states to estimate the ratio of their partition functions. He wrote an identity that holds for every weight function, found the weight of least variance, and obtained the equation with the Fermi function; the name comes from the Metropolis acceptance probability that appears in a special case. Meng and Wong (1996) found the same estimator in statistics as the optimal bridge sampler. Shirts, Bair, Hooker and Pande (2003) showed it is a maximum likelihood estimate and extended it to nonequilibrium work, and Shirts and Chodera (2008) generalized it to many states as MBAR.
References
- Charles H. Bennett, Efficient estimation of free energy differences from Monte Carlo data, Journal of Computational Physics 22(2), 1976, 245-268, the acceptance ratio identity for an arbitrary weight function, the optimal weight and the self-consistent equation with the Fermi function
- Michael R. Shirts, Eric Bair, Giles Hooker and Vijay S. Pande, Equilibrium free energies from nonequilibrium measurements using maximum-likelihood methods, Physical Review Letters 91, 140601, 2003, the derivation of the BAR equation as a maximum likelihood estimate from the forward and reverse work and its variance
- Michael R. Shirts and John D. Chodera, Statistically optimal analysis of samples from multiple equilibrium states, Journal of Chemical Physics 129, 124105, 2008, the multistate generalization (MBAR) that reduces to BAR for two states
- 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 treatment of the Bennett acceptance ratio among the free energy perturbation methods
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 Y2JYEC Edit this page History Report an error Markdown