Algorithm Search⌘K

Algorithmadvanced

Metadynamics

Adds Gaussian hills at visited values of collective variables so the system escapes free energy minima; in the well-tempered form the bias converges to a scaled free energy.

Time
O(T + m G) worst
Space
O(G) extra
Where
G = the number of grid points of the bias; T = the number of time steps; m = the number of hills
Properties
not consistentrandomizediterativerandomizednot unbiased
Origin
Alessandro Laio, Michele Parrinello, 2002

Metadynamics computes a free energy surface along a few collective variables s(x)s(x) by building a bias during the run. Every τ\tau steps it adds a small Gaussian hill of width σ\sigma to a bias V(s)V(s) at the current value of ss. Hills pile up where the system stays, so a free energy well fills until the system spills over the barrier into the next well, which then fills too. The system thus escapes minima that ordinary Langevin dynamics would not leave in the time available. In standard metadynamics (Laio and Parrinello 2002) the hills have a constant height ww, and at long times −V(s)-V(s) follows the free energy F(s)F(s) up to a constant, but it keeps fluctuating with an error that does not shrink, and the bias grows without bound. In well-tempered metadynamics (Barducci, Bussi and Parrinello 2008) the height is w e−V(s)/(kBΔT)w\,e^{-V(s)/(k_B \Delta T)}, the hills shrink as the bias grows, and the bias converges to V=−ΔTT+ΔTFV = -\frac{\Delta T}{T + \Delta T} F up to a constant (Dama, Parrinello and Voth 2014), so F=−T+ΔTΔTVF = -\frac{T + \Delta T}{\Delta T} V.

In plain words

Picture a ball rolling in a landscape of valleys, with the ball shaken by heat. It stays in one valley for a very long time because the hills around it are high.

Metadynamics drops a small pile of sand wherever the ball is, every few steps. The valley slowly fills with sand, the ball rises with it, and at last it rolls over into the next valley, which then fills in turn. In the end the landscape is nearly flat, and the sand that was added has the shape of the valleys, upside down.

In the well-tempered form the piles get smaller where much sand already lies, so the sand settles to a fixed shape instead of growing for ever.

The problem

The input is a potential U(x)U(x), a collective variable s(x)s(x), the temperature TT, a dynamics that samples e−β(U+V)e^{-\beta(U + V)} with β=1/(kBT)\beta = 1/(k_B T), and the hill parameters ww, σ\sigma, τ\tau, and ΔT\Delta T for the well-tempered form. The target is the free energy profile

F(s)=−kBTln⁡p(s)+constF(s) = -k_B T \ln p(s) + \text{const}

of the marginal p(s)p(s) of s(x)s(x) in the canonical ensemble. The output is the bias VV on a grid and the estimate of FF that follows from it. Unlike umbrella sampling the bias is not known in advance and is not fixed; unlike plain sampling, the run crosses the barriers.

