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
- Model
- Real RAM
- Properties
- randomizediterativerandomizednot symmetricnot symplectic
- Evidence
- Proof sketchCode in 1 languages
- 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 of particles, a force routine for , a time step , a number of steps , the temperature , a diffusion tensor and a random number source. is a symmetric positive definite matrix of size ; for particles that do not interact through the solvent it is diagonal, with for a friction coefficient , for example the Stokes-Einstein value for a sphere of radius in a fluid of viscosity . The equation is
Its stationary density is . 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 of degrees of freedom: the temperature enters only through in the drift and the noise.
The algorithm
BROWNIAN-DYNAMICS(x, FORCES, h, S, kT, DIFFUSION)- 1
f ← FORCES(x) - 2
for step ← 1 to S do - 3
D ← DIFFUSION(x) ▷ dN by dN; skip L3 and L4 for one constant per particle - 4
L ← CHOLESKY(D) ▷ L L^T = D - 5
R ← dN independent standard normal numbers - 6
x ← x + (h / kT) D f + sqrt(2 h) L R - 7
f ← FORCES(x) - 8
every k steps, record a copy of x - 9
return (x, the recorded samples)
With one diffusion constant per particle, line L6 reads . Line L6 leaves out the term . It is zero for a constant 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 .
Example
One step by hand. One particle in one dimension in the well with in reduced units, , and the normal draw . The force is , so line L6 gives .
The time step error in a harmonic well. For and a constant , let . The stationary variance of the step is for (a theorem, Claim 5 of the proof), and the step is unstable for . A run of 400 particles with , 1000 steps from 0, a sample every 2 steps and the first 100 steps dropped (seed 1):
| 0.1 | 0.5 | 1 | 1.5 | |
|---|---|---|---|---|
| measured | 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 , as for any Euler-Maruyama step.
Free diffusion. With no forces, the step is exact for any : after a time , the mean squared displacement in dimensions is . 400 free particles in two dimensions with , and 50 steps (seed 3) give 14.11 against 14.
Hydrodynamic coupling. For two spheres of radius at distance along the first axis, the Rotne-Prager-Yamakawa tensor gives the following coupling blocks, as fractions of the Stokes-Einstein value :
| 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, | 1.5 | 0.75 | 0.375 | 0.15 |
At contact, , both forms of the tensor give and for the parts across and along, so it is continuous. Far apart it approaches the Oseen tensor, which decays like . 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:
- The Boltzmann density is stationary, with zero probability flux, for the Fokker-Planck equation of the overdamped equation.
- The step is the Euler-Maruyama step of that equation when .
- The Rotne-Prager-Yamakawa tensor has zero divergence in both of its regions, so no divergence term is needed with it.
- Free particles and a constant force give the exact mean and covariance of the displacement for every .
- In a harmonic well the stationary variance of the step is .
So the sampled distribution is the Boltzmann distribution of the positions up to an 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 hold all coordinates (), , and let be a symmetric positive definite diffusion matrix. The overdamped Langevin equation in the Ito form is
with .
Claim 1 (the Boltzmann density is stationary). is a stationary solution of the Fokker-Planck equation of (1), and its probability flux is 0.
Proof. For the Fokker-Planck equation is with . Here , so
For , , so .
The term is needed for this: without it the flux has the extra part , and the stationary law is wrong.
Claim 2 (the step). If , then lines L3 to L6 are the Euler-Maruyama step of (1):
The noise term has the covariance . For a scalar diffusion coefficient per particle, is diagonal with entries , and line L6 adds times a standard normal to each coordinate.
Proof. Line L4 computes the Cholesky factor of , line L5 draws , and line L6 adds the drift and . The covariance is .
constant gives . The Euler-Maruyama method has weak order 1, so averages over the sampled law differ from Boltzmann averages by . 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 in three dimensions, with the blocks used by the implementation, in both regions and .
Proof. The diagonal blocks are the constant with . An off-diagonal block depends on , so its contribution to is , and it is enough to show . Write .
For ,
For the first bracket, and , with sum 0. The second bracket is , and its divergence is for .
For , . Here and , so the sum is .
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 , where both give with , and the diagonal blocks give the Stokes-Einstein value .
Claim 4 (free particles and a constant force). With a constant scalar and a constant force on each particle, the displacement after steps is normal with mean and covariance , for every . So for the mean squared displacement in dimensions is exactly at .
Proof. Each step adds and an independent normal with covariance .
Claim 5 (the harmonic well). For with a scalar , let with . The stationary variance of the chain is
Proof. The step is . A stationary variance satisfies , so . For , , so the chain converges to this law from any start.
The right value is ; the relative error is , of order as Claim 2 says. The step is unstable for , so must be small compared with for the stiffest force.
Complexity
With one diffusion constant per particle, each step does one force evaluation and normal draws, so steps take time with all-pairs forces and extra space. With a full diffusion tensor, building it takes time and space per step, and its Cholesky factor time, so steps take time and extra space. Fixman's Chebyshev method and Ewald-like methods for the tensor reduce this for large .
Properties
- Ensemble. The Boltzmann (canonical) distribution of the positions, up to , for any positive definite 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 .
- 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 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 , 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 constant this is the Metropolis-adjusted Langevin algorithm.
- Faster noise. Fixman (1986) approximated with Chebyshev polynomials of , 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 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 , and the error is of order below that. Steep repulsive walls need a small step or a rejection rule.
- Units. has units of length squared per time, and the drift is , not .
- Interpreting the time. With a wrong , 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.
# 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
- 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
- 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
- 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.
| 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 1T83PZ Edit this page History Report an error Markdown