Algorithm Search⌘K

Algorithmcore

Brownian dynamics

Also called Ermak-McCammon algorithm.

Integrates the overdamped Langevin equation, moving positions by force times mobility plus noise, for solutes in an implicit solvent.

Time
O(S N^3) worst
Space
O(N^2) extra
Where
N = the number of particles; S = the number of time steps
Properties
randomizediterativerandomizednot symmetricnot symplectic
Origin
Donald L. Ermak, J. Andrew McCammon, 1978

Brownian dynamics simulates particles in a solvent on time scales much longer than the time it takes the solvent to stop their motion. On these scales the velocities are not variables any more: each step moves the positions by the force times a mobility plus a random displacement. The equation it integrates is the overdamped limit of Langevin dynamics, and its stationary distribution is the Boltzmann distribution of the positions (a theorem). The step of Ermak and McCammon (1978) uses a diffusion tensor, which can couple the particles through the solvent flow they cause (hydrodynamic interactions). With one diffusion constant per particle it is the Euler-Maruyama step of the overdamped Langevin equation.

In plain words

A protein or a colloid in water is pushed around by water molecules many billions of times each second. When we only care about slow motions, such as two proteins finding each other, we can forget the speed of each particle. A particle in water stops almost at once when no force acts on it.

So each step does two things. It moves each particle a little in the direction of the force on it, more for small particles that move easily in water. Then it adds a random jump, which is the effect of the water knocks. The size of the jumps is tied to the temperature. With these two parts the particles end up in the right places with the right frequencies. A more detailed version also lets a moving particle drag its neighbors through the water.

The problem

The input is positions xi∈Rdx_i \in \mathbb{R}^d of NN particles, a force routine for fi=−∇iUf_i = -\nabla_i U, a time step hh, a number of steps SS, the temperature kBTk_B T, a diffusion tensor D(x)D(x) and a random number source. DD is a symmetric positive definite matrix of size dN×dNdN \times dN; for particles that do not interact through the solvent it is diagonal, with Di=kBT/ζiD_i = k_B T / \zeta_i for a friction coefficient ζi\zeta_i, for example the Stokes-Einstein value Di=kBT/(6πηai)D_i = k_B T / (6\pi\eta a_i) for a sphere of radius aia_i in a fluid of viscosity η\eta. The equation is

dx=1kBTD(x)f(x) dt+∇⋅D(x) dt+2 L(x) dW,LLT=D.dx = \frac{1}{k_B T} D(x) f(x)\, dt + \nabla \cdot D(x)\, dt + \sqrt{2}\, L(x)\, dW, \qquad L L^{\mathsf T} = D.

Its stationary density is ρ(x)∝e−U(x)/kBT\rho(x) \propto e^{-U(x)/k_B T}. The output is the trajectory of positions and samples of it. Brownian dynamics has no velocities, so it reports no kinetic temperature and needs no count NfN_f of degrees of freedom: the temperature enters only through kBTk_B T in the drift and the noise.

The algorithm

  1. BROWNIAN-DYNAMICS(x, FORCES, h, S, kT, DIFFUSION)
  2. 1f ← FORCES(x)
  3. 2for step ← 1 to S do
  4. 3D ← DIFFUSION(x) ▷ dN by dN; skip L3 and L4 for one constant per particle
  5. 4L ← CHOLESKY(D) ▷ L L^T = D
  6. 5R ← dN independent standard normal numbers
  7. 6x ← x + (h / kT) D f + sqrt(2 h) L R
  8. 7f ← FORCES(x)
  9. 8every k steps, record a copy of x
  10. 9return (x, the recorded samples)

With one diffusion constant DiD_i per particle, line L6 reads xi←xi+(hDi/kBT)fi+2Dih Rix_i \leftarrow x_i + (h D_i / k_B T) f_i + \sqrt{2 D_i h}\, R_i. Line L6 leaves out the term h∇⋅Dh \nabla \cdot D. It is zero for a constant DD and for the Rotne-Prager-Yamakawa tensor, which the implementation provides; for other tensors it must be added. The Cholesky decomposition on line L4 gives noise with covariance 2hD2hD.

Example

One step by hand. One particle in one dimension in the well U=12kx2U = \frac12 k x^2 with k=D=kBT=1k = D = k_B T = 1 in reduced units, x=1x = 1, h=0.1h = 0.1 and the normal draw R=0.3R = 0.3. The force is −1-1, so line L6 gives x=1−0.1+0.2⋅0.3=1.034164x = 1 - 0.1 + \sqrt{0.2} \cdot 0.3 = 1.034164.

The time step error in a harmonic well. For U=12kx2U = \frac12 k x^2 and a constant DD, let c=hDk/kBTc = hDk/k_B T. The stationary variance of the step is (kBT/k)/(1−c/2)(k_B T/k)/(1 - c/2) for 0<c<20 < c < 2 (a theorem, Claim 5 of the proof), and the step is unstable for c≥2c \ge 2. A run of 400 particles with k=D=kBT=1k = D = k_B T = 1, 1000 steps from 0, a sample every 2 steps and the first 100 steps dropped (seed 1):

