Algorithm Search⌘K

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
Properties
consistentdeterministiciterativenot randomizednot unbiased
Origin
Charles H. Bennett, 1976

The Bennett acceptance ratio (BAR) estimates the free energy difference ΔA=A1−A0\Delta A = A_1 - A_0 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 ΔA\Delta A 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 n0n_0 samples xix_i of the canonical ensemble of state 0 and n1n_1 samples yjy_j of state 1, the energies U0U_0 and U1U_1 on both sets, and β=1/(kBT)\beta = 1/(k_B T). Write the reduced differences

wF,i=β (U1(xi)−U0(xi)),wR,j=β (U0(yj)−U1(yj)),w_{F,i} = \beta\,(U_1(x_i) - U_0(x_i)), \qquad w_{R,j} = \beta\,(U_0(y_j) - U_1(y_j)),

and the Fermi function f(t)=1/(1+et)f(t) = 1 / (1 + e^t). The output is the root CC of

∑j=1n1f(wR,j+C)=∑i=1n0f(wF,i−C),βΔA^=C−ln⁡(n1/n0),\sum_{j=1}^{n_1} f(w_{R,j} + C) = \sum_{i=1}^{n_0} f(w_{F,i} - C), \qquad \beta \widehat{\Delta A} = C - \ln(n_1 / n_0),

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

  1. BAR(w_F[1..n_0], w_R[1..n_1], beta) ▷ f(t) = 1 / (1 + e^t)
  2. 1M ← ln(n_1 / n_0)
  3. 2lo ← 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
  4. 3while hi - lo > tol do
  5. 4C ← (lo + hi) / 2
  6. 5if sum_j f(w_R[j] + C) > sum_i f(w_F[i] - C) then lo ← C
  7. 6else hi ← C
  8. 7return ((lo + hi) / 2 - M) / beta

The left side of the equation decreases strictly in CC and the right side increases strictly, so their difference has exactly one sign change, and lines L3 to L6 keep the root inside [lo,hi][lo, hi]. The bracket of line L2 holds whenever n0/n1n_0 / n_1 and n1/n0n_1 / n_0 are below e40−1e^{40} - 1 (Claim 3). The function ff is computed as e−t/(1+e−t)e^{-t}/(1 + e^{-t}) for t>0t > 0, so it never overflows. Each test of line L5 costs O(n0+n1)O(n_0 + n_1). A Newton step on the same equation converges faster, but bisection cannot fail.

The error bar is the delta-method error at the root,

σβΔA2≈var f(wF−C)n0 f(wF−C)‾2+var f(wR+C)n1 f(wR+C)‾2,\sigma^2_{\beta \Delta A} \approx \frac{\mathrm{var}\, f(w_F - C)}{n_0\, \overline{f(w_F - C)}^2} + \frac{\mathrm{var}\, f(w_R + C)}{n_1\, \overline{f(w_R + C)}^2},

for independent samples. It is a large-sample estimate.

Example

By hand. One sample of each state, with U1−U0=1.0U_1 - U_0 = 1.0 at the state-0 sample and 0.20.2 at the state-1 sample, at β=1\beta = 1. Then wF=1.0w_F = 1.0, wR=−0.2w_R = -0.2, M=0M = 0, and the equation f(−0.2+C)=f(1.0−C)f(-0.2 + C) = f(1.0 - C) holds when −0.2+C=1.0−C-0.2 + C = 1.0 - C, so C=0.6C = 0.6 and ΔA=0.6\Delta A = 0.6: 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. U0=x2/2U_0 = x^2/2 and U1=x2U_1 = x^2 at kBT=1k_B T = 1, so ΔA=12ln⁡2=0.346574\Delta A = \frac12 \ln 2 = 0.346574. With NN exact samples of each state (seed 1):

NN 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:

NN per state BAR FEP forward FEP reverse
20 −0.0019-0.0019, spread 0.0719 −0.0030-0.0030, spread 0.0886 −0.0039-0.0039, spread 0.1997
200 −0.0024-0.0024, spread 0.0232 −0.0028-0.0028, spread 0.0278 −0.0034-0.0034, spread 0.0817

