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
- Model
- Real RAM
- Properties
- not consistentrandomizediterativerandomizednot unbiased
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Alessandro Laio, Michele Parrinello, 2002
Metadynamics computes a free energy surface along a few collective variables by building a bias during the run. Every steps it adds a small Gaussian hill of width to a bias at the current value of . 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 , and at long times follows the free energy 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 , the hills shrink as the bias grows, and the bias converges to up to a constant (Dama, Parrinello and Voth 2014), so .
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 , a collective variable , the temperature , a dynamics that samples with , and the hill parameters , , , and for the well-tempered form. The target is the free energy profile
of the marginal of in the canonical ensemble. The output is the bias on a grid and the estimate of 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
METADYNAMICS(U, s, x_0, kT, h, steps, w, sigma, tau, k dT)- 1
V ← 0 on a grid of s - 2
for n ← 1 to steps do - 3
x ← x - h (U'(x) + V'(s(x)) s'(x)) + sqrt(2 kT h) xi ▷ xi ~ N(0, 1) - 4
if n mod tau = 0 then - 5
height ← w (standard) or w exp(-V(s(x)) / k dT) (well-tempered) - 6
V(s') ← V(s') + height exp(-(s' - s(x))^2 / (2 sigma^2)) on the grid - 7
return 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 ; molecular dynamics with a thermostat is the usual choice in practice. Line L6 keeps 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 . Line L7 rescales the well-tempered bias by the bias factor. The ratio is called the bias factor, and the collective variable is sampled as if at the higher temperature (Claim 2 of the proof).
Example
Take , , , so with minima at and a barrier of . Use , , and , start at , and count a transition each time passes from below to above 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 after the best constant shift:
| form | largest value of | largest error | barrier | asymmetry |
|---|---|---|---|---|
| well-tempered, | 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 , 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 it was 0.42 to 0.74 at 80000 steps. The grid bias agreed with the direct sum of all hills to , and its force with a finite difference to .
Correctness
The proof in proofs/correctness.md shows:
- The standard bias grows without bound. With constant heights, the integral of over the whole line equals the number of hills times , so cannot converge.
- The fixed shape of the bias. In the limit of slow deposition and narrow hills, the deposition rate is uniform in exactly when ; then is distributed as . The limit gives the standard form with and a flat distribution of , and gives no bias.
- The constant grows like a logarithm. In the same limit the well-tempered constant grows like , so the hill heights decay like .
- 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 for grid spacing .
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 be one collective variable, its free energy at inverse temperature , and the bias after hills. Hill is centred at , the value of at the time of deposit, and has height and width :
Claim 1 (the standard bias grows without bound). With , for every trajectory. If all centres lie in an interval , then , where for any . So grows at least linearly in . Since is nondecreasing in at every , it does not converge to a bounded function, and it does not converge in .
Proof. Each Gaussian has integral ; sum over . For a centre in , the mass of its Gaussian outside is at most the mass outside , which is the fraction . So the integral of over the interval , of length , is at least , and the maximum is at least this integral divided by the length.
Thus in standard metadynamics can follow only up to a constant that grows with , 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 under ,
and the hills are narrow, so each hill adds mass at . Then the expected change of per hill is
Claim 2 (the fixed shape). In the quasi-static model, the rate is the same at every if and only if
for a constant . For the well-tempered shape, : is sampled as if at temperature . For the standard shape, is uniform.
Proof. The rate is uniform if and only if does not depend on . For the standard form this reads . For the well-tempered form it reads ; multiply by to get . Then , so , which gives the density.
As the well-tempered shape tends to the standard one and ; as the factor tends to 0, which is no bias. Line L7 of the algorithm inverts the well-tempered shape: , and , the factor of the code.
The fixed shape attracts in this model. Write with the shape of Claim 2. Then with (or for the standard form) and independent of . So where is larger it grows more slowly, and the difference moves towards 0.
Claim 3 (the constant grows like a logarithm). In the quasi-static model with the well-tempered shape , there is with , so
which grows like , and the hill heights decay like . For the standard form is a positive constant, so grows linearly, as in Claim 1.
Proof. , so does not depend on . Then , and by Claim 2 the last product is a positive constant; call its product with . Solve the separable equation: . The heights are , and . For the standard form, with uniform.
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 , and let the code store at each node the exact value and slope of the sum of hills. On each cell the code returns the cubic Hermite interpolant of these values and slopes, and its derivative as the force. Then is continuously differentiable on , is exactly its derivative, and
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 , with the Hermite basis , , , . Their -derivatives are , , and , and the chain rule divides by ; these are the expressions of the code. At and , and 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, for some in the cell, with .
For a Gaussian of width , per hill, so with and the relative error is below per hill, which agrees with the measured on the page. Outside 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 and for the grid bias. Each of the hills costs to add on a grid of points, or less if only the points within a few are updated. So the time is and the extra space is . Without a grid, each step must sum all hills so far, which costs 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. follows up to fluctuations of order of the hill size, and the bias grows without bound.
- Well-tempered form converges to up to a constant, and the hills shrink like .
- Tunable. sets how far the bias flattens the surface: the barrier seen by is divided by the bias factor .
- 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 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 , 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 .
- 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 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.
# 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
- 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
- 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
- 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.
| 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 EGQBSZ Edit this page History Report an error Markdown