hh 0.1 0.5 1 1.5
measured ⟨x2⟩\langle x^2 \rangle 1.0474 1.3354 2.0042 4.0145
exact for the step 1.0526 1.3333 2 4

The right value is 1. The error is of order hh, as for any Euler-Maruyama step.

Free diffusion. With no forces, the step is exact for any hh: after a time tt, the mean squared displacement in dd dimensions is 2dDt2dDt. 400 free particles in two dimensions with D=0.7D = 0.7, h=0.1h = 0.1 and 50 steps (seed 3) give 14.11 against 14.

Hydrodynamic coupling. For two spheres of radius aa at distance rr along the first axis, the Rotne-Prager-Yamakawa tensor gives the following coupling blocks, as fractions of the Stokes-Einstein value D0D_0:

r/ar / a 1 2 4 10
along the line of centers 0.8125 0.625 0.3594 0.149
across it 0.7188 0.4375 0.1953 0.0755
Oseen, along, 3a/(2r)3a/(2r) 1.5 0.75 0.375 0.15

At contact, r=2ar = 2a, both forms of the tensor give 716\frac{7}{16} and 316\frac{3}{16} for the parts across and along, so it is continuous. Far apart it approaches the Oseen tensor, which decays like 1/r1/r. The Oseen tensor can fail to be positive definite when spheres are close, which is why the corrected tensor is used.

Correctness

The proof in proofs/correctness.md shows:

  1. The Boltzmann density is stationary, with zero probability flux, for the Fokker-Planck equation of the overdamped equation.
  2. The step is the Euler-Maruyama step of that equation when ∇⋅D=0\nabla \cdot D = 0.
  3. The Rotne-Prager-Yamakawa tensor has zero divergence in both of its regions, so no divergence term is needed with it.
  4. Free particles and a constant force give the exact mean and covariance of the displacement for every hh.
  5. In a harmonic well the stationary variance of the step is (kBT/k)/(1−c/2)(k_B T/k)/(1 - c/2).

So the sampled distribution is the Boltzmann distribution of the positions up to an O(h)O(h) error, the weak order of the Euler-Maruyama method.

Proof: The Ermak-McCammon step is the Euler-Maruyama step of an equation whose stationary law is the Boltzmann densityfull

Let x∈Rnx \in \mathbb{R}^{n} hold all coordinates (n=Ndn = N d), f=−∇Uf = -\nabla U, and let D(x)D(x) be a symmetric positive definite n×nn \times n diffusion matrix. The overdamped Langevin equation in the Ito form is

dx=1kBTD(x)f(x) dt+(∇⋅D)(x) dt+2 L(x) dW,LLT=D,(1)dx = \frac{1}{k_B T} D(x) f(x)\,dt + (\nabla \cdot D)(x)\,dt + \sqrt{2}\,L(x)\,dW, \qquad L L^{\mathsf T} = D, \qquad (1)

with (∇⋅D)a=∑b∂bDab(\nabla \cdot D)_a = \sum_b \partial_b D_{ab}.

Claim 1 (the Boltzmann density is stationary). ρ(x)∝e−βU(x)\rho(x) \propto e^{-\beta U(x)} is a stationary solution of the Fokker-Planck equation of (1), and its probability flux is 0.

Proof. For dx=b dt+σ dWdx = b\,dt + \sigma\,dW the Fokker-Planck equation is ∂tρ=−∇⋅J\partial_t \rho = -\nabla \cdot J with Ja=baρ−∑b∂b(12(σσT)abρ)J_a = b_a \rho - \sum_b \partial_b \bigl( \frac12 (\sigma\sigma^{\mathsf T})_{ab} \rho \bigr). Here 12σσT=D\frac12 \sigma\sigma^{\mathsf T} = D, so

Ja=(Df)akBTρ+(∇⋅D)aρ−(∇⋅D)aρ−∑bDab∂bρ=∑bDab(fbkBTρ−∂bρ).J_a = \frac{(Df)_a}{k_B T}\rho + (\nabla \cdot D)_a \rho - (\nabla \cdot D)_a \rho - \sum_b D_{ab} \partial_b \rho = \sum_b D_{ab} \Bigl( \frac{f_b}{k_B T}\rho - \partial_b \rho \Bigr).

For ρ∝e−βU\rho \propto e^{-\beta U}, ∂bρ=βfbρ\partial_b \rho = \beta f_b \rho, so J=0J = 0. □\square

The term ∇⋅D\nabla \cdot D is needed for this: without it the flux has the extra part −(∇⋅D)ρ-(\nabla \cdot D)\rho, and the stationary law is wrong.

Claim 2 (the step). If ∇⋅D=0\nabla \cdot D = 0, then lines L3 to L6 are the Euler-Maruyama step of (1):