BAR has the smallest spread, and the forward FEP spread at N=200N = 200 matches its theory value 0.1547/200=0.0278\sqrt{0.1547/200} = 0.0278. The reverse FEP has infinite variance here, and its spread is the worst.

Poor overlap. A unit well moved by a=3a = 3, with ΔA=0\Delta A = 0 exactly and 1000 samples of each state (seed 1): BAR gives −0.039±0.091-0.039 \pm 0.091, forward FEP gives 0.851, and reverse FEP gives −0.301-0.301. 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 0.3381±0.00680.3381 \pm 0.0068.

Correctness

The proof in proofs/correctness.md shows:

  1. The acceptance ratio identity. For every weight function WW for which the averages exist, Z1/Z0=⟨We−βU1⟩0/⟨We−βU0⟩1Z_1 / Z_0 = \langle W e^{-\beta U_1} \rangle_0 / \langle W e^{-\beta U_0} \rangle_1.
  2. The Bennett equation. With the weight W∝1/(n0e−βU0+n1eβΔAe−βU1)W \propto 1/(n_0 e^{-\beta U_0} + n_1 e^{\beta \Delta A} e^{-\beta U_1}) the identity becomes the expected form of the equation above, which holds at the true C=βΔA+ln⁡(n1/n0)C = \beta \Delta A + \ln(n_1 / n_0).
  3. 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.
  4. 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).
  5. Symmetry and exact cases. Swapping the states changes the sign of the estimate exactly, a constant difference U1−U0=cU_1 - U_0 = c gives cc 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 U0U_0 and U1U_1 be potentials on the same space with Zk=∫e−βUk(x) dxZ_k = \int e^{-\beta U_k(x)}\,dx finite and positive, Ak=−β−1ln⁡ZkA_k = -\beta^{-1} \ln Z_k and ΔA=A1−A0\Delta A = A_1 - A_0. Write ⟨g⟩k=Zk−1∫g e−βUk dx\langle g \rangle_k = Z_k^{-1} \int g\, e^{-\beta U_k}\,dx, wF=β(U1−U0)w_F = \beta(U_1 - U_0) on state-0 samples, wR=β(U0−U1)w_R = \beta(U_0 - U_1) on state-1 samples, and f(t)=1/(1+et)f(t) = 1/(1 + e^t).

Claim 1 (the acceptance ratio identity). For every measurable W>0W > 0 with ∫We−βU0e−βU1 dx\int W e^{-\beta U_0} e^{-\beta U_1}\,dx finite and positive,

Z1Z0=⟨We−βU1⟩0⟨We−βU0⟩1.\frac{Z_1}{Z_0} = \frac{\langle W e^{-\beta U_1} \rangle_0}{\langle W e^{-\beta U_0} \rangle_1}.

Proof. Both averages are integrals of the same function We−βU0e−βU1W e^{-\beta U_0} e^{-\beta U_1}, divided by Z0Z_0 in the numerator and by Z1Z_1 in the denominator. Let II be that integral. Then the ratio is (I/Z0)/(I/Z1)=Z1/Z0(I / Z_0) / (I / Z_1) = Z_1 / Z_0. □\square

Claim 2 (the Bennett equation). Let n0,n1>0n_0, n_1 > 0 and C∗=βΔA+ln⁡(n1/n0)C^* = \beta \Delta A + \ln(n_1 / n_0). Then

n1⟨f(wR+C∗)⟩1=n0⟨f(wF−C∗)⟩0.n_1 \langle f(w_R + C^*) \rangle_1 = n_0 \langle f(w_F - C^*) \rangle_0.

Proof. Take W=1/(n0e−βU0+n1(Z0/Z1)e−βU1)W = 1 / (n_0 e^{-\beta U_0} + n_1 (Z_0 / Z_1) e^{-\beta U_1}), which satisfies the condition of Claim 1 because We−βU0e−βU1≤e−βU0/(n1Z0/Z1)W e^{-\beta U_0} e^{-\beta U_1} \le e^{-\beta U_0} / (n_1 Z_0 / Z_1) is integrable and positive. Note Z0/Z1=eβΔAZ_0 / Z_1 = e^{\beta \Delta A}. Then

