Algorithm Search⌘K

Algorithmcore

Free energy perturbation

Also called Zwanzig formula.

Estimates the free energy difference of two states as -kT log of the average of exp(-dU/kT) over samples of one state.

Time
O(K N) worst
Space
O(N) extra
Where
K = the number of windows; N = the number of samples per window
Properties
consistentrandomizednot iterativerandomizednot unbiased
Origin
Robert W. Zwanzig, 1954

Free energy perturbation (FEP) estimates the free energy difference ΔA=A1−A0\Delta A = A_1 - A_0 of two states with potential energies U0U_0 and U1U_1 from samples of state 0 alone. It uses the exact identity of Zwanzig (1954), ΔA=−kBTln⁡⟨e−β(U1−U0)⟩0\Delta A = -k_B T \ln \langle e^{-\beta (U_1 - U_0)} \rangle_0 with β=1/(kBT)\beta = 1/(k_B T), and replaces the canonical average by a sample mean. It is importance sampling of the ratio of partition functions Z1/Z0Z_1 / Z_0, with state 0 as the proposal. FEP, thermodynamic integration, the Bennett acceptance ratio and the Jarzynski equality form one family: FEP uses one end state, BAR uses both, TI uses many states between them, and Jarzynski uses nonequilibrium paths. The estimate is exact in the limit of many samples, biased for a finite number, and useless when the two states share few configurations.

In plain words

You know how a system behaves in one state and want to know how much more or less favourable a second state is. Free energy perturbation takes snapshots of the first state and asks, for each snapshot, how much the energy would change in the second state. It then takes a special kind of average of these changes.

The average gives most weight to the snapshots where the second state is most favourable. If such snapshots are rare in the first state, the average depends on a few lucky ones, and the answer is poor even with many snapshots. The cure is to go in small steps: a chain of states between the two ends, each close to the next, and one small calculation for each pair.

The problem

The input is a sampler for the canonical ensemble of state 0, the two potential energy functions U0U_0 and U1U_1 on the same configuration space, and β\beta. The output is an estimate of

ΔA=A1−A0=−1βln⁡Z1Z0,Zj=∫e−βUj(x) dx,\Delta A = A_1 - A_0 = -\frac{1}{\beta} \ln \frac{Z_1}{Z_0}, \qquad Z_j = \int e^{-\beta U_j(x)}\, dx,

with Aj=−kBTln⁡ZjA_j = -k_B T \ln Z_j. The identity behind the method (a theorem, Claim 1 of the proof) is

ΔA=−1βln⁡⟨e−βΔU⟩0,ΔU=U1−U0.\Delta A = -\frac{1}{\beta} \ln \bigl\langle e^{-\beta \Delta U} \bigr\rangle_0, \qquad \Delta U = U_1 - U_0.

It needs that every configuration with e−βU1>0e^{-\beta U_1} > 0 also has e−βU0>0e^{-\beta U_0} > 0. For a long path the states are joined by a family UλU_\lambda with λ∈[0,1]\lambda \in [0, 1], and the staged form uses the windows 0=λ0<λ1<⋯<λK=10 = \lambda_0 < \lambda_1 < \dots < \lambda_K = 1.

The algorithm

  1. FEP(x_1, ..., x_N samples of state 0, U_0, U_1, beta)
  2. 1d_i ← U_1(x_i) - U_0(x_i) for each i
  3. 2m ← min_i d_i ▷ shift so that no exponential overflows
  4. 3s ← sum_i exp(-beta (d_i - m))
  5. 4return m - (1 / beta) ln(s / N)
  6. STAGED-FEP(lambda_0 = 0 < lambda_1 < ... < lambda_K = 1, SAMPLE, U, beta, N)
  7. 5dA ← 0
  8. 6for k ← 0 to K - 1 do
  9. 7draw N samples x_i of the state lambda_k with SAMPLE
  10. 8dA ← dA + FEP(x, U_{lambda_k}, U_{lambda_{k+1}}, beta)
  11. 9return dA

Line L4 equals −β−1ln⁡(N−1∑ie−βdi)-\beta^{-1} \ln \bigl( N^{-1} \sum_i e^{-\beta d_i} \bigr), and the shift by mm makes every exponent at most 0 with one of them equal to 0. The windows of STAGED-FEP are independent, so the errors of the windows add in quadrature. The error bar of one window is the delta-method error sd(w)/(βN w‾)\mathrm{sd}(w) / (\beta \sqrt{N}\, \overline{w}) with wi=e−β(di−m)w_i = e^{-\beta (d_i - m)}; it assumes independent samples and a finite variance of ww. For a correlated chain, use block averages instead.