x′=x+hkBTD(x)f(x)+2h L(x)R,R∼N(0,I).x' = x + \frac{h}{k_B T} D(x) f(x) + \sqrt{2h}\,L(x) R, \qquad R \sim N(0, I).

The noise term has the covariance 2hD(x)2hD(x). For a scalar diffusion coefficient DiD_i per particle, LL is diagonal with entries Di\sqrt{D_i}, and line L6 adds 2Dih\sqrt{2 D_i h} times a standard normal to each coordinate.

Proof. Line L4 computes the Cholesky factor LL of DD, line L5 draws RR, and line L6 adds the drift and 2hLR\sqrt{2h} L R. The covariance is 2h E[LRRTLT]=2hLLT=2hD2h\,\mathbb{E}[L R R^{\mathsf T} L^{\mathsf T}] = 2h L L^{\mathsf T} = 2h D. □\square

DD constant gives ∇⋅D=0\nabla \cdot D = 0. The Euler-Maruyama method has weak order 1, so averages over the sampled law differ from Boltzmann averages by O(h)O(h). Claim 5 gives this error in a case we can solve.

Claim 3 (the Rotne-Prager-Yamakawa tensor has zero divergence). For spheres of radius aa in three dimensions, with the blocks used by the implementation, ∇⋅D=0\nabla \cdot D = 0 in both regions r≥2ar \ge 2a and r<2ar < 2a.

Proof. The diagonal blocks are the constant D0ID_0 I with D0=kBT/(6πηa)D_0 = k_B T / (6\pi\eta a). An off-diagonal block T(r)T(r) depends on r=xi−xjr = x_i - x_j, so its contribution to (∇⋅D)i(\nabla \cdot D)_i is ±∑b∂bTab(r)\pm \sum_b \partial_b T_{ab}(r), and it is enough to show ∑b∂bTab=0\sum_b \partial_b T_{ab} = 0. Write r=∣r∣r = |r|.

For r≥2ar \ge 2a,

T=kBT8πη(δabr+rarbr3)+kBT a212πη(δabr3−3rarbr5).T = \frac{k_B T}{8\pi\eta} \Bigl( \frac{\delta_{ab}}{r} + \frac{r_a r_b}{r^3} \Bigr) + \frac{k_B T\,a^2}{12\pi\eta} \Bigl( \frac{\delta_{ab}}{r^3} - \frac{3 r_a r_b}{r^5} \Bigr).

For the first bracket, ∂b(δab/r)=−ra/r3\partial_b(\delta_{ab}/r) = -r_a/r^3 and ∂b(rarb/r3)=ra/r3+3ra/r3−3ra/r3=ra/r3\partial_b(r_a r_b / r^3) = r_a/r^3 + 3r_a/r^3 - 3r_a/r^3 = r_a/r^3, with sum 0. The second bracket is −∂a∂b(1/r)-\partial_a\partial_b (1/r), and its divergence is −∂a∇2(1/r)=0-\partial_a \nabla^2(1/r) = 0 for r≠0r \ne 0.

For r<2ar < 2a, T=D0((1−9r32a)δab+332ararbr)T = D_0 \bigl( (1 - \frac{9r}{32a})\delta_{ab} + \frac{3}{32a} \frac{r_a r_b}{r} \bigr). Here ∂b((1−9r32a)δab)=−9ra32ar\partial_b\bigl((1 - \frac{9r}{32a})\delta_{ab}\bigr) = -\frac{9 r_a}{32 a r} and ∂b(rarb/r)=ra/r+3ra/r−ra/r=3ra/r\partial_b (r_a r_b / r) = r_a/r + 3r_a/r - r_a/r = 3r_a/r, so the sum is −9ra32ar+9ra32ar=0-\frac{9r_a}{32ar} + \frac{9 r_a}{32ar} = 0. □\square

So the step of Claim 2 is the Euler-Maruyama step of (1) also for the Rotne-Prager-Yamakawa tensor, with no divergence term to add. The tensor is positive definite for all configurations, which is the reason it is used in place of the Oseen tensor (the first bracket alone), so the Cholesky factor in line L4 exists. The two forms agree at r=2ar = 2a, where both give D0(716δab+316eaeb)D_0 \bigl(\frac{7}{16}\delta_{ab} + \frac{3}{16} e_a e_b\bigr) with e=r/∣r∣e = r/|r|, and the diagonal blocks give the Stokes-Einstein value D0D_0.

Claim 4 (free particles and a constant force). With a constant scalar DD and a constant force gg on each particle, the displacement after nn steps is normal with mean nhDg/(kBT)n h D g / (k_B T) and covariance 2nhD I2 n h D\,I, for every hh. So for g=0g = 0 the mean squared displacement in dd dimensions is exactly 2dDt2 d D t at t=nht = nh.

Proof. Each step adds hDg/(kBT)h D g/(k_B T) and an independent normal with covariance 2hD I2hD\,I. □\square

