Algorithmresearch
BAOAB Langevin integrator
Also called BAOAB splitting.
Splits Langevin dynamics into kick, drift and exact Ornstein-Uhlenbeck steps in the order B A O A B, which gives very accurate configurational sampling.
- Time
- O(S N^2) worst
- Space
- O(N) extra
- Where
- N = the number of particles; S = the number of time steps
- Model
- Real RAM
- Properties
- randomizediterativerandomizedsymmetricnot symplectic
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Benedict Leimkuhler, Charles Matthews, 2013
BAOAB is an integrator for Langevin dynamics, the equations of motion with friction and random forces that sample the canonical ensemble. It splits the equations into three parts that can each be solved exactly: a kick B by the forces, a drift A of the positions, and an Ornstein-Uhlenbeck step O of the velocities, which holds the friction and the noise. It composes them in the order B A O A B, with the O step in the middle of the drift. Leimkuhler and Matthews (2013) showed that this order gives a much smaller error in averages of the positions than other orders at the same cost. On a harmonic oscillator the positions have the exact canonical law for every stable time step (a theorem).
In plain words
Langevin dynamics mixes three simple motions: atoms push each other, atoms move on, and the solvent slows them and knocks them at random. A program does the three motions one after another in small time steps, and the order matters.
BAOAB does half a push, half a move, then the slowing and knocking, then the other half of the move and the other half of the push. Doing the random part in the middle of the move turns out to make the positions of the atoms much more accurate. The speeds are less accurate in exchange, but for most questions, such as the shape of a molecule or the free energy of a state, the positions are what matter. It costs the same as other orders: one force computation per step.
The problem
The input is as for Langevin dynamics: positions , velocities and masses of particles, a force routine for , a time step , a number of steps , the target , the friction and a random number source. The equations are
The parts are B: , A: , and O: . The output is the trajectory and samples of , to be used for averages of functions of . The kinetic temperature uses , since the noise does not conserve momentum.
The algorithm
BAOAB(x, v, m, FORCES, h, S, kT, gamma)- 1
f ← FORCES(x); c ← exp(-gamma h) - 2
for step ← 1 to S do - 3
v_i ← v_i + (h / 2) f_i / m_i for each particle i ▷ B - 4
x_i ← x_i + (h / 2) v_i for each particle i ▷ A - 5
v_i ← c v_i + sqrt((1 - c²) kT / m_i) R_i for each particle i ▷ O, R_i standard normal in R^d - 6
x_i ← x_i + (h / 2) v_i for each particle i ▷ A - 7
f ← FORCES(x) - 8
v_i ← v_i + (h / 2) f_i / m_i for each particle i ▷ B - 9
every k steps, record a copy of (x, v) - 10
return (x, v, the recorded samples)
The forces from line L7 serve the kick on line L3 of the next step, so there is one force evaluation per step. Line L5 is the exact solution of the Ornstein-Uhlenbeck part over the full time . With , line L5 does nothing, the two drifts join, and the step is velocity Verlet. The OBABO splitting uses the same parts with the O step split in two at the ends.
Example
One step by hand. One particle on a spring with in reduced units, , , , , so and . With the normal draw on line L5:
| after | L3 | L4 | L5 | L6 | L8 |
|---|---|---|---|---|---|
| 1 | 0.9975 | 0.9975 | 1.005882 | 1.005882 | |
| 0.167637 | 0.167637 | 0.117343 |
Exact positions on a harmonic oscillator. For , and , the stationary law of BAOAB has exactly and , for any (a theorem, Claim 4 of the proof). A run of 50 oscillators with , 4000 steps from rest, a sample every 5 steps and the first 200 steps dropped (seed 1) gives:
| measured | exact | measured | exact | OBABO exact | |
|---|---|---|---|---|---|
| 0.5 | 0.9916 | 1 | 0.9335 | 0.9375 | 1.0667 |
| 1 | 0.9918 | 1 | 0.7510 | 0.75 | 1.3333 |
| 1.5 | 1.0039 | 1 | 0.4366 | 0.4375 | 2.2857 |
OBABO has the opposite behavior: exact velocities and wrong positions.
A quartic well. For in one dimension with , the canonical value is . 50 particles with , 8000 steps from rest, a sample every 5 steps and the first 500 steps dropped, averaged over seeds 1 to 5, with the standard error over the seeds:
| BAOAB | OBABO | |
|---|---|---|
| 0.1 | ||
| 0.2 | ||
| 0.3 | ||
| 0.4 |
These are measurements. The error of OBABO grows like , to 0.018 at . The error of BAOAB stays below 0.004 over this range. For this well, both are unstable near , since the force grows like .
Correctness
The proof in proofs/correctness.md shows:
- The parts are exact. Lines L3 and L8 are the flow of B, lines L4 and L6 the flow of A, and line L5 an exact draw from the flow of O.
- What each part keeps. O keeps the canonical density exactly. A and B keep the volume of phase space but not the density.
- The regrouped chain. Cut the step at line L5: the state there follows , which is position Verlet followed by O.
- The harmonic oscillator. The chain has a unique stationary law, it converges to it from any start, and the positions have the exact canonical variance.
- Limits. With the step is velocity Verlet.
For general smooth potentials, the error of BAOAB in averages of the positions is , and in the limit of high friction the leading term vanishes and the error is of order , as shown by Leimkuhler and Matthews (2013). That result is a theorem of the paper, under its assumptions; it is not proved on this page. So the method samples the canonical ensemble up to the time step error, and the error is smaller than for other splittings of the same cost.
Proof: Each BAOAB part is an exact flow, and for a harmonic force the positions have the exact canonical lawfull
We use the Langevin equations , and the pseudocode of the page.
Claim 1 (the parts). Line L3 and line L8 are the exact flow of with fixed. Lines L4 and L6 are the exact flow of with fixed. Line L5 is an exact draw from the flow of with fixed.
Proof. With fixed, is constant, so the kick is exact. With fixed, the drift is exact. The O flow over a time is with and standard normal (the Ornstein-Uhlenbeck solution, as on the Langevin dynamics page). Line L5 uses and the standard deviation computed before the loop. The force used in line L3 of a step was computed in line L7 of the step before, at the same positions, because nothing changes between them.
Claim 2 (what each part keeps). keeps the canonical density exactly. and keep the volume of phase space, but not .
Proof. keeps the Maxwell-Boltzmann law of ( times ) and does not touch . and are shears, with Jacobian determinant 1.
So BAOAB is not exact for a general force. The error in the configurational averages is in general. Leimkuhler and Matthews (2013) show that in the limit of large friction it becomes for BAOAB; this proof does not repeat that analysis. The next claim shows the effect in a case we can solve.
Claim 3 (the regrouped chain). Let be the state just before line L5 of step . Then with , read from right to left, and the state at the end of step is .
Proof. After line L5 of step the step applies (L6) and (L8). The next step applies (L3) and (L4) before its line L5. Two kicks at the same positions add up to .
is one step of position Verlet.
Claim 4 (the harmonic oscillator). Let in one dimension, , and . Then the chain of states at the ends of the steps has a unique stationary law, it converges to it from any start, and the law is normal with
So the positions have the exact canonical law for every stable .
Proof. Scale so that (put for ). Position Verlet is the linear map
with determinant 1. It keeps : the cross terms are , the coefficient of is , and the coefficient of is . So it keeps the normal law with density proportional to : and independent, , . keeps , since under the velocity is independent of with variance 1. So is stationary for .
It is the only stationary law. In the norm , position Verlet is an isometry and , the mean part of , is a contraction with only if . If , then and the velocity of is 0, which is , so . So , the spectral radius of is less than 1, and converges in law to .
Now push through (no change), then and :
Then , and .
The error is moved into the velocities, which have the variance of the right value. Velocity averages, such as the kinetic temperature, must therefore not be computed from at the end of a BAOAB step if the time step is large. For the velocity variance is of the right value.
Claim 5 (limits). With , and the noise is 0, so line L5 does nothing and the step is , velocity Verlet.
Complexity
Each step does one force evaluation, normal draws and other work. With the all-pairs forces of the molecular dynamics page, steps take time. The extra space is for the copies of and , plus the samples.
Properties
- Ensemble. Canonical (NVT) for the positions, up to a small time step error, for any .
- Accurate positions, less accurate velocities. On a harmonic oscillator the position law is exact and the velocity law at the end of a step is too narrow by the factor .
- Robust at high friction. As the method becomes a stable and accurate integrator of Brownian dynamics, where other splittings degrade.
- Dynamics. For small the motion is close to Newtonian, as for any Langevin integrator, and diffusion is slowed as grows.
- Cost. The same as velocity Verlet plus normal draws.
Variants and improvements
- Other orders. The five-letter words in A, B and O give a family of methods. ABOBA, OBABO and BAOAB are the symmetric ones studied by Leimkuhler and Matthews. OBABO, the splitting of Bussi and Parrinello, has exact velocities on the harmonic oscillator, and BAOAB has exact positions.
- The high friction limit. For with the time rescaled, BAOAB becomes the update , which averages two successive normal draws. It is a more accurate alternative to the Euler-Maruyama step of Brownian dynamics.
- Constraints. With bond constraints, the A step is followed by a projection, as in RATTLE and its geodesic variants.
- Exact sampling. A Metropolis test on top of a Langevin step removes the bias, as in the Metropolis-adjusted Langevin algorithm and generalized Hamiltonian Monte Carlo.
When to use it
Use BAOAB when the goal is configurational averages from Langevin dynamics: free energies, structures, distributions of collective variables. It allows larger time steps for the same accuracy, so it saves force evaluations. It is a good choice at high friction too. When velocity statistics or dynamical properties at large steps matter, use a different splitting or a smaller step.
Pitfalls
- The kinetic temperature from the end-of-step velocities. At large it is too low, as the example shows, even though the positions are right. Do not use it to judge the thermostat. On the harmonic oscillator the velocity just before line L5 has the right variance, so it is a better choice there.
- Unstable steps. The method needs for the fastest motion , as velocity Verlet does. Stiff bonds limit the step.
- The force at line L7. It serves line L3 of the next step. If something else moves the positions between steps, such as a barostat, compute the force again.
- Comparing integrators by the temperature. Compare them by configurational averages, such as the potential energy or a radial distribution function.
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/baoab-langevin-integrator/. The authors are listed in prov/V8MPCG.jsonl.
"""The BAOAB splitting for Langevin dynamics (Leimkuhler and Matthews 2013).
The Langevin equations for N particles in d dimensions are
dx_i = v_i dt,
m_i dv_i = f_i dt - m_i gamma v_i dt + sqrt(2 m_i gamma kT) dW_i.
The vector field is split into three parts, each solved exactly:
B: dv = (f / m) dt (kick, positions fixed)
A: dx = v dt (drift, velocities fixed)
O: dv = -gamma v dt + noise (Ornstein-Uhlenbeck, positions fixed)
One step of length h is B for h / 2, A for h / 2, O for h, A for h / 2 and
B for h / 2. The O step is v <- c v + sqrt((1 - c^2) kT / m) R with
c = exp(-gamma h) and R standard normal. The force after the second A part
is kept for the first B part of the next step, so there is one force
evaluation per step.
Cost: one force evaluation, N d normal draws and Theta(N d) extra work per
step.
"""
import math
import random
from typing import Callable
Vec = list[float]
ForceField = Callable[[list[Vec]], tuple[float, list[Vec]]]
def harmonic(k: float) -> ForceField:
"""Independent springs U = k |x_i|^2 / 2 for each particle."""
def field(pos: list[Vec]) -> tuple[float, list[Vec]]:
u = sum(0.5 * k * c * c for p in pos for c in p)
return u, [[-k * c for c in p] for p in pos]
return field
def quartic() -> ForceField:
"""Independent quartic wells U = |x_i|^4 / 4 for each particle (1D use)."""
def field(pos: list[Vec]) -> tuple[float, list[Vec]]:
u = sum(0.25 * c ** 4 for p in pos for c in p)
return u, [[-c ** 3 for c in p] for p in pos]
return field
def baoab(
x: list[Vec], v: list[Vec], m: list[float], forces: ForceField, h: float,
steps: int, kT: float, gamma: float, rng: random.Random, every: int = 1,
) -> tuple[list[Vec], list[Vec], list[tuple[list[Vec], list[Vec]]]]:
"""Run steps of BAOAB.
Returns the final positions and velocities, and copies of (x, v) after
every `every` steps. The inputs are not changed.
"""
if h <= 0 or gamma < 0 or kT <= 0 or every < 1:
raise ValueError("need h > 0, gamma >= 0, kT > 0 and every >= 1")
x = [list(p) for p in x]
v = [list(p) for p in v]
n = len(x)
c = math.exp(-gamma * h)
sd = [math.sqrt((1.0 - c * c) * kT / mi) for mi in m]
_, f = forces(x) # @line L1
samples = []
for step in range(1, steps + 1): # @line L2
for i in range(n):
for a in range(len(x[i])):
v[i][a] += 0.5 * h * f[i][a] / m[i] # @line L3
x[i][a] += 0.5 * h * v[i][a] # @line L4
v[i][a] = c * v[i][a] + sd[i] * rng.gauss(0.0, 1.0) # @line L5
x[i][a] += 0.5 * h * v[i][a] # @line L6
_, f = forces(x) # @line L7
for i in range(n):
for a in range(len(x[i])):
v[i][a] += 0.5 * h * f[i][a] / m[i] # @line L8
if step % every == 0: # @line L9
samples.append(([list(p) for p in x], [list(p) for p in v]))
return x, v, samples # @line L10
test_baoab_langevin_integrator.py 72 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/baoab-langevin-integrator/. The authors are listed in prov/V8MPCG.jsonl.
import math
import random
import pytest
from baoab_langevin_integrator import baoab, harmonic, quartic
def stationary_covariance(h, gamma, omega2=1.0, kT=1.0):
"""Exact stationary covariance of (x, v) for one BAOAB step on U = omega2 x^2 / 2.
Iterates S <- A S A^T + Q over the five linear parts of the step.
"""
c = math.exp(-gamma * h)
b = ([[1, 0], [-0.5 * h * omega2, 1]], [[0, 0], [0, 0]])
a = ([[1, 0.5 * h], [0, 1]], [[0, 0], [0, 0]])
o = ([[1, 0], [0, c]], [[0, 0], [0, (1 - c * c) * kT]])
s = [[0.0, 0.0], [0.0, 0.0]]
for _ in range(3000):
for mat, q in (b, a, o, a, b):
ms = [[sum(mat[i][k] * s[k][j] for k in range(2)) for j in range(2)] for i in range(2)]
s = [[sum(ms[i][k] * mat[j][k] for k in range(2)) + q[i][j] for j in range(2)] for i in range(2)]
return s
def moments(samples, n):
xx = sum(p[0] ** 2 for s in samples for p in s[0]) / (len(samples) * n)
vv = sum(p[0] ** 2 for s in samples for p in s[1]) / (len(samples) * n)
return xx, vv
@pytest.mark.parametrize("h", [0.5, 1.0, 1.5])
def test_harmonic_positions_are_exact_for_every_stable_step(h):
# BAOAB gives <x^2> = kT / k exactly for h omega < 2, and
# <v^2> = (kT / m)(1 - h^2 omega^2 / 4).
s = stationary_covariance(h, 1.0)
assert s[0][0] == pytest.approx(1.0, abs=1e-10)
assert s[1][1] == pytest.approx(1.0 - h * h / 4.0, abs=1e-10)
assert s[0][1] == pytest.approx(0.0, abs=1e-10)
def test_harmonic_samples_match_the_exact_law():
n, h = 50, 1.0
rng = random.Random(1)
_, _, samples = baoab([[0.0]] * n, [[0.0]] * n, [1.0] * n, harmonic(1.0), h, 1200, 1.0, 1.0, rng, every=5)
xx, vv = moments(samples[20:], n)
assert xx == pytest.approx(1.0, rel=0.06)
assert vv == pytest.approx(0.75, rel=0.06)
def test_quartic_well_position_moment_is_close_to_canonical():
# Canonical <x^2> for U = x^4 / 4 at kT = 1 is 2 Gamma(3/4) / Gamma(1/4).
exact = 2 * math.gamma(0.75) / math.gamma(0.25)
assert exact == pytest.approx(0.67598, abs=1e-5)
n = 50
rng = random.Random(1)
_, _, samples = baoab([[0.0]] * n, [[0.0]] * n, [1.0] * n, quartic(), 0.3, 1500, 1.0, 1.0, rng, every=5)
xx, _ = moments(samples[20:], n)
assert xx == pytest.approx(exact, rel=0.04)
def test_zero_friction_is_velocity_verlet_and_conserves_energy():
x, v, _ = baoab([[1.0]], [[0.0]], [1.0], harmonic(1.0), 0.05, 200, 1.0, 0.0, random.Random(0))
assert 0.5 * v[0][0] ** 2 + 0.5 * x[0][0] ** 2 == pytest.approx(0.5, abs=1e-3)
assert x[0][0] == pytest.approx(math.cos(10.0), abs=0.01)
def test_bad_arguments_raise():
with pytest.raises(ValueError):
baoab([[1.0]], [[0.0]], [1.0], harmonic(1.0), 0.0, 1, 1.0, 1.0, random.Random(0))
History
Splittings of Langevin dynamics with an exact Ornstein-Uhlenbeck part were used by Bussi and Parrinello (2007), in the order OBABO. Leimkuhler and Matthews (2013) studied the error of the invariant measure for all symmetric orders of the A, B and O parts and found the order B A O A B best for configurational averages, with a fourth order error in the high friction limit. Leimkuhler, Matthews and Stoltz (2016) gave error expansions for equilibrium and nonequilibrium averages. Integrators based on BAOAB are available in several molecular dynamics codes.
References
- Benedict Leimkuhler and Charles Matthews, Rational construction of stochastic numerical methods for molecular sampling, Applied Mathematics Research eXpress 2013(1), 2013, 34-56, the splittings of Langevin dynamics into A, B and O parts, the error of their invariant measures, and the high friction limit of BAOAB
- Benedict Leimkuhler, Charles Matthews and Gabriel Stoltz, The computation of averages from equilibrium and nonequilibrium Langevin molecular dynamics, IMA Journal of Numerical Analysis 36(1), 2016, 13-79, the error expansions of averages for splitting methods of Langevin dynamics
- Ben Leimkuhler and Charles Matthews, Molecular Dynamics, With Deterministic and Stochastic Numerical Methods, Springer, 2015, Chapter 7, numerical methods for stochastic molecular dynamics
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 V8MPCG Edit this page History Report an error Markdown