Algorithmadvanced
Stochastic velocity rescaling thermostat
Also called Bussi thermostat.
Rescales the kinetic energy by a random factor drawn so that it follows the canonical distribution, keeping Berendsen's smoothness with correct sampling.
- Time
- O(S N^2) worst
- Space
- O(N) extra
- Where
- N = the number of particles; S = the number of time steps
- Model
- Real RAM
- Properties
- randomizediterativerandomizednot symmetricnot symplectic
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Giovanni Bussi, Davide Donadio, Michele Parrinello, 2007
The stochastic velocity rescaling thermostat, also called the Bussi thermostat, controls the temperature in molecular dynamics. After each step it multiplies all velocities by one factor, as the Berendsen thermostat does. The factor is random: the kinetic energy follows the Berendsen relaxation plus a noise term, and the noise is chosen so that the stationary law of the kinetic energy is the canonical one. The method samples the canonical ensemble (a theorem, up to the error of the Verlet step), and the new kinetic energy is drawn exactly, with no time step error. Since the factor is close to 1 for many particles, the dynamics stay close to Newtonian.
In plain words
The Berendsen thermostat gently pushes the temperature toward the target. It does this so well that the temperature stops moving, but in a real system at fixed temperature the energy in motion goes up and down a little. So Berendsen gives the wrong spread.
This method adds a random push of the right size. Each step it looks at the energy in motion, picks a new value at random from the law it would reach after a short relaxation with random kicks, and scales all speeds by one common factor to get there. On average it still pulls toward the target, and the spread is now exactly right. All atoms keep their directions of motion, so the motion looks almost like plain molecular dynamics. A bookkeeping of the energy the bath adds or removes gives a total that must stay fixed, which checks the program.
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 coupling time , the number of degrees of freedom and a random number source. In the implementation ; with the total momentum fixed, use , and remove also one degree of freedom for each constraint. Let . Bussi, Donadio and Parrinello (2007) let the kinetic energy follow
with a Wiener process . The drift is the Berendsen equation for . The stationary law of this equation is the canonical law of , the gamma law with density proportional to . The output is the trajectory, the kinetic energy after each step and the effective energy
which is conserved up to the error of the integrator.
The algorithm
STOCHASTIC-VELOCITY-RESCALING(x, v, m, FORCES, h, S, kT, tau, N_f)- 1
(U, f) ← FORCES(x); K_0 ← N_f kT / 2; c ← exp(-h / tau); sigma² ← (1 - c) K_0 / N_f; Q ← 0 - 2
for step ← 1 to S do - 3
v_i ← v_i + (h / 2) f_i / m_i for each particle i ▷ velocity Verlet - 4
x_i ← x_i + h v_i for each particle i - 5
(U, f) ← FORCES(x) - 6
v_i ← v_i + (h / 2) f_i / m_i for each particle i - 7
K ← Σ_i m_i |v_i|² / 2 - 8
R_1 ← a standard normal number - 9
S_g ← 2 GAMMA((N_f - 1) / 2, 1), or 0 if N_f = 1 ▷ chi-squared with N_f - 1 degrees of freedom - 10
K' ← (sqrt(c K) + sigma R_1)² + sigma² S_g - 11
alpha ← sqrt(K' / K), with the sign of sqrt(c K) + sigma R_1 - 12
v_i ← alpha v_i for each particle i - 13
Q ← Q + (K' - K) ▷ heat from the bath - 14
record K' and the effective energy K' + U - Q - 15
return (x, v, the recorded K', the recorded effective energies)
Lines L8 to L10 draw the exact solution of the equation for over a time . The equation is the law of for independent Ornstein-Uhlenbeck processes , and by symmetry one of them can be taken along the current direction: it gives the term with , and the other give the chi-squared term. For , and , so the method is plain velocity Verlet. For , and is a fresh draw from the canonical law at each step.
Example
One rescaling by hand. Take , , and , so and , . With the draws and :
| quantity | ||||
|---|---|---|---|---|
| value | 1.557602 | 1.779375 | 3.362912 | 0.916912 |
Over many draws the mean of is , the Berendsen value, and the variance is . Berendsen gives the same mean with variance 0.
Canonical fluctuations. 20 harmonic oscillators in one dimension with in reduced units, , random normal start values (seed 4), and 40000 steps, of which the first 2000 are dropped. The canonical law of is gamma with mean and variance . Errors are batch-means standard errors with 20 batches.
| mean of | variance of | spread of | |
|---|---|---|---|
| 0.1 | 0.0167 | ||
| 1 | 0.0148 | ||
| 10 | 0.0126 |
These are measurements. The mean and the variance agree with 10 for all . A larger gives a slower decorrelation and larger errors, but not a bias, which is the difference from Berendsen. The effective energy stays within about 0.015 of its start, which is the size of the Verlet error at this step.
Free particles. With no forces, the rescaling is the whole dynamics and it is exact for any step. Five free particles with , and 8000 steps (seed 8) give a mean of of and a variance of , against 2.5 and 2.5.
Correctness
The proof in proofs/correctness.md shows:
- A representation. for independent Ornstein-Uhlenbeck processes solves the equation for in law.
- The exact step. Lines L8 to L10 draw with the law of the solution at time , for any and .
- The canonical law of is stationary. It is the gamma law with shape and scale .
- The canonical distribution is kept by the rescaling. Under the canonical law, and the direction of the scaled velocity vector are independent, and the rescaling changes only .
- The effective energy changes only in the Verlet parts.
- The sign of does not change the law; it keeps the velocity path continuous as .
So the method samples the canonical ensemble up to the error of the Verlet step. Ergodicity needs the Hamiltonian motion to mix the directions of the velocities, since the thermostat acts only on their length; for systems with a few independent parts, such as identical oscillators, it is not enough.
Proof: The rescaling draws the exact solution of the kinetic energy equation and keeps the canonical distributionfull
Let , and . The thermostat of Bussi, Donadio and Parrinello (2007) lets follow the stochastic differential equation
Claim 1 (a representation of (1)). Let be independent Ornstein-Uhlenbeck processes . Then solves (1) in law.
Proof. By the Ito formula,
The martingale has quadratic variation , so it is for a Brownian motion (Levy's characterization). This gives (1). The coefficients of (1) satisfy the Yamada-Watanabe condition, so the solution is unique in law.
Claim 2 (the exact step). Given , the law of is the law of
with standard normal and chi-squared with degrees of freedom, independent. Lines L8 to L10 draw this way.
Proof. The law of is invariant under rotations of , so we may start from . The exact Ornstein-Uhlenbeck step is , with and independent standard normals . So , and is chi-squared with degrees of freedom. Line L9 draws it as , which has this law.
So the rescaling has no time step error: for any and it draws the solution of (1) at time . From Claim 2, and , the values the tests check.
Claim 3 (the canonical law of is stationary). If has the gamma law with shape and scale , so does .
Proof. The stationary law of each is normal with variance . So the stationary law of is , the gamma law with shape and scale . Under the canonical distribution, are independent normals with variance , and has this law.
Claim 4 (the canonical distribution is kept). If has the canonical density before line L7, then after line L12 it still has it.
Proof. Write for the vector of the , of dimension . Under the canonical density, is independent of , and is a centered normal vector with covariance . So and the direction are independent, and the direction is uniform on the sphere. Line L12 multiplies by with , so the direction stays the same up to a sign that does not depend on the direction, and becomes . By Claim 3, has the gamma law, and it is independent of the direction and of . So the new has the same law as before.
The velocity Verlet part keeps the canonical density only up to its energy error. So the sampled distribution is canonical up to the integrator error, as for the other thermostats with a Verlet step.
Claim 5 (the effective energy). Let be the sum of the changes of made by the thermostat in the first steps (line L13). Then (line L14) changes only in the Verlet parts: is the change of in the Verlet part of step .
Proof. In step the thermostat changes by and adds the same amount to .
So a drift of measures the integration error alone, as the drift of does in a run without a thermostat.
Claim 6 (the sign). The sign of is the sign of , the first component of in Claim 2. The law of does not depend on this choice, and Claim 4 holds for either sign; the sign keeps the velocity path continuous in the limit .
Complexity
Each step does one force evaluation, work for the kinetic energy and the scaling, one normal draw and one gamma draw. A gamma draw takes expected time with the usual rejection methods. With the all-pairs forces of the molecular dynamics page, steps take time. The extra space is for the copies of and .
Properties
- Ensemble. Canonical (NVT), up to the time step error of the Verlet part, if the Hamiltonian motion mixes the velocity directions.
- Exact thermostat step. The new kinetic energy has no time step error.
- Global and gentle. One factor scales all velocities, close to 1 when is large, since the relative fluctuation of is . Directions of motion are kept, and a total momentum of zero stays zero.
- Dynamics stay physical. Diffusion and other dynamical properties are close to those of plain molecular dynamics for usual values of (a measurement in the 2007 paper).
- A quantity to monitor. The effective energy drifts only by integration error.
- Not deterministic. The trajectory depends on the random numbers.
Variants and improvements
- Several thermostats. Separate groups of atoms, such as solute and solvent, can each have their own rescaling with their own .
- Constant pressure. Bussi, Zykova-Timan and Parrinello (2009) combined the rescaling with a stochastic barostat, and Bernetti and Bussi (2020) gave stochastic cell rescaling. The Parrinello-Rahman barostat with this thermostat is a common NPT setup.
- Local thermostats. Langevin dynamics acts on each degree of freedom and has a proof of ergodicity, at the cost of a larger change of the dynamics. The Andersen thermostat redraws single velocities.
- Deterministic thermostats. Nose-Hoover chains give a time-reversible, deterministic alternative.
- Small time step limit. Integrating the equation for with the Euler-Maruyama method works for small , but the exact draw costs the same and has no error.
When to use it
Use it as a default thermostat for production runs in the NVT ensemble, in particular to replace Berendsen: it equilibrates as fast and samples the right distribution. It is a good choice when dynamical properties such as diffusion are measured, since it changes the dynamics little. For very small or nearly harmonic systems, where the Hamiltonian motion does not mix, prefer a local thermostat such as Langevin.
Pitfalls
- A wrong . The target is , so constraints and a fixed centre of mass must be counted, or the temperature is wrong.
- Zero kinetic energy. The factor needs . Start from random velocities.
- Identical copies. One global factor cannot make identical oscillators different. Start them at different values, as in the test.
- A wrong chi-squared draw. For large , summing squared normals is slow, and an approximation by one normal is not exact. Use a gamma generator, as on line L9.
- Ignoring the effective energy. A drift of shows a too large step, which no thermostat hides.
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/stochastic-velocity-rescaling/. The authors are listed in prov/BYYCSC.jsonl.
"""Molecular dynamics with the stochastic velocity rescaling thermostat.
Bussi, Donadio and Parrinello (2007) let the kinetic energy K follow the
stochastic differential equation
dK = (K0 - K) dt / tau + 2 sqrt(K K0 / N_f) dW / sqrt(tau),
with K0 = N_f kT / 2, the number of degrees of freedom N_f and the coupling
time tau. Its stationary law is the canonical law of K, with density
proportional to K^(N_f / 2 - 1) exp(-K / kT). The exact solution over a time
h is drawn as
K' = (sqrt(c K) + sqrt((1 - c) K0 / N_f) R_1)^2 + (1 - c) (K0 / N_f) S,
with c = exp(-h / tau), R_1 standard normal and S a chi-squared variable with
N_f - 1 degrees of freedom (2 times a gamma variable of shape (N_f - 1) / 2).
All velocities are then scaled by alpha = sqrt(K' / K), with the sign of
sqrt(c K) + sqrt((1 - c) K0 / N_f) R_1.
One step of length h here is one velocity Verlet step followed by one
rescaling. The sum of the changes of K made by the thermostat is kept, so
that the effective energy H~ = K + U - (that sum) can be monitored: it is
conserved up to the error of the Verlet step.
Cost: one force evaluation 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 kinetic(v: list[Vec], m: list[float]) -> float:
"""The kinetic energy K = sum_i m_i |v_i|^2 / 2."""
return sum(0.5 * mi * sum(c * c for c in vi) for vi, mi in zip(v, m))
def rescale_factor(k: float, k0: float, nf: int, c: float, rng: random.Random) -> float:
"""Draw alpha with alpha^2 K distributed as the exact SDE solution over a time h."""
r1 = rng.gauss(0.0, 1.0) # @line L8
s = 2.0 * rng.gammavariate(0.5 * (nf - 1), 1.0) if nf > 1 else 0.0 # @line L9
a = math.sqrt(c * k) + math.sqrt((1.0 - c) * k0 / nf) * r1
k_new = a * a + (1.0 - c) * (k0 / nf) * s # @line L10
alpha = math.sqrt(k_new / k) # @line L11
return alpha if a >= 0 else -alpha
def stochastic_velocity_rescaling(
x: list[Vec], v: list[Vec], m: list[float], forces: ForceField, h: float,
steps: int, kT: float, tau: float, nf: int, rng: random.Random,
) -> tuple[list[Vec], list[Vec], list[float], list[float]]:
"""Run steps of velocity Verlet with stochastic velocity rescaling.
Returns the final positions and velocities, the kinetic energy after each
step and the effective energy H~ after each step. The inputs are not
changed. Needs a nonzero kinetic energy at each rescaling.
"""
if h <= 0 or tau <= 0 or kT <= 0 or nf <= 0:
raise ValueError("need h > 0, tau > 0, kT > 0 and nf > 0")
x = [list(p) for p in x]
v = [list(p) for p in v]
n = len(x)
k0 = 0.5 * nf * kT
c = math.exp(-h / tau)
u, f = forces(x) # @line L1
heat = 0.0
ks, effective = [], []
for _ in range(steps): # @line L2
for i in range(n):
for a in range(len(x[i])):
v[i][a] += 0.5 * h * f[i][a] / m[i] # @line L3
x[i][a] += h * v[i][a] # @line L4
u, f = forces(x) # @line L5
for i in range(n):
for a in range(len(x[i])):
v[i][a] += 0.5 * h * f[i][a] / m[i] # @line L6
k = kinetic(v, m) # @line L7
alpha = rescale_factor(k, k0, nf, c, rng)
for vi in v:
for a in range(len(vi)):
vi[a] *= alpha # @line L12
heat += (alpha * alpha - 1.0) * k # @line L13
ks.append(alpha * alpha * k)
effective.append(alpha * alpha * k + u - heat) # @line L14
return x, v, ks, effective # @line L15
test_stochastic_velocity_rescaling.py 90 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/stochastic-velocity-rescaling/. The authors are listed in prov/BYYCSC.jsonl.
import math
import random
import pytest
from stochastic_velocity_rescaling import free, harmonic, rescale_factor, stochastic_velocity_rescaling
def batch_stats(xs, nb=10):
"""Mean and variance of xs, each with a batch-means standard error."""
size = len(xs) // nb
total = sum(xs) / len(xs)
means, variances = [], []
for b in range(nb):
part = xs[b * size:(b + 1) * size]
means.append(sum(part) / size)
variances.append(sum((z - total) ** 2 for z in part) / size)
def summary(vals):
mu = sum(vals) / nb
sd = math.sqrt(sum((z - mu) ** 2 for z in vals) / (nb - 1))
return mu, sd / math.sqrt(nb)
return summary(means), summary(variances)
def test_kinetic_energy_has_canonical_mean_and_variance():
# 20 oscillators in 1D, N_f = 20, kT = 1: K is Gamma(10, 1). The start
# values differ: the thermostat scales all velocities by one factor, so
# equal oscillators would stay equal.
n = 20
rng = random.Random(4)
x = [[rng.gauss(0.0, 1.0)] for _ in range(n)]
v = [[rng.gauss(0.0, 1.0)] for _ in range(n)]
_, _, ks, eff = stochastic_velocity_rescaling(x, v, [1.0] * n, harmonic(1.0), 0.05, 6000, 1.0, 0.1, n, rng)
(mean, se_mean), (var, se_var) = batch_stats(ks[500:])
assert abs(mean - 10.0) < 4 * se_mean + 0.05
assert abs(var - 10.0) < 4 * se_var + 0.3
assert se_mean < 0.3 and se_var < 1.5
# the effective energy drifts only by the Verlet error
assert max(eff) - min(eff) < 0.05
def test_free_particles_sample_the_gamma_law_for_any_step():
# With no forces the rescaling is the whole dynamics, and it is exact.
nf = 5
rng = random.Random(8)
x = [[0.0] for _ in range(nf)]
v = [[1.0] for _ in range(nf)]
_, _, ks, _ = stochastic_velocity_rescaling(x, v, [1.0] * nf, free(), 1.0, 8000, 1.0, 0.2, nf, rng)
(mean, se_mean), (var, se_var) = batch_stats(ks)
assert abs(mean - 2.5) < 4 * se_mean
assert abs(var - 2.5) < 4 * se_var
def test_one_draw_has_the_exact_conditional_mean_and_variance():
# The SDE dK = (K0 - K) dt / tau + 2 sqrt(K K0 / N_f) dW / sqrt(tau) gives
# E[K'] = K0 + (K - K0) c and
# Var[K'] = 2 (1 - c) (K0 / N_f) (2 c K + (1 - c) K0) for c = exp(-h / tau).
nf, k0, k = 6, 3.0, 4.0
c = math.exp(-0.5)
rng = random.Random(3)
draws = [rescale_factor(k, k0, nf, c, rng) ** 2 * k for _ in range(20000)]
mean = sum(draws) / len(draws)
var = sum((d - mean) ** 2 for d in draws) / len(draws)
exact_var = 2 * (1 - c) * (k0 / nf) * (2 * c * k + (1 - c) * k0)
assert mean == pytest.approx(k0 + (k - k0) * c, abs=4 * math.sqrt(exact_var / len(draws)))
assert var == pytest.approx(exact_var, rel=0.05)
def test_canonical_law_is_invariant_under_one_draw():
# Start K from Gamma(N_f / 2, kT); after one rescaling K is still
# Gamma(N_f / 2, kT), with mean and variance N_f kT / 2.
nf, kT = 4, 1.0
rng = random.Random(6)
c = math.exp(-1.0)
out = []
for _ in range(20000):
k = rng.gammavariate(nf / 2, kT)
out.append(rescale_factor(k, nf * kT / 2, nf, c, rng) ** 2 * k)
mean = sum(out) / len(out)
var = sum((d - mean) ** 2 for d in out) / len(out)
assert mean == pytest.approx(2.0, abs=4 * math.sqrt(2.0 / len(out)))
assert var == pytest.approx(2.0, rel=0.08)
def test_bad_arguments_raise():
with pytest.raises(ValueError):
stochastic_velocity_rescaling([[0.0]], [[1.0]], [1.0], free(), 0.1, 1, 1.0, 0.0, 1, random.Random(1))
History
Berendsen and coworkers (1984) introduced weak coupling, which relaxes the kinetic energy toward the target but suppresses its fluctuations. Bussi, Donadio and Parrinello (2007) added a stochastic term that gives the canonical law, showed how to draw the exact solution over one step, and defined the effective energy. In the same year Bussi and Parrinello studied the effective energy for Langevin dynamics. The thermostat is the v-rescale option of GROMACS and is available in many other codes.
References
- Giovanni Bussi, Davide Donadio and Michele Parrinello, Canonical sampling through velocity rescaling, Journal of Chemical Physics 126, 014101, 2007, the stochastic equation for the kinetic energy, its exact solution over a time step, the effective energy and the tests on water and other systems
- Giovanni Bussi and Michele Parrinello, Accurate sampling using Langevin dynamics, Physical Review E 75, 056707, 2007, the effective energy as a check of stochastic thermostats and the relation between global and local thermostats
- H. J. C. Berendsen, J. P. M. Postma, W. F. van Gunsteren, A. DiNola and J. R. Haak, Molecular dynamics with coupling to an external bath, Journal of Chemical Physics 81(8), 1984, 3684-3690, the weak coupling equation for the temperature, which is the drift part of the method
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 BYYCSC Edit this page History Report an error Markdown