Claim 5 (the harmonic well). For U=12kx2U = \frac12 k x^2 with a scalar DD, let c=hDk/(kBT)c = hDk/(k_B T) with 0<c<20 < c < 2. The stationary variance of the chain is

⟨x2⟩=kBTk 11−c/2.\langle x^2 \rangle = \frac{k_B T}{k} \, \frac{1}{1 - c/2}.

Proof. The step is x′=(1−c)x+2Dh Rx' = (1 - c)x + \sqrt{2Dh}\,R. A stationary variance ss satisfies s=(1−c)2s+2Dhs = (1 - c)^2 s + 2Dh, so s=2Dh/(c(2−c))=kBTk⋅22−cs = 2Dh / (c(2 - c)) = \frac{k_B T}{k} \cdot \frac{2}{2 - c}. For 0<c<20 < c < 2, ∣1−c∣<1|1 - c| < 1, so the chain converges to this law from any start. □\square

The right value is kBT/kk_B T/k; the relative error is c/2+O(c2)c/2 + O(c^2), of order hh as Claim 2 says. The step is unstable for c≥2c \ge 2, so hh must be small compared with kBT/(Dk)k_B T / (D k) for the stiffest force.

Complexity

With one diffusion constant per particle, each step does one force evaluation and dNdN normal draws, so SS steps take O(SN2)O(S N^2) time with all-pairs forces and O(N)O(N) extra space. With a full diffusion tensor, building it takes O(N2)O(N^2) time and space per step, and its Cholesky factor O(N3)O(N^3) time, so SS steps take O(SN3)O(S N^3) time and O(N2)O(N^2) extra space. Fixman's Chebyshev method and Ewald-like methods for the tensor reduce this for large NN.

Properties

  • Ensemble. The Boltzmann (canonical) distribution of the positions, up to O(h)O(h), for any positive definite DD when the divergence term is right.
  • No velocities. The method has no kinetic energy and no inertia. The dynamics are physical only on time scales much longer than the velocity relaxation time m/ζm/\zeta.
  • Diffusion is correct in the free case for any step, which is the main use: diffusion constants and rates of encounter.
  • Hydrodynamics are optional. A diagonal DD gives the free-draining model, and a full tensor couples the particles through the solvent.
  • Not time-reversible. The process satisfies detailed balance with respect to the Boltzmann density, but the step does not.

Variants and improvements

  • The limit of BAOAB. The high friction limit of BAOAB gives the update x′=x+(hD/kBT)f+Dh/2 (Rn+Rn+1)x' = x + (hD/k_B T) f + \sqrt{Dh/2}\,(R_n + R_{n+1}), which uses two successive draws and is more accurate for configurational averages.
  • A Metropolis test. Accepting or rejecting each step with the Metropolis rule removes the time step bias; with DD constant this is the Metropolis-adjusted Langevin algorithm.
  • Faster noise. Fixman (1986) approximated LRL R with Chebyshev polynomials of DD, which avoids the Cholesky factor.
  • Event-based methods. For rare transitions between states, kinetic Monte Carlo jumps from state to state with known rates.
  • Concentrations. For chemical species in well-mixed systems, the chemical Langevin equation uses the same kind of equation for concentrations.

When to use it

Use Brownian dynamics for solutes in an implicit solvent when the time scale of interest is much longer than the velocity relaxation time: colloids, polymers in solution, protein association, coarse-grained models. It allows much larger time steps than molecular dynamics with explicit water. Do not use it when inertia matters, for example for vibrations, for fast molecular motion or for gases.

Pitfalls

  • A missing divergence term. For a diffusion tensor that depends on the positions and has nonzero divergence, leaving out h∇⋅Dh \nabla \cdot D gives the wrong distribution.
  • The Oseen tensor. It is not positive definite when particles are close, and the Cholesky factor fails. Use the Rotne-Prager-Yamakawa form.
  • Too large a step. In a stiff well the step is unstable for hDk/kBT≥2hDk/k_B T \ge 2, and the error is of order hh below that. Steep repulsive walls need a small step or a rejection rule.
  • Units. DD has units of length squared per time, and the drift is Df/kBTD f / k_B T, not DfD f.
  • Interpreting the time. With a wrong DD, all times scale; check a known diffusion constant.

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.

brownian_dynamics.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/brownian-dynamics/. The authors are listed in prov/1T83PZ.jsonl.
"""Brownian dynamics with the Ermak-McCammon step.

In the overdamped limit the velocities are not kept. With the diffusion
tensor D (an (N d) by (N d) symmetric positive definite matrix), the
positions follow

    dx = (D f / kT) dt + div(D) dt + sqrt(2) L dW,   L L^T = D.

The Ermak-McCammon step of length h is

    x <- x + (h / kT) D f + h div(D) + sqrt(2 h) L R,

with R a vector of independent standard normals. Here the divergence term
is left out, which is exact for a constant D and for the Rotne-Prager-
Yamakawa tensor (its divergence is zero). With one diffusion coefficient
D_i per particle and no hydrodynamic coupling, the step is

    x_i <- x_i + (h D_i / kT) f_i + sqrt(2 D_i h) R_i,

the Euler-Maruyama step for the overdamped Langevin equation.

Cost per step: one force evaluation and N d normal draws. With a full
tensor, also Theta((N d)^2) to build D and Theta((N d)^3) for its Cholesky
factor.
"""