We−βU1=1n0eβ(U1−U0)+n1eβΔA=1n1eβΔA f(wF−C∗),W e^{-\beta U_1} = \frac{1}{n_0 e^{\beta (U_1 - U_0)} + n_1 e^{\beta \Delta A}} = \frac{1}{n_1 e^{\beta \Delta A}}\, f(w_F - C^*),

because n0ewF/(n1eβΔA)=ewF−C∗n_0 e^{w_F} / (n_1 e^{\beta \Delta A}) = e^{w_F - C^*}. In the same way

We−βU0=1n0+n1eβΔAeβ(U0−U1)=1n0 f(wR+C∗).W e^{-\beta U_0} = \frac{1}{n_0 + n_1 e^{\beta \Delta A} e^{\beta(U_0 - U_1)}} = \frac{1}{n_0}\, f(w_R + C^*).

Claim 1 gives e−βΔA=⟨We−βU1⟩0/⟨We−βU0⟩1=n0⟨f(wF−C∗)⟩0/(n1eβΔA⟨f(wR+C∗)⟩1)e^{-\beta \Delta A} = \langle W e^{-\beta U_1} \rangle_0 / \langle W e^{-\beta U_0} \rangle_1 = n_0 \langle f(w_F - C^*) \rangle_0 / (n_1 e^{\beta \Delta A} \langle f(w_R + C^*) \rangle_1). Multiply both sides by eβΔAe^{\beta \Delta A} and rearrange. □\square

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 R(C)=∑j=1n1f(wR,j+C)−∑i=1n0f(wF,i−C)R(C) = \sum_{j=1}^{n_1} f(w_{R,j} + C) - \sum_{i=1}^{n_0} f(w_{F,i} - C) for finite samples. Then RR is continuous and strictly decreasing, R(C)→n1R(C) \to n_1 as C→−∞C \to -\infty and R(C)→−n0R(C) \to -n_0 as C→+∞C \to +\infty, so RR has exactly one root CC. If max⁡(n0,n1)/min⁡(n0,n1)<e40−1\max(n_0, n_1) / \min(n_0, n_1) < e^{40} - 1, the root lies in [lo,hi][lo, hi] with lo=min⁡(min⁡iwF,i,min⁡j(−wR,j))−40lo = \min(\min_i w_{F,i}, \min_j (-w_{R,j})) - 40 and hi=max⁡(max⁡iwF,i,max⁡j(−wR,j))+40hi = \max(\max_i w_{F,i}, \max_j (-w_{R,j})) + 40, and the bisection of lines L3 to L6 returns a point within tol of it.

Proof. ff is continuous and strictly decreasing, so each f(wR+C)f(w_R + C) decreases and each f(wF−C)f(w_F - C) increases in CC, and RR is strictly decreasing. The limits follow from f(t)→1f(t) \to 1 as t→−∞t \to -\infty and f(t)→0f(t) \to 0 as t→+∞t \to +\infty. So RR has exactly one zero.

At C=loC = lo, every wR,j+lo≤wR,j−wR,j−40=−40w_{R,j} + lo \le w_{R,j} - w_{R,j} - 40 = -40, so each f(wR,j+lo)≥1/(1+e−40)f(w_{R,j} + lo) \ge 1 / (1 + e^{-40}), and every wF,i−lo≥40w_{F,i} - lo \ge 40, so each f(wF,i−lo)≤e−40f(w_{F,i} - lo) \le e^{-40}. Hence R(lo)≥n1/(1+e−40)−n0e−40>0R(lo) \ge n_1 / (1 + e^{-40}) - n_0 e^{-40} > 0 when n0/n1<e40/(1+e−40)n_0 / n_1 < e^{40} / (1 + e^{-40}), which holds under the assumption. In the same way R(hi)≤n1e−40−n0/(1+e−40)<0R(hi) \le n_1 e^{-40} - n_0 / (1 + e^{-40}) < 0 when n1/n0<e40/(1+e−40)n_1 / n_0 < e^{40} / (1 + e^{-40}). By the intermediate value theorem the root lies in (lo,hi)(lo, hi). Lines L5 and L6 keep R(lo)>0≥R(hi)R(lo) > 0 \ge R(hi), so the root stays in [lo,hi][lo, hi], and the width halves at each step until it is below tol. □\square