The algorithm

  1. METADYNAMICS(U, s, x_0, kT, h, steps, w, sigma, tau, k dT)
  2. 1V ← 0 on a grid of s
  3. 2for n ← 1 to steps do
  4. 3x ← x - h (U'(x) + V'(s(x)) s'(x)) + sqrt(2 kT h) xi ▷ xi ~ N(0, 1)
  5. 4if n mod tau = 0 then
  6. 5height ← w (standard) or w exp(-V(s(x)) / k dT) (well-tempered)
  7. 6V(s') ← V(s') + height exp(-(s' - s(x))^2 / (2 sigma^2)) on the grid
  8. 7return F ≈ -V (standard) or -((kT + k dT) / k dT) V (well-tempered), up to a constant

Line L3 is one Euler-Maruyama step of overdamped Langevin dynamics on U+VU + V; molecular dynamics with a thermostat is the usual choice in practice. Line L6 keeps VV on a grid as values and slopes, and the code reads it back by cubic Hermite interpolation, so the force in line L3 is the exact derivative of the bias that is read and one step costs O(1)O(1). Line L7 rescales the well-tempered bias by the bias factor. The ratio γ=(T+ΔT)/T\gamma = (T + \Delta T)/T is called the bias factor, and the collective variable is sampled as if at the higher temperature T+ΔTT + \Delta T (Claim 2 of the proof).

Example

Take U(x)=8(x2−1)2U(x) = 8(x^2 - 1)^2, s=xs = x, kBT=1k_B T = 1, so F=UF = U with minima at ±1\pm 1 and a barrier of 8 kBT8\,k_B T. Use h=0.005h = 0.005, σ=0.2\sigma = 0.2, w=0.1w = 0.1 and τ=10\tau = 10, start at x=−1x = -1, and count a transition each time xx passes from below −0.5-0.5 to above 0.50.5 or back.

Escape. In 10000 steps (seed 1) plain dynamics made 0 transitions and standard metadynamics made 25.

The profile after 80000 steps (seed 1), on the region with U<5U < 5 after the best constant shift:

form largest value of VV largest error barrier F(0)−F(1)F(0) - F(1) asymmetry F(−1)−F(1)F(-1) - F(1)
well-tempered, kBΔT=7k_B \Delta T = 7 24.0 0.418 7.932 0.197
standard 111.7 0.785 8.684 0.963

The exact barrier is 8 and the exact asymmetry is 0. The standard bias kept growing: its integral is exactly the number of hills times wσ2πw \sigma \sqrt{2\pi}, so it rises linearly with time (Claim 1). Over three seeds and times from 5000 to 80000 steps, the largest error of standard metadynamics stayed between 0.7 and 1.8 and did not decrease; with kBΔT=7k_B \Delta T = 7 it was 0.42 to 0.74 at 80000 steps. The grid bias agreed with the direct sum of all hills to 4.8×10−84.8 \times 10^{-8}, and its force with a finite difference to 10−910^{-9}.

Correctness

The proof in proofs/correctness.md shows:

  1. The standard bias grows without bound. With constant heights, the integral of VV over the whole line equals the number of hills times wσ2πw \sigma \sqrt{2\pi}, so VV cannot converge.
  2. The fixed shape of the bias. In the limit of slow deposition and narrow hills, the deposition rate is uniform in ss exactly when V=−ΔTT+ΔTF+cV = -\frac{\Delta T}{T + \Delta T} F + c; then ss is distributed as e−F/(kB(T+ΔT))e^{-F/(k_B (T + \Delta T))}. The limit ΔT→∞\Delta T \to \infty gives the standard form with V=−F+cV = -F + c and a flat distribution of ss, and ΔT→0\Delta T \to 0 gives no bias.
  3. The constant grows like a logarithm. In the same limit the well-tempered constant c(t)c(t) grows like kBΔTln⁡tk_B \Delta T \ln t, so the hill heights decay like 1/t1/t.
  4. The grid. The cubic Hermite bias is continuously differentiable, its derivative is the force used, and its error against the sum of the hills is at most Δs4max⁡∣V(4)∣/384\Delta s^4 \max |V^{(4)}| / 384 for grid spacing Δs\Delta s.

Claims 2 and 3 are statements about the quasi-static limit, not a proof that the stochastic algorithm converges. That proof for the well-tempered form is due to Dama, Parrinello and Voth (2014) and is not repeated here.

Proof: The growth of the standard bias, the fixed shape of the well-tempered bias, and the gridfull

Let ss be one collective variable, F(s)=−β−1ln⁡p(s)F(s) = -\beta^{-1} \ln p(s) its free energy at inverse temperature β=1/(kBT)\beta = 1/(k_B T), and Vn(s)V_n(s) the bias after nn hills. Hill jj is centred at sjs_j, the value of ss at the time of deposit, and has height wjw_j and width σ\sigma:

Vn(s)=∑j=1nwj e−(s−sj)2/(2σ2),wj=w (standard),wj=w e−Vj−1(sj)/(kBΔT) (well-tempered).V_n(s) = \sum_{j=1}^{n} w_j\, e^{-(s - s_j)^2 / (2\sigma^2)}, \qquad w_j = w \text{ (standard)}, \quad w_j = w\, e^{-V_{j-1}(s_j) / (k_B \Delta T)} \text{ (well-tempered)}.

Claim 1 (the standard bias grows without bound). With wj=ww_j = w, ∫−∞∞Vn(s) ds=n wσ2π\int_{-\infty}^{\infty} V_n(s)\,ds = n\, w \sigma \sqrt{2\pi} for every trajectory. If all centres lie in an interval [a,b][a, b], then max⁡sVn(s)≥n wσ2π (1−ϵ)/(b−a+2Lσ)\max_s V_n(s) \ge n\, w \sigma \sqrt{2\pi}\,(1 - \epsilon) / (b - a + 2 L \sigma), where ϵ=erfc(L/2)\epsilon = \mathrm{erfc}(L / \sqrt 2) for any L>0L > 0. So max⁡Vn\max V_n grows at least linearly in nn. Since VnV_n is nondecreasing in nn at every ss, it does not converge to a bounded function, and it does not converge in L1L^1.

Proof. Each Gaussian has integral wσ2πw \sigma \sqrt{2\pi}; sum over jj. For a centre in [a,b][a, b], the mass of its Gaussian outside [a−Lσ,b+Lσ][a - L\sigma, b + L\sigma] is at most the mass outside [sj−Lσ,sj+Lσ][s_j - L\sigma, s_j + L\sigma], which is the fraction erfc(L/2)=ϵ\mathrm{erfc}(L / \sqrt 2) = \epsilon. So the integral of VnV_n over the interval [a−Lσ,b+Lσ][a - L\sigma, b + L\sigma], of length b−a+2Lσb - a + 2L\sigma, is at least (1−ϵ)nwσ2π(1 - \epsilon) n w \sigma \sqrt{2\pi}, and the maximum is at least this integral divided by the length. □\square

Thus in standard metadynamics −Vn-V_n can follow FF only up to a constant that grows with nn, and the shape keeps fluctuating at the scale of the hills; Claim 2 describes the shape, not convergence.

For Claims 2 and 3 use the quasi-static model. The bias changes so slowly that at each time the walker has the equilibrium density of ss under U+VU + V,

pV(s)=e−β(F(s)+V(s))ZV,ZV=∫e−β(F+V) ds,p_V(s) = \frac{e^{-\beta (F(s) + V(s))}}{Z_V}, \qquad Z_V = \int e^{-\beta (F + V)}\,ds,

and the hills are narrow, so each hill adds mass wjσ2πw_j \sigma \sqrt{2\pi} at sjs_j. Then the expected change of VV per hill is

∂V∂n(s)=σ2π w g(V(s)) pV(s),g(V)=1 (standard),g(V)=e−V/(kBΔT) (well-tempered).\frac{\partial V}{\partial n}(s) = \sigma \sqrt{2\pi}\, w\, g(V(s))\, p_V(s), \qquad g(V) = 1 \text{ (standard)}, \quad g(V) = e^{-V / (k_B \Delta T)} \text{ (well-tempered)}.

Claim 2 (the fixed shape). In the quasi-static model, the rate ∂V/∂n\partial V / \partial n is the same at every ss if and only if

V(s)=−ΔTT+ΔTF(s)+c (well-tempered),V(s)=−F(s)+c (standard),V(s) = -\frac{\Delta T}{T + \Delta T} F(s) + c \text{ (well-tempered)}, \qquad V(s) = -F(s) + c \text{ (standard)},

for a constant cc. For the well-tempered shape, pV(s)∝e−F(s)/(kB(T+ΔT))p_V(s) \propto e^{-F(s) / (k_B (T + \Delta T))}: ss is sampled as if at temperature T+ΔTT + \Delta T. For the standard shape, pVp_V is uniform.

Proof. The rate is uniform if and only if ln⁡g(V(s))−β(F(s)+V(s))\ln g(V(s)) - \beta (F(s) + V(s)) does not depend on ss. For the standard form this reads F+V=constF + V = \text{const}. For the well-tempered form it reads V/(kBΔT)+β(F+V)=constV / (k_B \Delta T) + \beta (F + V) = \text{const}; multiply by kBTΔT/(T+ΔT)k_B T \Delta T / (T + \Delta T) to get V=−ΔTT+ΔTF+cV = -\frac{\Delta T}{T + \Delta T} F + c. Then F+V=TT+ΔTF+cF + V = \frac{T}{T + \Delta T} F + c, so β(F+V)=F/(kB(T+ΔT))+βc\beta (F + V) = F / (k_B (T + \Delta T)) + \beta c, which gives the density. □\square

As ΔT→∞\Delta T \to \infty the well-tempered shape tends to the standard one and g→1g \to 1; as ΔT→0\Delta T \to 0 the factor ΔT/(T+ΔT)\Delta T / (T + \Delta T) tends to 0, which is no bias. Line L7 of the algorithm inverts the well-tempered shape: F=−T+ΔTΔTV+constF = -\frac{T + \Delta T}{\Delta T} V + \text{const}, and (T+ΔT)/ΔT=(kBT+kBΔT)/(kBΔT)(T + \Delta T)/\Delta T = (k_B T + k_B \Delta T)/(k_B \Delta T), the factor of the code.

The fixed shape attracts in this model. Write V=V∗+uV = V^* + u with V∗V^* the shape of Claim 2. Then ∂u/∂n(s)=K e−αu(s)\partial u / \partial n (s) = K\, e^{-\alpha u(s)} with α=β+1/(kBΔT)>0\alpha = \beta + 1/(k_B \Delta T) > 0 (or α=β\alpha = \beta for the standard form) and K>0K > 0 independent of ss. So where uu is larger it grows more slowly, and the difference u(s1)−u(s2)u(s_1) - u(s_2) moves towards 0.

Claim 3 (the constant grows like a logarithm). In the quasi-static model with the well-tempered shape Vn=V∗+cnV_n = V^* + c_n, there is B>0B > 0 with dc/dn=B e−c/(kBΔT)dc / dn = B\, e^{-c / (k_B \Delta T)}, so

cn=kBΔTln⁡(ec0/(kBΔT)+Bn/(kBΔT)),c_n = k_B \Delta T \ln\bigl(e^{c_0 / (k_B \Delta T)} + B n / (k_B \Delta T)\bigr),

which grows like kBΔTln⁡nk_B \Delta T \ln n, and the hill heights w e−Vn(s)/(kBΔT)w\,e^{-V_n(s)/(k_B \Delta T)} decay like 1/n1/n. For the standard form dc/dndc / dn is a positive constant, so cnc_n grows linearly, as in Claim 1.

Proof. ZV∗+c=e−βcZV∗Z_{V^* + c} = e^{-\beta c} Z_{V^*}, so pV∗+c=pV∗p_{V^* + c} = p_{V^*} does not depend on cc. Then ∂V/∂n=σ2π w e−c/(kBΔT)⋅e−V∗(s)/(kBΔT)pV∗(s)\partial V / \partial n = \sigma \sqrt{2\pi}\, w\, e^{-c / (k_B \Delta T)} \cdot e^{-V^*(s) / (k_B \Delta T)} p_{V^*}(s), and by Claim 2 the last product is a positive constant; call BB its product with σ2π w\sigma \sqrt{2\pi}\, w. Solve the separable equation: d(ec/(kBΔT))/dn=B/(kBΔT)d(e^{c / (k_B \Delta T)}) / dn = B / (k_B \Delta T). The heights are w e−V∗(s)/(kBΔT)e−cn/(kBΔT)w\,e^{-V^*(s)/(k_B \Delta T)} e^{-c_n / (k_B \Delta T)}, and e−cn/(kBΔT)=1/(ec0/(kBΔT)+Bn/(kBΔT))e^{-c_n / (k_B \Delta T)} = 1 / (e^{c_0 / (k_B \Delta T)} + B n / (k_B \Delta T)). For the standard form, ∂V/∂n=σ2π w pV∗\partial V / \partial n = \sigma \sqrt{2\pi}\, w\, p_{V^*} with pV∗p_{V^*} uniform. □\square

Claims 2 and 3 hold in the quasi-static model only. They explain the scale factor and the decay of the hills, but they are not a proof that the stochastic algorithm converges. Dama, Parrinello and Voth (2014) proved the convergence of the well-tempered bias; this note does not repeat that proof.

Claim 4 (the grid). Let the grid have nodes si=lo+i Δss_i = lo + i\,\Delta s, and let the code store at each node the exact value V(si)V(s_i) and slope V′(si)V'(s_i) of the sum of hills. On each cell the code returns the cubic Hermite interpolant HH of these values and slopes, and its derivative H′H' as the force. Then HH is continuously differentiable on [lo,hi][lo, hi], H′H' is exactly its derivative, and

∣V(s)−H(s)∣≤Δs4384max⁡cell∣V(4)∣.|V(s) - H(s)| \le \frac{\Delta s^4}{384} \max_{\text{cell}} |V^{(4)}|.

Proof. Each deposit adds the exact value and derivative of the new Gaussian at every node, so the stored data are exact. On a cell with t=(s−si)/Δst = (s - s_i)/\Delta s, H=h00(t)Vi+h10(t)ΔsVi′+h01(t)Vi+1+h11(t)ΔsVi+1′H = h_{00}(t) V_i + h_{10}(t) \Delta s V'_i + h_{01}(t) V_{i+1} + h_{11}(t) \Delta s V'_{i+1} with the Hermite basis h00=(1+2t)(1−t)2h_{00} = (1 + 2t)(1 - t)^2, h10=t(1−t)2h_{10} = t(1 - t)^2, h01=t2(3−2t)h_{01} = t^2 (3 - 2t), h11=t2(t−1)h_{11} = t^2 (t - 1). Their tt-derivatives are 6t(t−1)6t(t - 1), (1−t)(1−3t)(1 - t)(1 - 3t), −6t(t−1)-6t(t - 1) and t(3t−2)t(3t - 2), and the chain rule divides by Δs\Delta s; these are the expressions of the code. At t=0t = 0 and t=1t = 1, HH and H′H' equal the stored values and slopes, so neighbouring cells join with matching value and slope. The error bound is the standard remainder of cubic Hermite interpolation, V(s)−H(s)=V(4)(ξ) t2(1−t)2Δs4/24V(s) - H(s) = V^{(4)}(\xi)\, t^2 (1 - t)^2 \Delta s^4 / 24 for some ξ\xi in the cell, with t2(1−t)2≤1/16t^2 (1 - t)^2 \le 1/16. □\square

For a Gaussian of width σ\sigma, ∣V(4)∣≤3w/σ4|V^{(4)}| \le 3 w / \sigma^4 per hill, so with Δs=0.01\Delta s = 0.01 and σ=0.2\sigma = 0.2 the relative error is below 10−710^{-7} per hill, which agrees with the measured 4.8×10−84.8 \times 10^{-8} on the page. Outside [lo,hi][lo, hi] the code returns 0, so the bias is not continuous at the edge of the grid; the runs on the page stay inside it.

Complexity

Each step costs one force evaluation of UU and O(1)O(1) for the grid bias. Each of the m=T/τm = T / \tau hills costs O(G)O(G) to add on a grid of GG points, or less if only the points within a few σ\sigma are updated. So the time is O(T+mG)O(T + m G) and the extra space is O(G)O(G). Without a grid, each step must sum all hills so far, which costs O(T2/τ)O(T^2 / \tau) in total. The grid grows exponentially with the number of collective variables, which limits metadynamics to about one to three of them.

Properties

  • History-dependent bias. The dynamics is not at equilibrium during the run; the bias changes the sampled distribution all the time.
  • Standard form does not converge. −V-V follows FF up to fluctuations of order of the hill size, and the bias grows without bound.
  • Well-tempered form converges to −ΔTT+ΔTF-\frac{\Delta T}{T + \Delta T} F up to a constant, and the hills shrink like 1/t1/t.
  • Tunable. ΔT\Delta T sets how far the bias flattens the surface: the barrier seen by ss is divided by the bias factor γ\gamma.
  • Exploration without a path. It needs no windows or path in advance, only the collective variables.
  • Depends on the collective variables. A slow motion that is not described by ss is not accelerated, and the bias can then be wrong.

Variants and improvements

  • Well-tempered metadynamics (Barducci, Bussi and Parrinello 2008), as above.
  • Reweighting. Samples of the biased run can be reweighted to the unbiased ensemble to get averages of other quantities, using the bias and its time-dependent constant.
  • Multiple walkers. Several runs add hills to one shared bias.
  • Parallel tempering metadynamics and bias-exchange metadynamics combine the bias with parallel tempering or with exchanges between runs that bias different variables.
  • Related adaptive biases. Wang-Landau sampling fills the density of states with a decreasing step, the adaptive biasing force method builds the mean force instead of the bias, and hyperdynamics uses a bias to accelerate rare events while keeping their rates.

When to use it

Use metadynamics to explore an unknown free energy surface along one to three good collective variables, to find the states and the paths between them, and, in the well-tempered form, to compute the surface. Prefer umbrella sampling with WHAM when the path is known and the most accurate profile along it is wanted. Use the well-tempered form for any quantitative work; standard metadynamics is mainly a tool to explore.

Pitfalls

  • Bad collective variables. If a slow degree of freedom is missing from ss, the system can be pushed over the wrong barrier and the bias shows hysteresis; check by running forward and backward and from different starts.
  • Hills too large or too frequent. The system then is not near equilibrium under the current bias, and the error grows.
  • Standard bias used as a converged answer. It keeps fluctuating; average over time or use the well-tempered form.
  • Missing scale factor. The well-tempered bias must be multiplied by (T+ΔT)/ΔT(T + \Delta T)/\Delta T.
  • Grid boundaries. Outside the grid the bias is zero in the code here; in practice add walls, or the system can leave the grid and not feel the bias.
  • Overfilling at edges. Near a hard wall in ss the Gaussians spill over and the estimate near the wall is wrong.

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.

metadynamics.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/metadynamics/. The authors are listed in prov/EGQBSZ.jsonl.
"""Metadynamics (Laio and Parrinello 2002) and its well-tempered form
(Barducci, Bussi and Parrinello 2008) on a one-dimensional coordinate s = x.

The walker follows overdamped Langevin dynamics on U + V, stepped by the
Euler-Maruyama method with time step h,

    x <- x - h (U'(x) + V'(x)) + sqrt(2 kT h) xi,   xi ~ N(0, 1).

Every tau steps a Gaussian of width sigma is added to the bias V at the
current s. In standard metadynamics the height is a constant w, and -V
follows F only up to fluctuations of order w that do not die out. In the
well-tempered form the height is w exp(-V(s) / (k dT)), the bias converges,
and F(s) is estimated by -((kT + k dT) / k dT) V(s) up to a constant.

The bias is kept on a grid as values and slopes, and read back by cubic
Hermite interpolation, so the force is the exact derivative of the bias that
is read. One step costs O(1) and one deposit costs O(grid size).
"""

import math
from typing import Callable, Optional


class GridBias:
    """A sum of Gaussians kept on a uniform grid over [lo, hi]."""

    def __init__(self, lo: float, hi: float, n: int):
        self.lo, self.hi, self.n = lo, hi, n
        self.dx = (hi - lo) / (n - 1)
        self.v = [0.0] * n
        self.d = [0.0] * n

    def deposit(self, center: float, height: float, sigma: float) -> None:
        for i in range(self.n):
            s = self.lo + i * self.dx
            g = height * math.exp(-0.5 * ((s - center) / sigma) ** 2)
            self.v[i] += g
            self.d[i] -= g * (s - center) / (sigma * sigma)

    def _cell(self, x: float):
        t = (x - self.lo) / self.dx
        i = min(max(int(t), 0), self.n - 2)
        return i, t - i

    def value(self, x: float) -> float:
        if x < self.lo or x > self.hi:
            return 0.0
        i, t = self._cell(x)
        h00 = (1 + 2 * t) * (1 - t) ** 2
        h10 = t * (1 - t) ** 2
        h01 = t * t * (3 - 2 * t)
        h11 = t * t * (t - 1)
        return (h00 * self.v[i] + h10 * self.dx * self.d[i]
                + h01 * self.v[i + 1] + h11 * self.dx * self.d[i + 1])

    def deriv(self, x: float) -> float:
        if x < self.lo or x > self.hi:
            return 0.0
        i, t = self._cell(x)
        g00 = 6 * t * (t - 1)
        g10 = (1 - t) * (1 - 3 * t)
        g01 = -g00
        g11 = t * (3 * t - 2)
        return (g00 * self.v[i] / self.dx + g10 * self.d[i]
                + g01 * self.v[i + 1] / self.dx + g11 * self.d[i + 1])


def metadynamics(du: Callable[[float], float], x0: float, kT: float, h: float, steps: int,
                 height: float, sigma: float, tau: int, rng,
                 bias_temp: Optional[float] = None,
                 grid: tuple = (-2.5, 2.5, 501)) -> tuple[GridBias, list[float]]:
    """Run metadynamics; bias_temp = k dT gives the well-tempered form, None the standard one.

    Returns the bias and the trajectory of x.
    """
    bias = GridBias(*grid)                                       # @line L1
    noise = math.sqrt(2.0 * kT * h)
    x, xs = x0, []
    for n in range(1, steps + 1):                                # @line L2
        x += -h * (du(x) + bias.deriv(x)) + noise * rng.gauss(0.0, 1.0)  # @line L3
        xs.append(x)
        if n % tau == 0:                                         # @line L4
            w = height
            if bias_temp is not None:
                w = height * math.exp(-bias.value(x) / bias_temp)  # @line L5
            bias.deposit(x, w, sigma)                            # @line L6
    return bias, xs


def free_energy_estimate(bias: GridBias, kT: float, bias_temp: Optional[float] = None) -> list[float]:
    """F on the grid, up to a constant: -V for standard, -((kT + k dT) / k dT) V for well-tempered."""
    factor = 1.0 if bias_temp is None else (kT + bias_temp) / bias_temp  # @line L7
    return [-factor * v for v in bias.v]                         # @line L7


def double_well(height: float):
    """U(x) = height (x^2 - 1)^2 and its derivative."""
    return (lambda x: height * (x * x - 1.0) ** 2,
            lambda x: 4.0 * height * x * (x * x - 1.0))
test_metadynamics.py 75 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/metadynamics/. The authors are listed in prov/EGQBSZ.jsonl.
import math
import random

import pytest

from metadynamics import GridBias, double_well, free_energy_estimate, metadynamics

U, DU = double_well(8.0)  # barrier of 8 kT at kT = 1
GRID = [-2.5 + 0.01 * i for i in range(501)]


def transitions(xs):
    """Well-to-well moves, counted only when x passes from below -0.5 to above 0.5 or back."""
    side, count = None, 0
    for x in xs:
        new = -1 if x < -0.5 else (1 if x > 0.5 else side)
        if side is not None and new != side:
            count += 1
        side = new
    return count


def test_grid_bias_matches_direct_sum_and_force_is_its_derivative():
    b = GridBias(-2.5, 2.5, 501)
    b.deposit(0.3, 1.0, 0.2)
    b.deposit(-0.4, 0.5, 0.3)

    def direct(x):
        return math.exp(-0.5 * ((x - 0.3) / 0.2) ** 2) + 0.5 * math.exp(-0.5 * ((x + 0.4) / 0.3) ** 2)

    xs = [-2.0 + 0.0137 * i for i in range(290)]
    assert max(abs(b.value(x) - direct(x)) for x in xs) < 1e-6
    fd = [(b.value(x + 1e-6) - b.value(x - 1e-6)) / 2e-6 for x in xs]
    assert max(abs(f - b.deriv(x)) for f, x in zip(fd, xs)) < 1e-7
    assert b.value(3.0) == 0.0 and b.deriv(-3.0) == 0.0


def test_plain_dynamics_rarely_crosses_but_metadynamics_does():
    _, plain = metadynamics(DU, -1.0, 1.0, 0.005, 10000, 0.0, 0.2, 10, random.Random(1))
    _, meta = metadynamics(DU, -1.0, 1.0, 0.005, 10000, 0.1, 0.2, 10, random.Random(1))
    assert transitions(plain) <= 2
    assert transitions(meta) >= 20


def test_standard_bias_volume_grows_without_bound():
    # Each Gaussian adds w sigma sqrt(2 pi) to the integral of V; nothing slows the growth.
    steps, w, sigma, tau = 10000, 0.1, 0.2, 10
    bias, xs = metadynamics(DU, -1.0, 1.0, 0.005, steps, w, sigma, tau, random.Random(2))
    assert max(abs(x) for x in xs) < 2.2
    volume = sum(bias.v) * bias.dx
    assert volume == pytest.approx(steps // tau * w * sigma * math.sqrt(2 * math.pi), rel=1e-3)


def test_well_tempered_estimate_scale_factor():
    b = GridBias(-1.0, 1.0, 3)
    b.v = [1.0, 2.0, 0.5]
    assert free_energy_estimate(b, 1.0) == [-1.0, -2.0, -0.5]
    assert free_energy_estimate(b, 1.0, 7.0) == pytest.approx([-8 / 7, -16 / 7, -4 / 7])


def test_well_tempered_profile_against_exact():
    bt = 7.0
    bias, _ = metadynamics(DU, -1.0, 1.0, 0.005, 80000, 0.1, 0.2, 10, random.Random(1), bias_temp=bt)
    f = free_energy_estimate(bias, 1.0, bt)
    idx = [i for i, s in enumerate(GRID) if U(s) < 5.0]
    off = sum(U(GRID[i]) - f[i] for i in idx) / len(idx)
    assert max(abs(f[i] + off - U(GRID[i])) for i in idx) < 0.8
    # grid points 150, 250 and 350 are x = -1, 0 and 1
    assert f[250] - f[350] == pytest.approx(8.0, abs=0.7)
    assert abs(f[150] - f[350]) < 0.5
    # The bias stays bounded: well below the standard bias after the same number of hills.
    std, _ = metadynamics(DU, -1.0, 1.0, 0.005, 80000, 0.1, 0.2, 10, random.Random(1))
    assert max(bias.v) < 0.8 * max(std.v)

History

Laio and Parrinello (2002) introduced metadynamics as a way to escape free energy minima, with a bias built from the history of the run in the space of a few collective variables. Barducci, Bussi and Parrinello (2008) made the hill height decrease with the bias and showed that the bias then settles to a scaled free energy. Dama, Parrinello and Voth (2014) proved that the well-tempered bias converges in the long-time limit. Laio and Gervasio (2008) review the method.

References

  1. Alessandro Laio and Michele Parrinello, Escaping free-energy minima, Proceedings of the National Academy of Sciences of the USA 99(20), 2002, 12562-12566, the history-dependent bias on collective variables and its use to explore and reconstruct the free energy
  2. Alessandro Barducci, Giovanni Bussi and Michele Parrinello, Well-tempered metadynamics, a smoothly converging and tunable free-energy method, Physical Review Letters 100, 020603, 2008, the hill height that decreases with the local bias, the convergence of the bias to a scaled free energy, and the effective temperature of the collective variables
  3. James F. Dama, Michele Parrinello and Gregory A. Voth, Well-tempered metadynamics converges asymptotically, Physical Review Letters 112, 240602, 2014, the proof that the well-tempered bias converges in the long-time limit

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