Example

By hand. Three samples of state 0 have βΔU=0,1,2\beta \Delta U = 0, 1, 2, in units of kBTk_B T. Then m=0m = 0, s=1+e−1+e−2=1.503215s = 1 + e^{-1} + e^{-2} = 1.503215 and

βΔA≈−ln⁡(1.503215/3)=0.691006.\beta \Delta A \approx -\ln(1.503215 / 3) = 0.691006.

The plain mean of βΔU\beta \Delta U is 1. The FEP estimate is always at most the plain mean (Jensen's inequality), and here the sample with βΔU=0\beta \Delta U = 0 carries more than half of the weight.

Harmonic wells, both directions. Let U0=x2/2U_0 = x^2/2 and U1=x2U_1 = x^2 in one dimension at kBT=1k_B T = 1, so k0=1k_0 = 1, k1=2k_1 = 2 and ΔA=12ln⁡(k1/k0)=0.346574\Delta A = \frac{1}{2} \ln(k_1 / k_0) = 0.346574 exactly. The forward estimate samples the wide well (x∼N(0,1)x \sim N(0, 1)) and the reverse estimate samples the narrow well (x∼N(0,1/2)x \sim N(0, 1/2)) and returns −FEP-\mathrm{FEP} of the opposite difference:

NN forward (seed 1) forward error bar reverse (seed 2)
10 0.3565 0.1249 0.3808
100 0.3100 0.0369 0.5622
1000 0.3536 0.0125 0.3496
10000 0.3441 0.0039 0.3424

The forward direction has E[w]=1/2E[w] = 1/\sqrt{2} and E[w2]=1/3E[w^2] = 1/\sqrt{3}, so the large-NN variance of the estimate is 0.1547/N0.1547 / N (a theorem, Claim 5), and the error bars match it. The reverse direction has E[w2]=∞E[w^2] = \infty: the weight ex2/2e^{x^2/2} is not square integrable under N(0,1/2)N(0, 1/2). Its estimate still converges, but there is no valid error bar and the error falls more slowly than 1/N1/\sqrt{N}.

Bias. Over 4000 independent runs of N=5N = 5 forward samples, the mean of the estimate is ΔA+0.0190±0.0031\Delta A + 0.0190 \pm 0.0031, close to the first-order bias var(w)/(2NβE[w]2)=0.0155\mathrm{var}(w) / (2 N \beta E[w]^2) = 0.0155. With N=2N = 2 the bias is 0.0591 (first order 0.0387), and with N=20N = 20 it is 0.0040 (first order 0.0039). The bias is always upward (Claim 4).

Staging a poor overlap. Move a unit well by a=3a = 3: Uλ=(x−3λ)2/2U_\lambda = (x - 3\lambda)^2 / 2. The free energy does not change, so ΔA=0\Delta A = 0. With 1200 samples in total, split over KK equal windows:

KK estimate (seed 1) error bar spread over replicas theory spread
1 0.7975 0.1853 0.5033 2.598
2 0.1844 0.1175 0.156 0.168
3 0.0877 0.0992 0.110 0.114
6 0.0370 0.0888 0.089 0.092
12 0.0308 0.0860 0.085 0.088

The theory variance is K2(ea2/K2−1)/1200K^2 (e^{a^2/K^2} - 1) / 1200 (Claim 7). With one window it is huge, but the estimate does not show it: the error bar of 0.185 says the answer is 0.80±0.190.80 \pm 0.19, more than four error bars from the truth, and the spread over replicas, 0.50, is far below the theory value, because the samples that would raise it almost never occur. With six windows the error bar, the spread and the theory agree.

Correctness

The proof in proofs/correctness.md shows:

  1. The Zwanzig identity Z1/Z0=⟨e−βΔU⟩0Z_1 / Z_0 = \langle e^{-\beta \Delta U} \rangle_0 holds whenever the support of state 1 lies inside the support of state 0.
  2. The shift on lines L2 to L4 does not change the value and keeps every exponential in (0,1](0, 1].
  3. Consistency. For independent samples, or an ergodic chain, the estimate converges to ΔA\Delta A with probability 1.
  4. Bounds and bias. The estimate lies between min⁡iΔUi\min_i \Delta U_i and the mean of ΔUi\Delta U_i, and its expected value is at least ΔA\Delta A for every NN.
  5. Error. If E[w2]<∞E[w^2] < \infty, then N(ΔA^−ΔA)\sqrt{N}(\widehat{\Delta A} - \Delta A) tends to a normal law with variance var(w)/(β2E[w]2)\mathrm{var}(w) / (\beta^2 E[w]^2), and the first-order bias is var(w)/(2NβE[w]2)\mathrm{var}(w) / (2 N \beta E[w]^2).
  6. Staging. The window identities add up to the identity for the whole path.
  7. The two examples: the exact moments for the harmonic wells and the variance K2(ea2/K2−1)/NK^2(e^{a^2/K^2} - 1)/N for the shifted well.
Proof: The Zwanzig identity, and the bias, consistency and error of the exponential averagefull

Let ρ0(x)=e−βU0(x)/Z0\rho_0(x) = e^{-\beta U_0(x)} / Z_0 be the canonical density of state 0, with Zj=∫e−βUj(x) dxZ_j = \int e^{-\beta U_j(x)}\,dx finite and positive for j=0,1j = 0, 1. Write ΔU=U1−U0\Delta U = U_1 - U_0, w(x)=e−βΔU(x)w(x) = e^{-\beta \Delta U(x)} and ΔA=−β−1ln⁡(Z1/Z0)\Delta A = -\beta^{-1} \ln(Z_1 / Z_0).

Claim 1 (Zwanzig identity). If e−βU1(x)>0e^{-\beta U_1(x)} > 0 implies e−βU0(x)>0e^{-\beta U_0(x)} > 0, then E0[w]=Z1/Z0E_0[w] = Z_1 / Z_0, so ΔA=−β−1ln⁡E0[w]\Delta A = -\beta^{-1} \ln E_0[w].

Proof. On the set where e−βU0>0e^{-\beta U_0} > 0,

E0[w]=∫e−βU0(x)Z0e−β(U1(x)−U0(x)) dx=1Z0∫e−βU1(x) dx=Z1Z0.E_0[w] = \int \frac{e^{-\beta U_0(x)}}{Z_0} e^{-\beta (U_1(x) - U_0(x))}\,dx = \frac{1}{Z_0} \int e^{-\beta U_1(x)}\,dx = \frac{Z_1}{Z_0}.

The integral over the set where e−βU0=0e^{-\beta U_0} = 0 is missing on the left, and by the hypothesis e−βU1e^{-\beta U_1} is 0 there too, so nothing is lost on the right. □\square

If the hypothesis fails, the same computation gives E0[w]=Z1′/Z0E_0[w] = Z_1' / Z_0 with Z1′Z_1' the integral over the support of state 0 only, which is smaller than Z1Z_1. This is the support condition of importance sampling.

Claim 2 (the shift). For any real numbers d1,…,dNd_1, \dots, d_N and m=min⁡idim = \min_i d_i,

m−1βln⁡(1N∑ie−β(di−m))=−1βln⁡(1N∑ie−βdi),m - \frac{1}{\beta} \ln \Bigl( \frac{1}{N} \sum_i e^{-\beta (d_i - m)} \Bigr) = -\frac{1}{\beta} \ln \Bigl( \frac{1}{N} \sum_i e^{-\beta d_i} \Bigr),

and every term e−β(di−m)e^{-\beta (d_i - m)} lies in (0,1](0, 1], with at least one equal to 1.

Proof. ∑ie−βdi=e−βm∑ie−β(di−m)\sum_i e^{-\beta d_i} = e^{-\beta m} \sum_i e^{-\beta (d_i - m)}; take −β−1ln⁡-\beta^{-1} \ln of both sides divided by NN. Since di−m≥0d_i - m \ge 0, each term is at most 1, and the index of the minimum gives 1. □\square

So lines L2 to L4 compute the estimator ΔA^=−β−1ln⁡w‾\widehat{\Delta A} = -\beta^{-1} \ln \overline{w} with w‾=N−1∑iw(xi)\overline{w} = N^{-1} \sum_i w(x_i), and the sum ss lies in [1,N][1, N], so neither overflow nor a logarithm of 0 occurs.

Claim 3 (consistency). If x1,x2,…x_1, x_2, \dots are independent draws from ρ0\rho_0, or a chain that is ergodic for ρ0\rho_0, then ΔA^→ΔA\widehat{\Delta A} \to \Delta A with probability 1 as N→∞N \to \infty.

Proof. w≥0w \ge 0 and E0[w]=Z1/Z0<∞E_0[w] = Z_1/Z_0 < \infty by Claim 1. The strong law of large numbers (or the ergodic theorem for the chain) gives w‾→Z1/Z0>0\overline{w} \to Z_1 / Z_0 > 0 almost surely, and −β−1ln⁡-\beta^{-1} \ln is continuous on (0,∞)(0, \infty). □\square

Claim 4 (bounds and bias). For every sample, min⁡iΔU(xi)≤ΔA^≤N−1∑iΔU(xi)\min_i \Delta U(x_i) \le \widehat{\Delta A} \le N^{-1} \sum_i \Delta U(x_i). For independent draws and every NN, E[ΔA^]≥ΔAE[\widehat{\Delta A}] \ge \Delta A.

Proof. The lower bound follows from Claim 2: s≤Ns \le N, so −β−1ln⁡(s/N)≥0-\beta^{-1} \ln(s/N) \ge 0. For the upper bound, the exponential is convex, so by Jensen's inequality for the uniform average over the sample, w‾=N−1∑ie−βdi≥e−βdˉ\overline{w} = N^{-1} \sum_i e^{-\beta d_i} \ge e^{-\beta \bar d} with dˉ\bar d the mean of the did_i; take −β−1ln⁡-\beta^{-1} \ln, which reverses the order. For the bias, ln⁡\ln is concave, so Jensen's inequality for the expectation over samples gives E[ln⁡w‾]≤ln⁡E[w‾]=ln⁡(Z1/Z0)E[\ln \overline{w}] \le \ln E[\overline{w}] = \ln(Z_1/Z_0), and multiplying by −β−1<0-\beta^{-1} < 0 gives E[ΔA^]≥ΔAE[\widehat{\Delta A}] \ge \Delta A. □\square

Claim 5 (error and first-order bias). Let the draws be independent with μ=E0[w]\mu = E_0[w] and σ2=var0(w)<∞\sigma^2 = \mathrm{var}_0(w) < \infty. Then

N (ΔA^−ΔA)→N(0,σ2β2μ2)\sqrt{N}\,(\widehat{\Delta A} - \Delta A) \to N\Bigl(0, \frac{\sigma^2}{\beta^2 \mu^2}\Bigr)

in distribution. If moreover ww takes its values in an interval [c,C][c, C] with c>0c > 0, the bias is E[ΔA^]−ΔA=σ2/(2Nβμ2)+O(N−3/2)E[\widehat{\Delta A}] - \Delta A = \sigma^2 / (2 N \beta \mu^2) + O(N^{-3/2}).

Proof. The central limit theorem gives N(w‾−μ)→N(0,σ2)\sqrt{N}(\overline{w} - \mu) \to N(0, \sigma^2). The map g(t)=−β−1ln⁡tg(t) = -\beta^{-1} \ln t has g′(μ)=−1/(βμ)g'(\mu) = -1/(\beta \mu), and the delta method gives the first statement. For the bias, Taylor's theorem gives g(w‾)=g(μ)+g′(μ)(w‾−μ)+12g′′(μ)(w‾−μ)2+16g′′′(ξ)(w‾−μ)3g(\overline{w}) = g(\mu) + g'(\mu)(\overline{w} - \mu) + \frac12 g''(\mu)(\overline{w} - \mu)^2 + \frac16 g'''(\xi)(\overline{w} - \mu)^3 with ξ\xi between μ\mu and w‾\overline{w}, so ξ∈[c,C]\xi \in [c, C]. Here g′′(μ)=1/(βμ2)g''(\mu) = 1/(\beta \mu^2) and ∣g′′′(ξ)∣=2/(βξ3)≤2/(βc3)|g'''(\xi)| = 2/(\beta \xi^3) \le 2/(\beta c^3). The linear term has mean 0, the quadratic term has mean σ2/(2Nβμ2)\sigma^2 / (2 N \beta \mu^2), and E∣w‾−μ∣3≤(E(w‾−μ)4)3/4=O(N−3/2)E|\overline{w} - \mu|^3 \le (E(\overline{w} - \mu)^4)^{3/4} = O(N^{-3/2}) for bounded ww. □\square

When ww is not bounded away from 0, as in the harmonic example, the same first-order term is the usual approximation; the page compares it with a measured bias.

The error bar of the code replaces σ\sigma and μ\mu by their sample values. It is valid only when σ<∞\sigma < \infty and NN is large enough that the rare large values of ww have been seen.

Claim 6 (staging). For 0=λ0<⋯<λK=10 = \lambda_0 < \dots < \lambda_K = 1 with finite ZλkZ_{\lambda_k} and the support condition in each window,

ΔA=∑k=0K−1−1βln⁡⟨e−β(Uλk+1−Uλk)⟩λk.\Delta A = \sum_{k=0}^{K-1} -\frac{1}{\beta} \ln \bigl\langle e^{-\beta (U_{\lambda_{k+1}} - U_{\lambda_k})} \bigr\rangle_{\lambda_k}.

Proof. By Claim 1 the kk-th term is −β−1ln⁡(Zλk+1/Zλk)-\beta^{-1} \ln(Z_{\lambda_{k+1}} / Z_{\lambda_k}). The sum telescopes to −β−1ln⁡(Z1/Z0)-\beta^{-1} \ln(Z_1 / Z_0). □\square

With independent windows the estimate of the sum has the sum of the variances of the windows, which gives the error bar of STAGED-FEP. Claims 3 to 5 apply to each term, so the staged estimate is consistent and biased upward.

Claim 7 (the examples).

(a) For U0=x2/2U_0 = x^2/2, U1=x2U_1 = x^2 and β=1\beta = 1: in the forward direction E[w]=1/2E[w] = 1/\sqrt2 and E[w2]=1/3E[w^2] = 1/\sqrt3. In the reverse direction, with samples of state 1 and weight e+ΔUe^{+\Delta U}, the second moment is infinite.

(b) For Uλ=(x−aλ)2/2U_\lambda = (x - a\lambda)^2 / 2 and β=1\beta = 1, one window from λ\lambda to λ+δ\lambda + \delta has var(w)/E[w]2=ea2δ2−1\mathrm{var}(w)/E[w]^2 = e^{a^2 \delta^2} - 1. So KK equal windows with N/KN/K samples each give the large-NN variance K2(ea2/K2−1)/NK^2 (e^{a^2/K^2} - 1) / N.

Proof. (a) w=e−x2/2w = e^{-x^2/2} and x∼N(0,1)x \sim N(0, 1), so E[w]=(2π)−1/2∫e−x2 dx=1/2E[w] = (2\pi)^{-1/2} \int e^{-x^2}\,dx = 1/\sqrt2 and E[w2]=(2π)−1/2∫e−3x2/2 dx=1/3E[w^2] = (2\pi)^{-1/2} \int e^{-3x^2/2}\,dx = 1/\sqrt3. In reverse, x∼N(0,1/2)x \sim N(0, 1/2) has density π−1/2e−x2\pi^{-1/2} e^{-x^2} and the weight is ex2/2e^{x^2/2}, so E[w2]=π−1/2∫ex2e−x2 dx=∞E[w^2] = \pi^{-1/2} \int e^{x^2} e^{-x^2}\,dx = \infty.

(b) Shift xx so that the window starts at 0: ΔU=(x−b)2/2−x2/2=−bx+b2/2\Delta U = (x - b)^2/2 - x^2/2 = -bx + b^2/2 with b=aδb = a\delta, and x∼N(0,1)x \sim N(0, 1). Then w=ebx−b2/2w = e^{bx - b^2/2}, E[w]=1E[w] = 1 and E[w2]=e−b2E[e2bx]=eb2E[w^2] = e^{-b^2} E[e^{2bx}] = e^{b^2}. By Claim 5 one window has variance (eb2−1)/n(e^{b^2} - 1) / n with nn samples; with δ=1/K\delta = 1/K, n=N/Kn = N/K and KK independent windows the total is K⋅K(ea2/K2−1)/NK \cdot K (e^{a^2/K^2} - 1) / N. □\square

For a=3a = 3 and N=1200N = 1200 this is (e9−1)/1200=6.75(e^9 - 1)/1200 = 6.75 for one window, a standard deviation of 2.60, and 0.0085 for six windows, a standard deviation of 0.092.

Complexity

One window costs NN evaluations of ΔU\Delta U and NN exponentials, so the staged form costs Θ(KN)\Theta(K N) plus KNK N draws from the sampler, which in practice is the dominant cost (molecular dynamics or Monte Carlo). The extra space is O(N)O(N) for the differences, or O(1)O(1) if a running maximum and a running sum are kept. The number of samples needed for a given error is proportional to var(w)/E[w]2\mathrm{var}(w) / E[w]^2, which grows exponentially as the overlap gets worse: for the shifted well it is ea2−1e^{a^2} - 1 in one window and K2(ea2/K2−1)K^2(e^{a^2/K^2} - 1) over KK windows (a theorem for that example).

Properties

  • Exact identity, biased estimator. The identity is a theorem; the estimate is biased upward for finite NN and consistent.
  • Asymmetric. The forward and reverse estimates are not equally good. The better direction is usually the one that samples the state with the wider distribution (a heuristic), as in the harmonic example.
  • Only end states. One window needs samples of one state and the energy of the other on those samples; it needs no derivative of UU.
  • Self-deceiving error bars. When the overlap is poor, the error bar from the samples is too small, as in the shifted well with one window.
  • Insensitive to a constant. Adding a constant cc to U1U_1 adds cc to the estimate exactly.

Variants and improvements

  • Staging with intermediate λ\lambda windows, as above. The number and spacing of windows is a choice; a common heuristic keeps the standard deviation of βΔU\beta \Delta U in each window near 1 to 2.
  • Bennett acceptance ratio. BAR uses the samples of both states of a window and has the lowest variance among a broad class of estimators; MBAR (Shirts and Chodera 2008) extends it to all windows at once.
  • Cumulant expansion. βΔA=β⟨ΔU⟩0−β22var0(ΔU)+…\beta \Delta A = \beta \langle \Delta U \rangle_0 - \frac{\beta^2}{2} \mathrm{var}_0(\Delta U) + \dots, exact to second order when ΔU\Delta U is normal. It is a model, not an identity, and it fails for skewed distributions.
  • Nonequilibrium paths. The Jarzynski equality is FEP with the instantaneous switch replaced by a finite-time switch; annealed importance sampling is its counterpart in statistics.
  • Thermodynamic integration replaces the exponential average by an integral of ⟨∂U/∂λ⟩λ\langle \partial U / \partial \lambda \rangle_\lambda, which has no exponential and is often more stable.

When to use it

Use FEP for small changes, where the two states share most of their important configurations: a small mutation of a ligand, a change of a charge, a new force field term. Its simplicity and its use of end states only make it a quick first estimate, and in staged form it is the classic alchemical method. For large changes, use many windows and combine them with BAR, or use thermodynamic integration. Run both directions: if the forward and reverse estimates disagree by much more than their error bars, the overlap is too poor.

Pitfalls

  • Poor overlap with small error bars. The estimate can be wrong by many error bars, as in the one-window shifted well. Always compare forward and reverse, or look at the histogram of βΔU\beta \Delta U.
  • Infinite variance. In the reverse harmonic case the variance of ww is infinite, and the usual error bar is meaningless.
  • Overflow. Computing e−βΔUe^{-\beta \Delta U} without the shift overflows or underflows for ∣βΔU∣|\beta \Delta U| beyond a few hundred.
  • Particles that appear. When atoms are switched on, configurations where they overlap others give U1=∞U_1 = \infty and break the support condition in the reverse direction; soft-core potentials are the standard fix.
  • Correlated samples. The error formula assumes independent samples; use block averages for a correlated chain.

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.

free_energy_perturbation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/free-energy-perturbation/. The authors are listed in prov/1TXW31.jsonl.
"""Free energy perturbation (Zwanzig 1954), also called exponential averaging.

For two states with potential energies U_0 and U_1 on the same configuration
space, at the inverse temperature beta,

    A_1 - A_0 = -(1 / beta) ln < exp(-beta (U_1 - U_0)) >_0,

where <.>_0 is the canonical average in state 0. The estimator replaces the
average by the mean over N samples of state 0. It is computed with a shift by
the smallest energy difference, so that no exponential overflows.

The staged form splits the path from state 0 to state 1 into windows
lambda_0 = 0 < lambda_1 < ... < lambda_K = 1 and adds the estimates of the
windows. The sampler of each state is an input (exact draws, Metropolis Monte
Carlo or molecular dynamics); it is not part of the method.

Cost: Theta(N) energy differences and exponentials per window.
"""

import math
from typing import Callable, Sequence


def fep(du: Sequence[float], beta: float) -> float:
    """Estimate A_1 - A_0 from the differences du_i = U_1(x_i) - U_0(x_i), x_i from state 0."""
    n = len(du)
    if n == 0:
        raise ValueError("need at least one sample")
    m = min(du)                                          # @line L2
    s = 0.0
    for d in du:
        s += math.exp(-beta * (d - m))                   # @line L3
    return m - math.log(s / n) / beta                    # @line L4


def fep_from_samples(xs, u0: Callable, u1: Callable, beta: float) -> float:
    """FEP from configurations xs of state 0 and the two energy functions."""
    du = [u1(x) - u0(x) for x in xs]                     # @line L1
    return fep(du, beta)


def fep_error(du: Sequence[float], beta: float) -> float:
    """Delta-method standard error of fep(du, beta) for independent samples.

    With w_i = exp(-beta du_i), the error is sd(w) / (beta sqrt(N) mean(w)).
    It is a large-N estimate; when the variance of w is infinite it is not valid.
    """
    n = len(du)
    if n < 2:
        raise ValueError("need at least two samples")
    m = min(du)
    w = [math.exp(-beta * (d - m)) for d in du]
    mean = sum(w) / n
    var = sum((x - mean) ** 2 for x in w) / (n - 1)
    return math.sqrt(var / n) / (beta * mean)


def staged_fep(lambdas: Sequence[float], sample: Callable, energy: Callable,
               beta: float, n: int, rng) -> tuple[float, float]:
    """Staged FEP over the windows lambdas[0] < ... < lambdas[K].

    sample(lam, n, rng) returns n configurations of the state lam, and
    energy(lam, x) is U_lam(x). Returns the estimate and its standard error
    (the errors of independent windows added in quadrature).
    """
    total, var = 0.0, 0.0                                # @line L5
    for k in range(len(lambdas) - 1):                    # @line L6
        xs = sample(lambdas[k], n, rng)                  # @line L7
        du = [energy(lambdas[k + 1], x) - energy(lambdas[k], x) for x in xs]
        total += fep(du, beta)                           # @line L8
        var += fep_error(du, beta) ** 2
    return total, math.sqrt(var)                         # @line L9
test_free_energy_perturbation.py 111 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/free-energy-perturbation/. The authors are listed in prov/1TXW31.jsonl.
import math
import random

import pytest

from free_energy_perturbation import fep, fep_error, fep_from_samples, staged_fep


def test_hand_example():
    # du = 0, 1, 2 in units of kT: dA = -ln((1 + e^-1 + e^-2) / 3).
    assert fep([0.0, 1.0, 2.0], 1.0) == pytest.approx(0.691006, abs=1e-6)


def test_constant_difference_is_exact():
    assert fep([2.5] * 7, 0.4) == pytest.approx(2.5, abs=1e-12)
    assert fep([-1.25], 3.0) == pytest.approx(-1.25, abs=1e-12)


def test_no_overflow_for_large_differences():
    du = [1000.0, 1001.0, 1002.0]
    assert fep(du, 1.0) == pytest.approx(1000.0 + 0.691006, abs=1e-6)
    du = [-1000.0, -999.0]
    assert math.isfinite(fep(du, 1.0))


def test_jensen_bound_estimate_never_exceeds_mean():
    rng = random.Random(11)
    for _ in range(50):
        du = [rng.uniform(-3, 3) for _ in range(rng.randint(1, 20))]
        assert fep(du, 1.0) <= sum(du) / len(du) + 1e-12
        assert fep(du, 1.0) >= min(du) - 1e-12


def test_harmonic_wells_against_exact_value():
    # U_0 = x^2 / 2, U_1 = x^2 (k_0 = 1, k_1 = 2), kT = 1: dA = ln(2) / 2.
    exact = 0.5 * math.log(2.0)
    rng = random.Random(1)
    xs = [rng.gauss(0.0, 1.0) for _ in range(20000)]
    est = fep_from_samples(xs, lambda x: 0.5 * x * x, lambda x: x * x, 1.0)
    se = fep_error([0.5 * x * x for x in xs], 1.0)
    assert abs(est - exact) < 4 * se
    # The exact large-N error: var(w) / (N E[w]^2) with E[w] = 1/sqrt(2), E[w^2] = 1/sqrt(3).
    assert se == pytest.approx(math.sqrt((1 / math.sqrt(3) - 0.5) / 0.5 / 20000), rel=0.05)


def test_temperature_scaling():
    # dA = (kT / 2) ln(k_1 / k_0) for each kT.
    for kT in (0.5, 2.0):
        beta = 1.0 / kT
        rng = random.Random(2)
        xs = [rng.gauss(0.0, math.sqrt(kT)) for _ in range(20000)]
        du = [0.5 * x * x for x in xs]
        assert abs(fep(du, beta) - 0.5 * kT * math.log(2.0)) < 4 * fep_error(du, beta)


def test_small_samples_are_biased_upward():
    # E[fep] >= dA by Jensen's inequality; the first-order bias is var(w) / (2 N beta E[w]^2).
    exact = 0.5 * math.log(2.0)
    rng = random.Random(3)
    n, reps = 5, 4000
    vals = [fep([0.5 * rng.gauss(0, 1) ** 2 for _ in range(n)], 1.0) for _ in range(reps)]
    mean = sum(vals) / reps
    sd = math.sqrt(sum((v - mean) ** 2 for v in vals) / (reps - 1))
    first_order = (1 / math.sqrt(3) - 0.5) / 0.5 / (2 * n)
    se = sd / math.sqrt(reps)
    assert mean - exact > 4 * se
    assert abs(mean - exact - first_order) < 4 * se + 0.5 * first_order


def shifted(a):
    def sample(lam, n, rng):
        return [a * lam + rng.gauss(0.0, 1.0) for _ in range(n)]

    def energy(lam, x):
        return 0.5 * (x - a * lam) ** 2

    return sample, energy


def test_staged_fep_on_shifted_well():
    # Moving a unit well by a = 3 does not change A, so dA = 0.
    sample, energy = shifted(3.0)
    lams = [k / 6 for k in range(7)]
    est, se = staged_fep(lams, sample, energy, 1.0, 200, random.Random(1))
    assert abs(est) < 4 * se
    assert se < 0.12


def test_one_window_with_poor_overlap_fails_its_own_error_bar():
    # One window with the same 1200 samples: the error bar of the estimator is too small.
    sample, energy = shifted(3.0)
    est, se = staged_fep([0.0, 1.0], sample, energy, 1.0, 1200, random.Random(1))
    assert abs(est) > 4 * se


def test_staged_harmonic_matches_exact():
    def sample(lam, n, rng):
        return [rng.gauss(0.0, 1.0 / math.sqrt(1 + 15 * lam)) for _ in range(n)]

    def energy(lam, x):
        return 0.5 * (1 + 15 * lam) * x * x

    est, se = staged_fep([0, 1 / 15, 3 / 15, 7 / 15, 1], sample, energy, 1.0, 2000, random.Random(5))
    assert abs(est - 0.5 * math.log(16.0)) < 4 * se


def test_empty_input_raises():
    with pytest.raises(ValueError):
        fep([], 1.0)

History

Zwanzig (1954) wrote the free energy of a perturbed system as an average of the Boltzmann factor of the perturbation over the unperturbed system, and expanded it for the equation of state of gases at high temperature. The same identity became a computational method once Monte Carlo and molecular dynamics could sample the unperturbed system. Bennett (1976) analysed its variance and showed how to use both states. Its alchemical use, in which atoms are mutated through intermediate states, became common in the 1980s for solvation and binding free energies.

References

  1. Robert W. Zwanzig, High-temperature equation of state by a perturbation method. I. Nonpolar gases, Journal of Chemical Physics 22(8), 1954, 1420-1426, the perturbation formula for the free energy as an average of exp(-U_1/kT) over the unperturbed system
  2. 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 chapter on free energy perturbation, its bias and variance, and staging
  3. Tony Lelièvre, Mathias Rousset and Gabriel Stoltz, Free Energy Computations, A Mathematical Perspective, Imperial College Press, 2010, the treatment of free energy differences between two states and the free energy perturbation identity
  4. Michael P. Allen and Dominic J. Tildesley, Computer Simulation of Liquids, second edition, Oxford University Press, 2017, the sections on free energy differences by perturbation and on staging

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.

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