Claim 4 (least variance). Let Z^\hat Z be the ratio of the two sample means of Claim 1 with n0n_0 independent samples of state 0 and n1n_1 of state 1, and let ϕ=e−βU0e−βU1\phi = e^{-\beta U_0} e^{-\beta U_1}. To first order in 1/n01 / n_0 and 1/n11 / n_1 (the delta method), the relative variance of Z^\hat Z is

var Z^(Z1/Z0)2=∫W2ϕ D dx(∫Wϕ dx)2−1n0−1n1,D=Z0e−βU1n0+Z1e−βU0n1.\frac{\mathrm{var}\,\hat Z}{(Z_1 / Z_0)^2} = \frac{\int W^2 \phi\, D\,dx}{\bigl(\int W \phi\,dx\bigr)^2} - \frac{1}{n_0} - \frac{1}{n_1}, \qquad D = \frac{Z_0 e^{-\beta U_1}}{n_0} + \frac{Z_1 e^{-\beta U_0}}{n_1}.

Among all WW for which these integrals are finite, this is smallest when W∝1/DW \propto 1 / D, which is the weight of Claim 2.

Proof. Write a=⟨We−βU1⟩0=I/Z0a = \langle W e^{-\beta U_1} \rangle_0 = I / Z_0 and b=⟨We−βU0⟩1=I/Z1b = \langle W e^{-\beta U_0} \rangle_1 = I / Z_1 with I=∫WϕI = \int W \phi. The sample means a^\hat a and b^\hat b are independent with variances σa2/n0\sigma_a^2 / n_0 and σb2/n1\sigma_b^2 / n_1, where σa2+a2=⟨W2e−2βU1⟩0=Z0−1∫W2ϕ e−βU1\sigma_a^2 + a^2 = \langle W^2 e^{-2\beta U_1} \rangle_0 = Z_0^{-1} \int W^2 \phi\, e^{-\beta U_1} and σb2+b2=Z1−1∫W2ϕ e−βU0\sigma_b^2 + b^2 = Z_1^{-1} \int W^2 \phi\, e^{-\beta U_0}. The delta method gives

var(a^/b^)(a/b)2≈σa2n0a2+σb2n1b2=Z0∫W2ϕ e−βU1n0I2+Z1∫W2ϕ e−βU0n1I2−1n0−1n1.\frac{\mathrm{var}(\hat a / \hat b)}{(a / b)^2} \approx \frac{\sigma_a^2}{n_0 a^2} + \frac{\sigma_b^2}{n_1 b^2} = \frac{Z_0 \int W^2 \phi\, e^{-\beta U_1}}{n_0 I^2} + \frac{Z_1 \int W^2 \phi\, e^{-\beta U_0}}{n_1 I^2} - \frac{1}{n_0} - \frac{1}{n_1}.

So the relative variance is ∫W2ϕ D/(∫Wϕ)2−1/n0−1/n1\int W^2 \phi\, D / (\int W \phi)^2 - 1/n_0 - 1/n_1 with D>0D > 0 as in the statement. By the Cauchy-Schwarz inequality, (∫Wϕ)2=(∫(WϕD)ϕ/D)2≤∫W2ϕD⋅∫ϕ/D(\int W \phi)^2 = (\int (W \sqrt{\phi D}) \sqrt{\phi / D})^2 \le \int W^2 \phi D \cdot \int \phi / D, so the first term is at least 1/∫(ϕ/D)1 / \int (\phi / D), which does not depend on WW, with equality exactly when WϕDW \sqrt{\phi D} is proportional to ϕ/D\sqrt{\phi / D}, that is W∝1/DW \propto 1 / D where ϕ>0\phi > 0. Multiplying DD by the constant n0n1/Z1n_0 n_1 / Z_1 shows 1/D∝1/(n0e−βU0+n1(Z0/Z1)e−βU1)1 / D \propto 1 / (n_0 e^{-\beta U_0} + n_1 (Z_0 / Z_1) e^{-\beta U_1}), the weight of Claim 2. □\square

