Algorithm Search⌘K

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
Properties
randomizediterativerandomizedsymmetricnot symplectic
Origin
Paul Langevin, 1908

Langevin dynamics adds two forces to Newton's equations of motion: a friction force −mγv-m\gamma v 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 xi∈Rdx_i \in \mathbb{R}^d, velocities viv_i and masses mim_i of NN particles, a force routine for fi=−∇iUf_i = -\nabla_i U, a time step hh, a number of steps SS, the target kBTk_B T, the friction coefficient γ≥0\gamma \ge 0 (a rate, with units of inverse time) and a random number source. The Langevin equations are

dxi=vi dt,mi dvi=fi dt−miγvi dt+2miγkBT dWi,dx_i = v_i\, dt, \qquad m_i\, dv_i = f_i\, dt - m_i \gamma v_i\, dt + \sqrt{2 m_i \gamma k_B T}\, dW_i,

with independent Wiener processes WiW_i in Rd\mathbb{R}^d. The amplitude of the noise follows from the fluctuation-dissipation relation, and with it the canonical density exp⁡(−(K+U)/kBT)\exp(-(K + U)/k_B T) is stationary. The output is the trajectory and samples of (x,v)(x, v). The noise and the friction act on each particle against a fixed background, so the total momentum is not conserved: for the kinetic temperature T=2K/(NfkB)T = 2K / (N_f k_B), use Nf=dNN_f = dN, less one for each constraint.

The algorithm

  1. LANGEVIN-OBABO(x, v, m, FORCES, h, S, kT, gamma)
  2. 1f ← FORCES(x); c ← exp(-gamma h / 2)
  3. 2for step ← 1 to S do
  4. 3v_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
  5. 4v_i ← v_i + (h / 2) f_i / m_i for each particle i ▷ B: half kick
  6. 5x_i ← x_i + h v_i for each particle i ▷ A: drift
  7. 6f ← FORCES(x)
  8. 7v_i ← v_i + (h / 2) f_i / m_i for each particle i ▷ B: half kick
  9. 8v_i ← c v_i + sqrt((1 - c²) kT / m_i) R_i for each particle i ▷ O: exact half step, fresh R_i
  10. 9every k steps, record a copy of (x, v)
  11. 10return (x, v, the recorded samples)

The friction and the noise alone form an Ornstein-Uhlenbeck process in vv, and lines L3 and L8 are its exact solution over a time h/2h/2. 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 γ=0\gamma = 0 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 m=k=kBT=1m = k = k_B T = 1 in reduced units, x=1x = 1, v=0v = 0, h=0.1h = 0.1 and γ=1\gamma = 1. Then c=e−0.05=0.951229c = e^{-0.05} = 0.951229 and 1−c2=0.308484\sqrt{1 - c^2} = 0.308484. With the normal draws R=0.5R = 0.5 on line L3 and R=−0.3R = -0.3 on line L8:

after L3 L4 L5 L7 L8
xx 1 1 1.010424 1.010424 1.010424
vv 0.154242 0.104242 0.104242 0.053721 −0.041444-0.041444

The time step error on a harmonic oscillator. For U=12kx2U = \frac12 k x^2 with ω2=k/m\omega^2 = k/m and hω<2h\omega < 2, the stationary law of OBABO is normal with ⟨v2⟩=kBT/m\langle v^2 \rangle = k_B T / m exactly and ⟨x2⟩=(kBT/k)/(1−h2ω2/4)\langle x^2 \rangle = (k_B T / k) / (1 - h^2\omega^2 / 4), for any γ>0\gamma > 0 (a theorem, Claim 4 of the proof). A run of 50 oscillators with m=k=kBT=γ=1m = k = k_B T = \gamma = 1, 4000 steps from rest, a sample every 5 steps and the first 200 steps dropped (seed 1) gives:

hh measured ⟨x2⟩\langle x^2 \rangle exact ⟨x2⟩\langle x^2 \rangle measured ⟨v2⟩\langle v^2 \rangle
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 O(h2)O(h^2) error, which BAOAB removes for this example.

Correctness

The proof in proofs/correctness.md shows:

  1. 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.
  2. The O step is exact. Lines L3 and L8 draw the Ornstein-Uhlenbeck solution over a time h/2h/2, which keeps the Maxwell law of vv exactly.
  3. The step is O around velocity Verlet, so it keeps the canonical law up to the O(h2)O(h^2) error of the Verlet part.
  4. On a harmonic oscillator the stationary law of the step is the normal law above, and it is unique.
  5. Limits. With γ=0\gamma = 0 the step is velocity Verlet. With no forces the velocities are an exact sample path of the Ornstein-Uhlenbeck process.

