Algorithmcore
Langevin dynamics
Also called Langevin thermostat.
Adds friction and a matching random force to Newton's equations so that the dynamics samples the canonical ensemble.
- 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
- Paul Langevin, 1908
Langevin dynamics adds two forces to Newton's equations of motion: a friction force that slows each particle down, and a random force that kicks it. The size of the random force is tied to the friction and the temperature, so that the canonical ensemble at that temperature is the stationary distribution (a theorem). In molecular dynamics it is a thermostat, often called the Langevin thermostat. In physics and chemistry it is also a model of a particle in a solvent: the solvent molecules are not simulated, and their effect is the friction and the random kicks. The page gives the equations and the OBABO integrator of Bussi and Parrinello (2007), which solves the friction and noise part exactly.
In plain words
Picture a ball moving among many small, fast molecules that are too many to simulate. They slow the ball down, like a thick fluid, and they also give it small random knocks.
Langevin dynamics adds exactly these two effects to each atom. The slowing down takes energy away and the knocks put energy in. When the two are matched to the temperature, they balance on average, and the atoms visit their states with the right weights for that temperature.
The program alternates a short step of ordinary motion with a step of slowing and knocking. The slowing and knocking part is solved exactly, so its size does not limit the time step.
The problem
The input is positions , velocities and masses of particles, a force routine for , a time step , a number of steps , the target , the friction coefficient (a rate, with units of inverse time) and a random number source. The Langevin equations are
with independent Wiener processes in . The amplitude of the noise follows from the fluctuation-dissipation relation, and with it the canonical density is stationary. The output is the trajectory and samples of . The noise and the friction act on each particle against a fixed background, so the total momentum is not conserved: for the kinetic temperature , use , less one for each constraint.
The algorithm
LANGEVIN-OBABO(x, v, m, FORCES, h, S, kT, gamma)- 1
f ← FORCES(x); c ← exp(-gamma h / 2) - 2
for step ← 1 to S do - 3
v_i ← c v_i + sqrt((1 - c²) kT / m_i) R_i for each particle i ▷ O: exact half step, R_i standard normal in R^d - 4
v_i ← v_i + (h / 2) f_i / m_i for each particle i ▷ B: half kick - 5
x_i ← x_i + h v_i for each particle i ▷ A: drift - 6
f ← FORCES(x) - 7
v_i ← v_i + (h / 2) f_i / m_i for each particle i ▷ B: half kick - 8
v_i ← c v_i + sqrt((1 - c²) kT / m_i) R_i for each particle i ▷ O: exact half step, fresh R_i - 9
every k steps, record a copy of (x, v) - 10
return (x, v, the recorded samples)
The friction and the noise alone form an Ornstein-Uhlenbeck process in , and lines L3 and L8 are its exact solution over a time . Lines L4 to L7 are a velocity Verlet step. The letters name the parts: O for Ornstein-Uhlenbeck, B for the kick and A for the drift, so the step is O B A B O. With it is velocity Verlet. The order B A O A B is the BAOAB integrator, which samples positions more accurately.
Example
One step by hand. One particle on a spring with in reduced units, , , and . Then and . With the normal draws on line L3 and on line L8:
| after | L3 | L4 | L5 | L7 | L8 |
|---|---|---|---|---|---|
| 1 | 1 | 1.010424 | 1.010424 | 1.010424 | |
| 0.154242 | 0.104242 | 0.104242 | 0.053721 |
The time step error on a harmonic oscillator. For with and , the stationary law of OBABO is normal with 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 | |
|---|---|---|---|
| 0.5 | 1.0719 | 1.0667 | 0.9914 |
| 1 | 1.3193 | 1.3333 | 0.9994 |
| 1.5 | 2.2885 | 2.2857 | 0.9971 |
The canonical values are 1 and 1. The velocities are right for any step, and the positions carry an error, which BAOAB removes for this example.
Correctness
The proof in proofs/correctness.md shows:
- The canonical density is stationary for the Fokker-Planck equation of the Langevin equations: the Hamiltonian part and the friction and noise part each keep it.
- The O step is exact. Lines L3 and L8 draw the Ornstein-Uhlenbeck solution over a time , which keeps the Maxwell law of exactly.
- The step is O around velocity Verlet, so it keeps the canonical law up to the error of the Verlet part.
- On a harmonic oscillator the stationary law of the step is the normal law above, and it is unique.
- Limits. With the step is velocity Verlet. With no forces the velocities are an exact sample path of the Ornstein-Uhlenbeck process.
For and a smooth potential that grows at infinity, the continuous Langevin process is ergodic, since the noise reaches all variables through the coupling of and (a theorem). So unlike the Nose-Hoover thermostat, Langevin dynamics needs no hypothesis of ergodicity.
Proof: The Langevin equation keeps the canonical density, and the OBABO step keeps the velocity law exactlyfull
The Langevin equations for particles in dimensions are
with , and independent Wiener processes . Let with .
Claim 1 (the canonical density is stationary). is a stationary solution of the Fokker-Planck equation of (1).
Proof. The Fokker-Planck operator is . The Hamiltonian part is 0 for any function of , since . The friction and noise part is
and for the bracket is , because .
The size of the noise is fixed by the friction: with any other factor than the bracket does not vanish. This is the fluctuation-dissipation relation. For and a smooth that grows at infinity, is also the unique stationary law and time averages converge to canonical averages (the noise reaches all velocities and the forces couple them to the positions). We do not prove this part here.
Claim 2 (the exact O step). The solution of over a time is
with standard normal and independent of . Lines L3 and L8 apply it with .
Proof. . The integral is normal with mean 0 and variance , so the noise term has variance .
So the O step keeps the Maxwell-Boltzmann law exactly: if is normal with variance , then is normal with variance . It does not change , so it keeps exactly, for every .
Claim 3 (the step). One step is , the O half steps around a velocity Verlet step. The O parts keep exactly. The Verlet part keeps the volume of phase space and keeps up to , so it keeps only up to the time step error.
Proof. Lines L4 to L7 are velocity Verlet, as on the molecular dynamics page; Claim 2 covers L3 and L8.
Claim 4 (the harmonic oscillator). Let , , , and . Then the stationary law of the OBABO chain is normal, with and independent,
and the chain converges to it from any start.
Proof. Scale so that (put for ). One velocity Verlet step is the linear map
It keeps : the cross terms are , the coefficient of is , and the coefficient of is . Its determinant is 1. So it keeps the normal law with density proportional to , which has , and no correlation. The O step keeps by Claim 2, since under the velocity is independent of with variance 1. So is stationary.
For uniqueness, the chain is with independent normal and , where and is the Verlet map. In the norm , is an isometry and is a contraction, with only if . If , then , so , and , so , so . So for , by compactness of the unit sphere, and the law of converges to the unique stationary law.
So the velocities have the right variance for every stable , and the positions have an error of relative size . For the position variance is of the right value. The tests compute both values by iteration of the covariance and by sampling.
Claim 5 (limits). With , , the O steps do nothing, and the step is velocity Verlet. With , the Verlet part does not change , so the velocities at the step times follow : they are an exact sample path of the Ornstein-Uhlenbeck process, with correlation between consecutive steps.
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; with neighbor lists the forces take per step. The extra space is for the copies of and , plus the samples that are recorded.
Properties
- Ensemble. Canonical (NVT), up to the time step error, for any . Ergodicity holds without an extra hypothesis.
- Local. Each particle has its own friction and noise, so the thermostat works on small, stiff and harmonic systems and on systems with hot spots.
- Dynamics are changed. The friction slows diffusion: a free particle has the diffusion constant (a theorem), and in a liquid a small changes little while a large one makes it much smaller. Momentum is not conserved, so hydrodynamic correlations are damped.
- Exact velocity distribution on a harmonic oscillator for any step, as in the example.
- Time-symmetric splitting, but not reversible as a deterministic map, since fresh noise is drawn.
Variants and improvements
- BAOAB. The BAOAB integrator uses the same parts in the order B A O A B and has a much smaller error in configurational averages, in particular for large friction.
- Overdamped limit. For large the velocities relax at once, and the motion of positions alone is Brownian dynamics.
- Older integrators. Schneider and Stoll (1978), van Gunsteren and Berendsen (1982) and Brunger, Brooks and Karplus (1984) gave earlier schemes. A direct Euler-Maruyama step is simple but has a larger error and no exact O part.
- Momentum-conserving noise. Dissipative particle dynamics puts friction and noise on pairs of particles, so momentum is conserved and hydrodynamics survive.
- Global thermostats. Stochastic velocity rescaling acts on the total kinetic energy only and changes the dynamics less.
- Sampling. In statistics, the Metropolis-adjusted Langevin algorithm uses the overdamped Langevin equation as a proposal and removes the time step error with an accept-reject step.
When to use it
Use Langevin dynamics when the goal is to sample the canonical ensemble robustly, for example for free energies, structure and equilibrium averages, or to model a solute in an implicit solvent. A common heuristic is a small , about in atomistic simulation, when dynamics matter, and a larger one when only sampling matters. Avoid it when transport properties such as viscosity or diffusion constants are measured in an explicit solvent, where a global thermostat changes them less.
Pitfalls
- Too large a friction. The dynamics then crawl, and sampling of slow motions gets slower, not faster.
- The same random numbers in every run. Restarts with the same seed repeat the noise, and parallel copies with one seed are correlated.
- A wrong . Momentum is not conserved, so do not subtract for the centre of mass when the kinetic temperature is computed.
- Units of . Some codes give a friction per mass, others a collision frequency, others a damping time . Check which.
- Judging the step by the velocities. The kinetic temperature is right even when the step is too large; check configurational quantities such as or the potential energy.
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/langevin-dynamics/. The authors are listed in prov/YHB5S5.jsonl.
"""Langevin dynamics with the Bussi-Parrinello (OBABO) integrator.
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,
with the friction coefficient gamma, the temperature kT and independent
Wiener processes W_i. The canonical density exp(-(K + U) / kT) is invariant.
One step of length h is the splitting of Bussi and Parrinello (2007): an
exact Ornstein-Uhlenbeck half step of the velocities (friction and noise
only), a velocity Verlet step, and a second exact Ornstein-Uhlenbeck half
step. The exact half step is
v <- c v + sqrt((1 - c^2) kT / m) R, c = exp(-gamma h / 2),
with R standard normal. With gamma = 0 the step is velocity Verlet. With no
forces the velocities are an exact sample path of the Ornstein-Uhlenbeck
process at the step times.
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 free() -> ForceField:
"""No forces: U = 0 and f = 0."""
def field(pos: list[Vec]) -> tuple[float, list[Vec]]:
return 0.0, [[0.0] * len(p) for p in pos]
return field
def _ou_half(v, m, c, kT, rng):
"""Exact Ornstein-Uhlenbeck flow of the velocities over a time h / 2."""
for i, vi in enumerate(v):
s = math.sqrt((1.0 - c * c) * kT / m[i])
for a in range(len(vi)):
vi[a] = c * vi[a] + s * rng.gauss(0.0, 1.0)
def langevin_dynamics(
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 Langevin dynamics with the OBABO splitting.
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(-0.5 * gamma * h)
_, f = forces(x) # @line L1
samples = []
for step in range(1, steps + 1): # @line L2
_ou_half(v, m, c, kT, rng) # @line L3
for i in range(n):
for a in range(len(x[i])):
v[i][a] += 0.5 * h * f[i][a] / m[i] # @line L4
x[i][a] += h * v[i][a] # @line L5
_, f = forces(x) # @line L6
for i in range(n):
for a in range(len(x[i])):
v[i][a] += 0.5 * h * f[i][a] / m[i] # @line L7
_ou_half(v, m, c, kT, rng) # @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_langevin_dynamics.py 80 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/langevin-dynamics/. The authors are listed in prov/YHB5S5.jsonl.
import math
import random
import pytest
from langevin_dynamics import free, harmonic, langevin_dynamics
def stationary_covariance(h, gamma, omega2=1.0, kT=1.0):
"""Exact stationary covariance of (x, v) for one OBABO 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(-0.5 * gamma * h)
o = ([[1, 0], [0, c]], [[0, 0], [0, (1 - c * c) * kT]])
b = ([[1, 0], [-0.5 * h * omega2, 1]], [[0, 0], [0, 0]])
a = ([[1, h], [0, 1]], [[0, 0], [0, 0]])
s = [[0.0, 0.0], [0.0, 0.0]]
for _ in range(3000):
for mat, q in (o, b, a, b, o):
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
def test_harmonic_oscillator_matches_exact_discrete_stationary_law():
# OBABO keeps <v^2> = kT / m exactly and gives <x^2> = (kT / k) / (1 - h^2 omega^2 / 4).
h = 1.0
s = stationary_covariance(h, 1.0)
assert s[1][1] == pytest.approx(1.0, abs=1e-12)
assert s[0][0] == pytest.approx(1.0 / (1.0 - h * h / 4.0), abs=1e-12)
n = 50
rng = random.Random(1)
_, _, samples = langevin_dynamics([[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(s[0][0], rel=0.05)
assert vv == pytest.approx(s[1][1], rel=0.05)
def test_small_step_approaches_canonical_values():
h = 0.1
s = stationary_covariance(h, 2.0)
assert s[0][0] == pytest.approx(1.0, abs=0.003)
n = 50
rng = random.Random(2)
_, _, samples = langevin_dynamics([[0.0]] * n, [[0.0]] * n, [1.0] * n, harmonic(1.0), h, 1500, 1.0, 2.0, rng, every=10)
xx, vv = moments(samples[10:], n)
assert xx == pytest.approx(1.0, rel=0.1)
assert vv == pytest.approx(1.0, rel=0.1)
def test_free_particle_velocities_are_an_ornstein_uhlenbeck_process():
# With no forces one step maps v to exp(-gamma h) v + noise, exactly.
n, h, gamma = 500, 0.5, 1.0
rng = random.Random(3)
v0 = [[rng.gauss(0.0, 1.0)] for _ in range(n)]
_, v1, _ = langevin_dynamics([[0.0]] * n, v0, [1.0] * n, free(), h, 1, 1.0, gamma, rng)
cov = sum(a[0] * b[0] for a, b in zip(v0, v1)) / n
var1 = sum(b[0] ** 2 for b in v1) / n
assert cov == pytest.approx(math.exp(-gamma * h), abs=0.15)
assert var1 == pytest.approx(1.0, abs=0.25)
def test_zero_friction_is_velocity_verlet():
x, v, _ = langevin_dynamics([[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):
langevin_dynamics([[1.0]], [[0.0]], [1.0], harmonic(1.0), 0.05, 1, 1.0, -1.0, random.Random(0))
History
Langevin (1908) wrote the equation of a Brownian particle as Newton's law with friction and a random force. Its use as a numerical method in molecular simulation came much later: Schneider and Stoll (1978) used it for phase transitions, and van Gunsteren and Berendsen (1982) and Brunger, Brooks and Karplus (1984) gave integrators for molecules. Bussi and Parrinello (2007) gave the splitting with exact Ornstein-Uhlenbeck half steps used here. Leimkuhler and Matthews (2013) studied the order of the parts and found the more accurate BAOAB.
References
- Giovanni Bussi and Michele Parrinello, Accurate sampling using Langevin dynamics, Physical Review E 75, 056707, 2007, the splitting with exact Ornstein-Uhlenbeck half steps around velocity Verlet and the effective energy
- Ben Leimkuhler and Charles Matthews, Molecular Dynamics, With Deterministic and Stochastic Numerical Methods, Springer, 2015, Chapter 6, the canonical distribution and stochastic differential equations, and Chapter 7, numerical methods for stochastic molecular dynamics
- Michael P. Allen and Dominic J. Tildesley, Computer Simulation of Liquids, second edition, Oxford University Press, 2017, the chapter on mesoscale methods, Langevin and Brownian dynamics
- Mark E. Tuckerman, Statistical Mechanics, Theory and Molecular Simulation, Oxford University Press, 2010, the chapter on the Langevin and generalized Langevin equations
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.
| 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 YHB5S5 Edit this page History Report an error Markdown