import math
import random
from typing import Callable, Union

from scimat import cholesky

Vec = list[float]
Matrix = list[list[float]]
ForceField = Callable[[list[Vec]], tuple[float, list[Vec]]]
Diffusion = Union[float, list[float], Callable[[list[Vec]], Matrix]]


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 constant_force(g: Vec) -> ForceField:
    """The same force g on every particle, U = -sum_i g . x_i."""
    def field(pos: list[Vec]) -> tuple[float, list[Vec]]:
        u = -sum(ga * c for p in pos for ga, c in zip(g, p))
        return u, [list(g) for _ 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 rpy_tensor(a: float, kT: float, eta: float) -> Callable[[list[Vec]], Matrix]:
    """The Rotne-Prager-Yamakawa diffusion tensor for spheres of radius a in 3D.

    The diagonal blocks are D0 I with D0 = kT / (6 pi eta a). For two spheres
    at distance r >= 2a the block is
        kT / (8 pi eta r) ((1 + 2 a^2 / (3 r^2)) I + (1 - 2 a^2 / r^2) e e^T),
    and for r < 2a it is
        D0 ((1 - 9 r / (32 a)) I + (3 r / (32 a)) e e^T),
    with e the unit vector from one center to the other. The matrix is
    positive definite for every configuration.
    """
    d0 = kT / (6.0 * math.pi * eta * a)

    def tensor(pos: list[Vec]) -> Matrix:
        n = len(pos)
        out = [[0.0] * (3 * n) for _ in range(3 * n)]
        for i in range(n):
            for s in range(3):
                out[3 * i + s][3 * i + s] = d0
            for j in range(i + 1, n):
                dx = [pos[i][s] - pos[j][s] for s in range(3)]
                r = math.sqrt(sum(c * c for c in dx))
                e = [c / r for c in dx]
                if r >= 2.0 * a:
                    pre = kT / (8.0 * math.pi * eta * r)
                    ci = pre * (1.0 + 2.0 * a * a / (3.0 * r * r))
                    ce = pre * (1.0 - 2.0 * a * a / (r * r))
                else:
                    ci = d0 * (1.0 - 9.0 * r / (32.0 * a))
                    ce = d0 * 3.0 * r / (32.0 * a)
                for s in range(3):
                    for t in range(3):
                        val = ce * e[s] * e[t] + (ci if s == t else 0.0)
                        out[3 * i + s][3 * j + t] = val
                        out[3 * j + t][3 * i + s] = val
        return out
    return tensor


def brownian_dynamics(
    x: list[Vec], forces: ForceField, h: float, steps: int, kT: float,
    diffusion: Diffusion, rng: random.Random, every: int = 1,
) -> tuple[list[Vec], list[list[Vec]]]:
    """Run steps of Brownian dynamics with the Ermak-McCammon step.

    diffusion is one coefficient for all particles, a list with one
    coefficient per particle, or a function that maps the positions to the
    (N d) by (N d) diffusion tensor (row i d + s is coordinate s of particle i).
    Returns the final positions and copies of the positions after every
    `every` steps. The input is not changed.
    """
    if h <= 0 or kT <= 0 or every < 1:
        raise ValueError("need h > 0, kT > 0 and every >= 1")
    x = [list(p) for p in x]
    n = len(x)
    tensor = diffusion if callable(diffusion) else None
    if tensor is None:
        dlist = list(diffusion) if isinstance(diffusion, list) else [float(diffusion)] * n
        if len(dlist) != n or min(dlist) <= 0:
            raise ValueError("need one positive diffusion coefficient per particle")
        sd = [math.sqrt(2.0 * di * h) for di in dlist]
    _, f = forces(x)  # @line L1
    samples = []
    for step in range(1, steps + 1):  # @line L2
        if tensor is None:
            for i in range(n):
                for s in range(len(x[i])):
                    r = rng.gauss(0.0, 1.0)  # @line L5
                    x[i][s] += h * dlist[i] * f[i][s] / kT + sd[i] * r  # @line L6
        else:
            d = len(x[0])
            dm = tensor(x)  # @line L3
            low = cholesky(dm)  # @line L4
            r = [rng.gauss(0.0, 1.0) for _ in range(n * d)]  # @line L5
            fl = [c for p in f for c in p]
            dx = [0.0] * (n * d)
            for row in range(n * d):
                drift = sum(dm[row][col] * fl[col] for col in range(n * d))
                noise = sum(low[row][col] * r[col] for col in range(row + 1))
                dx[row] = h * drift / kT + math.sqrt(2.0 * h) * noise
            for i in range(n):
                for s in range(d):
                    x[i][s] += dx[i * d + s]  # @line L6
        _, f = forces(x)  # @line L7
        if step % every == 0:  # @line L8
            samples.append([list(p) for p in x])
    return x, samples  # @line L9
scimat.py 227 lines
# SPDX-License-Identifier: MIT
# Shared helper of the scientific-computing pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small dense linear algebra and error norms for the scientific-computing pages.

A matrix is a list of rows and a vector is a list. Entries may be int,
float or fractions.Fraction. The routines that do not take a square root
(solve, inv, det and the arithmetic) keep Fraction entries exact.
cholesky, cholesky_solve and norm2 take square roots and return floats.

API (fixed; other pages copy this file byte for byte):
    zeros(m, n=None)        m by n zero matrix (n = m if not given)
    eye(n)                  n by n identity
    add(A, B), sub(A, B)    entrywise sum and difference (vectors or matrices)
    scale(c, A)             c times A (vector or matrix)
    matmul(A, B)            matrix product
    matvec(A, x)            matrix times vector
    transpose(A)            transpose
    dot(x, y)               inner product of two vectors
    norm2(x)                Euclidean norm of a vector, as a float
    outer(x, y)             outer product x y^T
    solve(A, b)             Gaussian elimination with partial pivoting;
                            b is a vector or a matrix of right sides
    inv(A)                  inverse of A
    det(A)                  determinant of A
    cholesky(A)             lower triangular L with A = L L^T (floats)
    cholesky_solve(L, b)    solve L L^T x = b for a vector b
    err_l1(e, dx=1)         sum |e_j| dx
    err_l2(e, dx=1)         sqrt(sum e_j^2 dx), as a float
    err_linf(e, dx=1)       max |e_j| (dx is not used)
    observed_order(errors)  [log2(E_i / E_(i+1)) for successive errors]
"""

import math


def zeros(m, n=None):
    """Return an m by n matrix of zeros (n = m if n is None)."""
    if n is None:
        n = m
    return [[0] * n for _ in range(m)]


def eye(n):
    """Return the n by n identity matrix."""
    out = zeros(n, n)
    for i in range(n):
        out[i][i] = 1
    return out


def _is_matrix(a):
    return len(a) > 0 and isinstance(a[0], list)


def add(a, b):
    """Return a + b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x + y for x, y in zip(a, b)]