For γ>0\gamma > 0 and a smooth potential that grows at infinity, the continuous Langevin process is ergodic, since the noise reaches all variables through the coupling of xx and vv (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 NN particles in dd dimensions are

dxi=vi dt,mi dvi=fi(x) dt−miγvi dt+2miγkBT dWi,(1)dx_i = v_i\,dt, \qquad m_i\,dv_i = f_i(x)\,dt - m_i \gamma v_i\,dt + \sqrt{2 m_i \gamma k_B T}\,dW_i, \qquad (1)

with f=−∇Uf = -\nabla U, γ≥0\gamma \ge 0 and independent Wiener processes WiW_i. Let ρ(x,v)∝exp⁡(−β(K+U))\rho(x, v) \propto \exp(-\beta(K + U)) with β=1/(kBT)\beta = 1/(k_B T).

Claim 1 (the canonical density is stationary). ρ\rho is a stationary solution of the Fokker-Planck equation of (1).

Proof. The Fokker-Planck operator is L∗=LH∗+LO∗\mathcal{L}^* = \mathcal{L}^*_H + \mathcal{L}^*_O. The Hamiltonian part LH∗ρ=−∑i(vi⋅∇xiρ+fimi⋅∇viρ)\mathcal{L}^*_H \rho = -\sum_i \bigl( v_i \cdot \nabla_{x_i} \rho + \frac{f_i}{m_i} \cdot \nabla_{v_i} \rho \bigr) is 0 for any function of H=K+UH = K + U, since vi⋅∇xiH+fimi⋅mivi=vi⋅(−fi)+fi⋅vi=0v_i \cdot \nabla_{x_i} H + \frac{f_i}{m_i} \cdot m_i v_i = v_i \cdot (-f_i) + f_i \cdot v_i = 0. The friction and noise part is

LO∗ρ=∑i,a∂via(γviaρ+γkBTmi∂viaρ),\mathcal{L}^*_O \rho = \sum_{i,a} \partial_{v_{ia}} \Bigl( \gamma v_{ia} \rho + \frac{\gamma k_B T}{m_i} \partial_{v_{ia}} \rho \Bigr),

and for ρ\rho the bracket is γviaρ−γviaρ=0\gamma v_{ia} \rho - \gamma v_{ia} \rho = 0, because ∂viaρ=−βmiviaρ\partial_{v_{ia}} \rho = -\beta m_i v_{ia} \rho. □\square

The size of the noise is fixed by the friction: with any other factor than 2miγkBT2 m_i \gamma k_B T the bracket does not vanish. This is the fluctuation-dissipation relation. For γ>0\gamma > 0 and a smooth UU that grows at infinity, ρ\rho 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 dv=−γv dt+2γkBT/m dWdv = -\gamma v\,dt + \sqrt{2\gamma k_B T / m}\,dW over a time tt is

v(t)=c v(0)+(1−c2) kBT/m  R,c=e−γt,v(t) = c\,v(0) + \sqrt{(1 - c^2)\,k_B T / m}\;R, \qquad c = e^{-\gamma t},

with RR standard normal and independent of v(0)v(0). Lines L3 and L8 apply it with t=h/2t = h/2.

Proof. v(t)=e−γtv(0)+2γkBT/m∫0te−γ(t−s) dWsv(t) = e^{-\gamma t} v(0) + \sqrt{2\gamma k_B T/m} \int_0^t e^{-\gamma(t - s)}\,dW_s. The integral is normal with mean 0 and variance ∫0te−2γ(t−s)ds=(1−c2)/(2γ)\int_0^t e^{-2\gamma(t-s)} ds = (1 - c^2)/(2\gamma), so the noise term has variance (1−c2)kBT/m(1 - c^2) k_B T / m. □\square

So the O step keeps the Maxwell-Boltzmann law exactly: if v(0)v(0) is normal with variance kBT/mk_B T/m, then v(t)v(t) is normal with variance c2kBT/m+(1−c2)kBT/m=kBT/mc^2 k_B T/m + (1 - c^2) k_B T/m = k_B T/m. It does not change xx, so it keeps ρ\rho exactly, for every hh.

Claim 3 (the step). One step is Oh/2∘Vh/2∘Ah∘Vh/2∘Oh/2O_{h/2} \circ V_{h/2} \circ A_h \circ V_{h/2} \circ O_{h/2}, the O half steps around a velocity Verlet step. The O parts keep ρ\rho exactly. The Verlet part keeps the volume of phase space and keeps HH up to O(h2)O(h^2), so it keeps ρ\rho 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. □\square

Claim 4 (the harmonic oscillator). Let d=N=1d = N = 1, U=12kx2U = \frac12 k x^2, ω2=k/m\omega^2 = k/m, q=h2ω2/4<1q = h^2\omega^2/4 < 1 and γ>0\gamma > 0. Then the stationary law of the OBABO chain is normal, with xx and vv independent,

⟨v2⟩=kBTm,⟨x2⟩=kBTk 11−q,\langle v^2 \rangle = \frac{k_B T}{m}, \qquad \langle x^2 \rangle = \frac{k_B T}{k}\,\frac{1}{1 - q},

and the chain converges to it from any start.

Proof. Scale so that m=ω=kBT=1m = \omega = k_B T = 1 (put hωh\omega for hh). One velocity Verlet step is the linear map

x′=ax+hv,v′=av−h(1−q)x,a=1−h2/2.x' = a x + h v, \qquad v' = a v - h(1 - q) x, \qquad a = 1 - h^2/2.

It keeps Q=v2+(1−q)x2Q = v^2 + (1 - q) x^2: the cross terms are −2ah(1−q)xv+2ah(1−q)xv=0-2ah(1-q)xv + 2ah(1-q)xv = 0, the coefficient of v2v^2 is a2+(1−q)h2=1a^2 + (1 - q)h^2 = 1, and the coefficient of x2x^2 is (1−q)(h2(1−q)+a2)=1−q(1-q)(h^2(1-q) + a^2) = 1 - q. Its determinant is 1. So it keeps the normal law GG with density proportional to e−Q/2e^{-Q/2}, which has ⟨v2⟩=1\langle v^2 \rangle = 1, ⟨x2⟩=1/(1−q)\langle x^2 \rangle = 1/(1-q) and no correlation. The O step keeps GG by Claim 2, since under GG the velocity is independent of xx with variance 1. So GG is stationary.

For uniqueness, the chain is zn+1=Mzn+ϵnz_{n+1} = M z_n + \epsilon_n with independent normal ϵn\epsilon_n and M=DPDM = D P D, where D=diag⁡(1,c)D = \operatorname{diag}(1, c) and PP is the Verlet map. In the norm ∥z∥2=Q(z)\|z\|^2 = Q(z), PP is an isometry and DD is a contraction, with ∥Dz∥=∥z∥\|Dz\| = \|z\| only if v=0v = 0. If ∥Mz∥=∥z∥\|Mz\| = \|z\|, then Dz=zDz = z, so v=0v = 0, and D(Pz)=PzD(Pz) = Pz, so v′=−h(1−q)x=0v' = -h(1-q)x = 0, so x=0x = 0. So ∥Mz∥<∥z∥\|Mz\| < \|z\| for z≠0z \ne 0, ∥M∥<1\|M\| < 1 by compactness of the unit sphere, and the law of znz_n converges to the unique stationary law. □\square

So the velocities have the right variance for every stable hh, and the positions have an error of relative size q=h2ω2/4q = h^2\omega^2/4. For hω=1h\omega = 1 the position variance is 4/34/3 of the right value. The tests compute both values by iteration of the covariance and by sampling.

Claim 5 (limits). With γ=0\gamma = 0, c=1c = 1, the O steps do nothing, and the step is velocity Verlet. With f=0f = 0, the Verlet part does not change vv, so the velocities at the step times follow Oh/2∘Oh/2=OhO_{h/2} \circ O_{h/2} = O_h: they are an exact sample path of the Ornstein-Uhlenbeck process, with correlation e−γhe^{-\gamma h} between consecutive steps. □\square

Complexity

Each step does one force evaluation, 2dN2dN normal draws and O(N)O(N) other work. With the all-pairs forces of the molecular dynamics page, SS steps take O(SN2)O(S N^2) time; with neighbor lists the forces take O(N)O(N) per step. The extra space is O(N)O(N) for the copies of xx and vv, plus the samples that are recorded.

Properties

  • Ensemble. Canonical (NVT), up to the time step error, for any γ>0\gamma > 0. 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 D=kBT/(mγ)D = k_B T / (m\gamma) (a theorem), and in a liquid a small γ\gamma changes DD 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 γ\gamma 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 γ\gamma, about 1 ps−11\ \mathrm{ps}^{-1} 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 NfN_f. Momentum is not conserved, so do not subtract dd for the centre of mass when the kinetic temperature is computed.
  • Units of γ\gamma. Some codes give a friction per mass, others a collision frequency, others a damping time 1/γ1/\gamma. 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 ⟨x2⟩\langle x^2 \rangle 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.

langevin_dynamics.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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
  4. 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.

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