The optimal weight contains the unknown Z0/Z1Z_0 / Z_1, 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 1/n1/n 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 f(wF−C)f(w_F - C) and f(wR+C)f(w_R + C).

Claim 5 (symmetry and exact cases). (a) Exchanging the states, which maps (wF,wR,n0,n1)(w_F, w_R, n_0, n_1) to (wR,wF,n1,n0)(w_R, w_F, n_1, n_0), maps the estimate ΔA^\widehat{\Delta A} to −ΔA^-\widehat{\Delta A}. (b) If U1−U0=cU_1 - U_0 = c everywhere, the estimate is cc. (c) With n0=n1=1n_0 = n_1 = 1, the estimate is (wF−wR)/(2β)(w_F - w_R) / (2\beta).

Proof. (a) Let CC be the root for the original data, so ∑jf(wR,j+C)=∑if(wF,i−C)\sum_j f(w_{R,j} + C) = \sum_i f(w_{F,i} - C). For the exchanged data the equation is ∑if(wF,i+C′)=∑jf(wR,j−C′)\sum_i f(w_{F,i} + C') = \sum_j f(w_{R,j} - C'), which C′=−CC' = -C satisfies; by Claim 3 it is the root. The new estimate is (C′−ln⁡(n0/n1))/β=−(C−ln⁡(n1/n0))/β(C' - \ln(n_0 / n_1)) / \beta = -(C - \ln(n_1 / n_0)) / \beta. (b) Then wF=βcw_F = \beta c and wR=−βcw_R = -\beta c, and the equation n1f(C−βc)=n0f(βc−C)n_1 f(C - \beta c) = n_0 f(\beta c - C) with t=C−βct = C - \beta c reads n1/(1+et)=n0/(1+e−t)=n0et/(1+et)n_1 / (1 + e^t) = n_0 / (1 + e^{-t}) = n_0 e^t / (1 + e^t), so et=n1/n0e^t = n_1 / n_0 and C=βc+ln⁡(n1/n0)C = \beta c + \ln(n_1 / n_0), which gives the estimate cc. (c) The equation f(wR+C)=f(wF−C)f(w_R + C) = f(w_F - C) holds if and only if wR+C=wF−Cw_R + C = w_F - C because ff is injective, so C=(wF−wR)/2C = (w_F - w_R)/2 and M=0M = 0. □\square

The example on the page with wF=1.0w_F = 1.0 and wR=−0.2w_R = -0.2 is case (c): the estimate is 0.60.6.

Complexity

Each evaluation of the equation costs O(n0+n1)O(n_0 + n_1), and bisection on a bracket of width LL needs ⌈log⁡2(L/tol)⌉\lceil \log_2(L / \mathrm{tol}) \rceil steps, about 45 for double precision on the brackets here. So BAR costs O(b n)O(b\, n) time with b≈50b \approx 50, which is negligible next to the cost of the samples. The extra space is O(1)O(1) 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 (0,1)(0, 1).
  • Antisymmetric. Swapping the roles of the states gives exactly −ΔA^-\widehat{\Delta A}, unlike FEP.
  • Shift by a constant. Adding a constant cc to U1U_1 adds exactly cc to the estimate.
  • Maximum likelihood. The same equation is the maximum likelihood estimate of ΔA\Delta A 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 KK states with samples of each, MBAR (Shirts and Chodera 2008) solves KK 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 ΔA\Delta A 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. wRw_R is β(U0−U1)\beta(U_0 - U_1) on the state-1 samples; mixing it up with β(U1−U0)\beta(U_1 - U_0) gives a wrong root with no warning.
  • Correlated samples. The error bar assumes independent samples; subsample the chain or use block averages.
  • Forgetting the ln⁡(n1/n0)\ln(n_1 / n_0) term for unequal sample sizes.
  • Overflow in ff. Computing 1/(1+et)1/(1 + e^t) directly overflows for large tt; 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.

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

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

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