def sub(a, b):
    """Return a - b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x - y for x, y in zip(a, b)]


def scale(c, a):
    """Return c times a, for a vector or a matrix a."""
    if _is_matrix(a):
        return [[c * x for x in row] for row in a]
    return [c * x for x in a]


def transpose(a):
    """Return the transpose of the matrix a."""
    return [list(col) for col in zip(*a)]


def matmul(a, b):
    """Return the matrix product a b."""
    bt = transpose(b)
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def matvec(a, x):
    """Return the product of the matrix a and the vector x."""
    return [sum(aij * xj for aij, xj in zip(row, x)) for row in a]


def dot(x, y):
    """Return the inner product of the vectors x and y."""
    return sum(a * b for a, b in zip(x, y))


def norm2(x):
    """Return the Euclidean norm of the vector x, as a float."""
    return math.sqrt(float(dot(x, x)))


def outer(x, y):
    """Return the outer product x y^T as a matrix."""
    return [[a * b for b in y] for a in x]


def _eliminate(a, rhs):
    """Reduce a to upper triangular form with partial pivoting.

    a is a copy of the square matrix, rhs a list of right side rows (one
    row per row of a) that receives the same row operations. Return the
    number of row swaps. Raise ValueError if a pivot is zero.
    """
    n = len(a)
    swaps = 0
    for k in range(n):
        p = max(range(k, n), key=lambda i: abs(a[i][k]))
        if a[p][k] == 0:
            raise ValueError("matrix is singular")
        if p != k:
            a[k], a[p] = a[p], a[k]
            rhs[k], rhs[p] = rhs[p], rhs[k]
            swaps += 1
        for i in range(k + 1, n):
            f = a[i][k] / a[k][k]
            if f == 0:
                continue
            for j in range(k, n):
                a[i][j] -= f * a[k][j]
            for j in range(len(rhs[i])):
                rhs[i][j] -= f * rhs[k][j]
    return swaps


def solve(a, b):
    """Solve a x = b by Gaussian elimination with partial pivoting.

    b is a vector (the result is a vector) or a matrix with one column per
    right side (the result is a matrix). Fraction entries stay exact.
    Raise ValueError if a is singular.
    """
    n = len(a)
    work = [list(row) for row in a]
    vector = not _is_matrix(b)
    rhs = [[v] for v in b] if vector else [list(row) for row in b]
    _eliminate(work, rhs)
    m = len(rhs[0]) if n else 0
    x = [[0] * m for _ in range(n)]
    for i in range(n - 1, -1, -1):
        for j in range(m):
            s = rhs[i][j]
            for k in range(i + 1, n):
                s -= work[i][k] * x[k][j]
            x[i][j] = s / work[i][i]
    if vector:
        return [row[0] for row in x]
    return x


def inv(a):
    """Return the inverse of the square matrix a."""
    return solve(a, eye(len(a)))


def det(a):
    """Return the determinant of the square matrix a (0 if singular)."""
    work = [list(row) for row in a]
    rhs = [[] for _ in a]
    try:
        swaps = _eliminate(work, rhs)
    except ValueError:
        return 0
    d = -1 if swaps % 2 else 1
    for i in range(len(a)):
        d *= work[i][i]
    return d


def cholesky(a):
    """Return the lower triangular L with a = L L^T, in floats.

    Raise ValueError if a is not symmetric positive definite.
    """
    n = len(a)
    low = [[0.0] * n for _ in range(n)]
    for j in range(n):
        s = float(a[j][j]) - sum(low[j][k] ** 2 for k in range(j))
        if s <= 0.0:
            raise ValueError("matrix is not positive definite")
        low[j][j] = math.sqrt(s)
        for i in range(j + 1, n):
            t = float(a[i][j]) - sum(low[i][k] * low[j][k] for k in range(j))
            low[i][j] = t / low[j][j]
    return low


def cholesky_solve(low, b):
    """Solve L L^T x = b, with L from cholesky, for a vector b."""
    n = len(low)
    y = [0.0] * n
    for i in range(n):
        y[i] = (float(b[i]) - sum(low[i][k] * y[k] for k in range(i))) / low[i][i]
    x = [0.0] * n
    for i in range(n - 1, -1, -1):
        x[i] = (y[i] - sum(low[k][i] * x[k] for k in range(i + 1, n))) / low[i][i]
    return x


def err_l1(e, dx=1):
    """Return the discrete L1 norm sum |e_j| dx."""
    return sum(abs(v) for v in e) * dx


def err_l2(e, dx=1):
    """Return the discrete L2 norm sqrt(sum e_j^2 dx), as a float."""
    return math.sqrt(float(sum(v * v for v in e) * dx))


def err_linf(e, dx=1):
    """Return the max norm max |e_j|. dx is accepted for a uniform call and not used."""
    return max(abs(v) for v in e)


def observed_order(errors):
    """Return [log2(E_i / E_(i+1))] for a list of errors on meshes h, h/2, h/4, ..."""
    return [math.log2(float(errors[i]) / float(errors[i + 1])) for i in range(len(errors) - 1)]
test_brownian_dynamics.py 112 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/brownian-dynamics/. The authors are listed in prov/1T83PZ.jsonl.
import math
import random

import pytest

from brownian_dynamics import brownian_dynamics, constant_force, free, harmonic, rpy_tensor
from scimat import cholesky, matmul, transpose


def test_harmonic_well_has_the_exact_discrete_stationary_variance():
    # x' = (1 - c) x + sqrt(2 D h) R with c = D k h / kT has stationary
    # variance (kT / k) / (1 - c / 2). Here c = 0.5, so the variance is 4/3
    # where the continuous process gives 1.
    n, h, d, kT, k = 400, 0.5, 1.0, 1.0, 1.0
    rng = random.Random(1)
    x = [[0.0] for _ in range(n)]
    x, samples = brownian_dynamics(x, harmonic(k), h, 300, kT, d, rng, every=2)
    vals = [p[0] ** 2 for s in samples[10:] for p in s]
    var = sum(vals) / len(vals)
    c = d * k * h / kT
    assert var == pytest.approx((kT / k) / (1 - c / 2), rel=0.03)


def test_small_step_gives_the_boltzmann_variance():
    n, h = 400, 0.02
    rng = random.Random(2)
    x = [[rng.gauss(0.0, 1.0)] for _ in range(n)]
    _, samples = brownian_dynamics(x, harmonic(1.0), h, 400, 1.0, 1.0, rng, every=20)
    vals = [p[0] ** 2 for s in samples for p in s]
    assert sum(vals) / len(vals) == pytest.approx(1.0 / (1 - 0.01), rel=0.04)


def test_free_mean_square_displacement_is_2_d_D_t():
    n, h, steps, d = 400, 0.1, 50, 0.7
    rng = random.Random(3)
    x0 = [[0.0, 0.0] for _ in range(n)]
    x, _ = brownian_dynamics(x0, free(), h, steps, 1.0, [d] * n, rng)
    msd = sum(p[0] ** 2 + p[1] ** 2 for p in x) / n
    t = h * steps
    # |dx|^2 / (2 D t) is chi-squared with 2 degrees of freedom: variance 4
    assert msd == pytest.approx(4 * d * t, abs=4 * 2 * d * t * 2 / math.sqrt(n))


def test_constant_force_gives_drift_D_F_over_kT():
    n, h, steps, d, kT = 400, 0.1, 20, 0.5, 2.0
    rng = random.Random(4)
    x, _ = brownian_dynamics([[0.0]] * n, constant_force([3.0]), h, steps, kT, d, rng)
    mean = sum(p[0] for p in x) / n
    t = h * steps
    assert mean == pytest.approx(d * 3.0 * t / kT, abs=4 * math.sqrt(2 * d * t / n))


def test_tensor_noise_has_covariance_2_D_h():
    # A fixed 2 by 2 diffusion tensor for one particle in 2D, no force.
    dm = [[1.0, 0.6], [0.6, 0.5]]
    rng = random.Random(5)
    _, samples = brownian_dynamics([[0.0, 0.0]], free(), 0.1, 4000, 1.0, lambda pos: dm, rng)
    prev = [0.0, 0.0]
    acc = [[0.0, 0.0], [0.0, 0.0]]
    for s in samples:
        dx = [s[0][0] - prev[0], s[0][1] - prev[1]]
        prev = s[0]
        for i in range(2):
            for j in range(2):
                acc[i][j] += dx[i] * dx[j] / len(samples)
    for i in range(2):
        for j in range(2):
            assert acc[i][j] == pytest.approx(2 * 0.1 * dm[i][j], abs=0.01)


def test_tensor_drift_is_D_F_over_kT():
    # Same fixed tensor with a constant force: the mean step is h D f / kT.
    dm = [[1.0, 0.6], [0.6, 0.5]]
    rng = random.Random(6)
    x, _ = brownian_dynamics([[0.0, 0.0]], constant_force([1.0, -2.0]), 0.1, 4000, 2.0, lambda pos: dm, rng)
    t = 0.1 * 4000
    expect = [t * (1.0 * 1.0 + 0.6 * -2.0) / 2.0, t * (0.6 * 1.0 + 0.5 * -2.0) / 2.0]
    for a in range(2):
        assert x[0][a] == pytest.approx(expect[a], abs=4 * math.sqrt(2 * dm[a][a] * t))


def test_rpy_tensor_is_symmetric_positive_definite_and_has_stokes_einstein_diagonal():
    rng = random.Random(7)
    a, kT, eta = 1.0, 1.0, 1.0
    tensor = rpy_tensor(a, kT, eta)
    for spread in (0.5, 2.0, 10.0):  # overlapping, near and far spheres
        pos = [[rng.uniform(0, spread) for _ in range(3)] for _ in range(4)]
        dm = tensor(pos)
        assert all(dm[i][j] == dm[j][i] for i in range(12) for j in range(12))
        low = cholesky(dm)
        back = matmul(low, transpose(low))
        assert max(abs(back[i][j] - dm[i][j]) for i in range(12) for j in range(12)) < 1e-12
        assert dm[0][0] == pytest.approx(kT / (6 * math.pi * eta * a), rel=1e-12)


def test_rpy_tensor_is_continuous_at_contact_and_decays_like_oseen():
    tensor = rpy_tensor(1.0, 1.0, 1.0)
    d0 = 1.0 / (6 * math.pi)
    inside = tensor([[0.0, 0.0, 0.0], [2.0 - 1e-9, 0.0, 0.0]])
    outside = tensor([[0.0, 0.0, 0.0], [2.0 + 1e-9, 0.0, 0.0]])
    assert inside[0][3] == pytest.approx(outside[0][3], abs=1e-8)
    assert outside[0][3] == pytest.approx(d0 * (7 / 16 + 3 / 16), abs=1e-8)
    far = tensor([[0.0, 0.0, 0.0], [1000.0, 0.0, 0.0]])
    # Oseen limit along the line of centers: kT / (4 pi eta r)
    assert far[0][3] == pytest.approx(1.0 / (4 * math.pi * 1000.0), rel=1e-5)


def test_bad_arguments_raise():
    with pytest.raises(ValueError):
        brownian_dynamics([[0.0]], free(), 0.1, 1, 1.0, -1.0, random.Random(0))

History

Einstein (1905) and Smoluchowski (1906) explained Brownian motion as diffusion and related the diffusion constant to friction and temperature. Ermak and McCammon (1978) gave the simulation step with a configuration-dependent diffusion tensor, including the divergence term, and used the Oseen and Rotne-Prager tensors for hydrodynamic interactions. The Rotne-Prager tensor (1969) and Yamakawa's form (1970) give a positive definite tensor for spheres. Later work by Fixman and others reduced the cost of the correlated noise for many particles.

References

  1. Donald L. Ermak and J. Andrew McCammon, Brownian dynamics with hydrodynamic interactions, Journal of Chemical Physics 69(4), 1978, 1352-1360, the step for the positions with a diffusion tensor, the divergence term and the use of the Oseen and Rotne-Prager tensors
  2. 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
  3. Ben Leimkuhler and Charles Matthews, Molecular Dynamics, With Deterministic and Stochastic Numerical Methods, Springer, 2015, Chapters 6 and 7, the overdamped limit of Langevin dynamics and its numerical methods

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