Algorithmcore
Berendsen thermostat
Also called weak coupling thermostat.
Rescales velocities each step so the temperature relaxes exponentially toward the target; it is stable but does not sample the canonical ensemble.
- Time
- O(S N^2) worst
- Space
- O(N) extra
- Where
- N = the number of particles; S = the number of time steps
- Model
- Real RAM
- Properties
- deterministiciterativenot symmetricnot symplectic
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Herman J. C. Berendsen, J. P. M. Postma, Wilfred F. van Gunsteren, A. DiNola, J. R. Haak, 1984
The Berendsen thermostat, also called weak coupling, controls the temperature of a molecular dynamics run by scaling all velocities by a factor after each step. The factor is chosen so that the kinetic temperature relaxes toward the target as , with a coupling time that the user sets. The method is simple, deterministic and very stable, so it brings a system to the target temperature quickly and smoothly. It does not sample the canonical ensemble: the fluctuations of the kinetic energy are too small, and for free particles they vanish. Use it to equilibrate, and use a canonical method such as stochastic velocity rescaling for production runs.
In plain words
After each step the program measures how hot the system is. If it is too hot, it slows all atoms down by the same small fraction. If it is too cold, it speeds them all up. The size of the correction depends on how far the temperature is from the target and on a time constant: a short time constant corrects hard and a long one corrects gently.
This is like a room thermostat that reacts smoothly instead of switching on and off. It works well to reach a temperature. But in a real system at a fixed temperature, the energy of the atoms goes up and down by a known amount. This method removes most of that natural variation, so averages that depend on it come out wrong.
The problem
The input is the positions , velocities and masses of particles, a force field with forces , a time step , a number of steps , the target temperature , the coupling time and the number of degrees of freedom used for the kinetic temperature. The target kinetic energy is , and the kinetic temperature of a state is . The output is the trajectory and the kinetic energy after each step. The goal is a temperature that follows
No ensemble is the goal. This is the reason the method has no sampling guarantee.
The algorithm
BERENDSEN-THERMOSTAT(x, v, m, FORCES, h, S, kT0, tau, N_f)- 1
(U, f) ← FORCES(x); K0 ← N_f kT0 / 2 - 2
for step ← 1 to S do - 3
v_i ← v_i + (h / 2) f_i / m_i for each particle i ▷ half kick - 4
x_i ← x_i + h v_i for each particle i ▷ drift - 5
(U, f) ← FORCES(x) - 6
v_i ← v_i + (h / 2) f_i / m_i for each particle i ▷ half kick - 7
K ← sum_i m_i |v_i|^2 / 2 - 8
lambda ← sqrt(1 + (h / tau)(K0 / K - 1)) - 9
v_i ← lambda v_i for each particle i - 10
record lambda^2 K - 11
return (x, v, the recorded kinetic energies)
The scaling of line L9 changes the kinetic energy to , one explicit Euler step of the relaxation equation. With it sets exactly in each step, the plain velocity rescaling. As the step becomes velocity Verlet. The implementation skips the scaling when and raises an error for , where can be negative.
Example
Free particles by hand. Four free particles on a line with and , so . Let and , so , and , . In step 1, the Verlet part changes nothing, line L8 gives , and becomes . Each step multiplies by :
| step | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|
| 7.4 | 6.86 | 6.374 | 5.9366 | 5.54294 |
After steps, , and tends to 2 with no fluctuation at all. In the canonical ensemble, for has mean 2 and variance 2.
Twenty oscillators. Take 20 independent oscillators on a line with , started at for with , so . The canonical law of has mean 10 and variance 10. Run 3000 steps with and drop the first 1000:
| mean of | variance of | |
|---|---|---|
| 0.1 | 10.0025 | 0.00477 |
| 0.5 | 10.0000 | |
| 2 | 9.99976 |
These are measurements. The mean is right, and the variance is wrong by a factor of more than 2000 for all three coupling times. On this harmonic system the scaling drives the oscillators into a state where hardly changes; in a system with interactions the effect is weaker but of the same kind.
Correctness
The method is not a sampler, so there is no claim of correctness for an ensemble. The proof in proofs/correctness.md shows what the method does:
- The factor is real for and .
- One scaling gives , the explicit Euler step of .
- Free particles relax as , exactly.
- Not canonical. For free particles the law of tends to a point mass at , while the canonical law of is a gamma law with variance .
- Weak coupling limit. As the step tends to velocity Verlet.
The scaling also changes the volume of phase space at each step, so there is no Liouville argument for any invariant density. The dynamics are not physical either: the scaling acts on all particles at once, so the temperature of one part of the system depends on the rest at once.
Proof: The Berendsen scaling relaxes the kinetic energy at rate 1 / tau, and it does not give the canonical distributionfull
We use the pseudocode of the page, with the target kinetic energy and the coupling time.
Claim 1 (the scale factor is real). If and , then , so line L8 is defined.
Proof. , so .
For and much larger than , is negative. The implementation raises an error for .
Claim 2 (one scaling). Let be the kinetic energy after the Verlet part of a step (line L7). After line L9 the kinetic energy is
Proof. Line L9 multiplies each velocity by , and is quadratic in the velocities, so . Insert from line L8.
So the scaling is the explicit Euler step, with step , for . This is the equation that Berendsen et al. (1984) give for the temperature.
Claim 3 (free particles). If , then after steps .
Proof. With the Verlet part does not change , so before line L9 of step is . Claim 2 gives . Induction on gives the claim.
Claim 4 (not canonical). There is a system for which the Berendsen dynamics does not have the canonical distribution as a limit: free particles.
Proof. In the canonical ensemble, has the gamma law with shape and scale , with variance . For free particles and , Claim 3 gives . For this tends to 0 for every start, so the law of tends to the point mass at , with variance 0. For , after one step. In both cases the limit is not the gamma law.
The free gas is a simple case, but the cause is general: the scaling is deterministic and always pushes toward , and nothing adds the fluctuations back. On the harmonic test of the page, the variance of falls far below the canonical value (a measurement, given on the page). The scaling also does not keep the volume of phase space, so there is no Liouville argument for any invariant density.
Claim 5 (weak coupling limit). As with bounded away from 0, , and the step tends to the velocity Verlet step.
Proof. , which tends to 0.
Complexity
Each step does one force evaluation and other work. With the all-pairs forces of the molecular dynamics page, steps cost time and the thermostat adds . The extra space is .
Properties
- Ensemble. None that is known in closed form. It is not canonical, and it is not microcanonical, since the energy changes. The mean of tends to .
- Deterministic. The same input gives the same run.
- Not time-reversible and not symplectic. The factor depends on , and the step does not keep phase-space volume.
- Momentum. A uniform scaling keeps if it is 0 at the start. If it is not 0, the scaling acts on the centre of mass motion too.
Variants and improvements
- Stochastic velocity rescaling. Bussi, Donadio and Parrinello (2007) add a noise term with the right size to the same relaxation equation, so that has the canonical law. Stochastic velocity rescaling keeps the smooth control and samples the canonical ensemble. With the noise set to zero it is the Berendsen method.
- Plain rescaling. sets in every step. This is the strongest form and has the smallest fluctuations.
- Berendsen barostat. The same paper scales the coordinates and the box by a factor that relaxes the pressure to a target. It has the same problem: the volume fluctuations are wrong. The Parrinello-Rahman barostat gives a box with its own dynamics instead.
- Group coupling. Scale each group of atoms, for example the solute and the solvent, with its own factor, to reduce the transfer of energy between groups.
When to use it
Use the Berendsen thermostat to equilibrate: to bring a system from a bad start, for example after energy minimization or after heating, to the target temperature without large swings. Then switch to a method that samples the canonical ensemble, such as stochastic velocity rescaling, the Nose-Hoover thermostat or Langevin dynamics. The use of the Berendsen thermostat for production runs is a habit from the time before these methods were common. It is not a method with a guarantee.
Pitfalls
- Wrong fluctuations. Any average that depends on the fluctuations is wrong: the heat capacity from energy fluctuations, the width of distributions, free energies from fluctuation formulas.
- The flying ice cube. Harvey, Tan and Cheatham (1998) showed that repeated velocity rescaling can move kinetic energy from the internal motions into the motion of the centre of mass and into slow modes. A molecule then moves as a cold, rigid body. Remove the centre of mass motion and couple groups separately, or use a canonical method.
- A wrong . The target uses . If constraints or a fixed centre of mass are not counted, the temperature is wrong by the ratio of the two counts.
- Short coupling times. With close to , the method is nearly plain rescaling, and the dynamics are disturbed strongly. Values of around 0.1 to 1 ps are common in biomolecular codes; these are choices.
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/berendsen-thermostat/. The authors are listed in prov/VZN3KE.jsonl.
"""Molecular dynamics with the Berendsen (weak coupling) thermostat.
The state is the positions x and the velocities v of N particles in d
dimensions, with masses m. Each step of length h is one velocity Verlet step,
followed by a scaling of all velocities by
lambda = sqrt(1 + (h / tau) (T0 / T - 1)),
where T = 2 K / (N_f k_B) is the kinetic temperature after the Verlet step,
T0 the target, tau the coupling time and N_f the number of degrees of
freedom (Berendsen et al. 1984). The scaling sets the new kinetic energy to
K + (h / tau) (K0 - K), with K0 = N_f k_B T0 / 2, so that without forces the
kinetic energy relaxes to K0 as (1 - h / tau)^n.
The method is deterministic. It does not sample the canonical ensemble: the
fluctuations of K are too small.
Cost: one force evaluation and Theta(N d) extra work per step.
"""
import math
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 berendsen_thermostat(
x: list[Vec], v: list[Vec], m: list[float], forces: ForceField, h: float,
steps: int, kT: float, tau: float, nf: int,
) -> tuple[list[Vec], list[Vec], list[float]]:
"""Run steps of velocity Verlet with Berendsen scaling toward kT.
nf is the number of degrees of freedom used for the kinetic temperature.
Returns the final positions, the final velocities and the kinetic energy
after each step. The inputs are not changed. Needs tau >= h.
"""
if h <= 0 or tau < h or kT <= 0 or nf <= 0:
raise ValueError("need h > 0, tau >= h, 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
_, f = forces(x) # @line L1
ks = []
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
_, 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
if k > 0:
lam = math.sqrt(1.0 + (h / tau) * (k0 / k - 1.0)) # @line L8
for vi in v:
for a in range(len(vi)):
vi[a] *= lam # @line L9
k *= lam * lam
ks.append(k) # @line L10
return x, v, ks # @line L11
test_berendsen_thermostat.py 54 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/berendsen-thermostat/. The authors are listed in prov/VZN3KE.jsonl.
import math
import pytest
from berendsen_thermostat import berendsen_thermostat, free, harmonic, kinetic
def test_free_particles_relax_geometrically_to_the_target():
# With no forces, K_(n+1) = lambda^2 K_n = K_n + (h / tau)(K0 - K_n),
# so K_n - K0 = (K_init - K0)(1 - h / tau)^n exactly.
n, h, tau = 4, 0.1, 1.0
x = [[0.0] for _ in range(n)]
v = [[2.0] for _ in range(n)]
_, _, ks = berendsen_thermostat(x, v, [1.0] * n, free(), h, 40, 1.0, tau, n)
k0, k_init = 2.0, 8.0
for step, k in enumerate(ks, start=1):
assert k == pytest.approx(k0 + (k_init - k0) * (1 - h / tau) ** step, rel=1e-12)
assert ks[:3] == pytest.approx([7.4, 6.86, 6.374], rel=1e-12)
def test_tau_equal_to_h_sets_the_target_in_one_step():
v = [[3.0, -1.0], [0.5, 2.0]]
_, v1, ks = berendsen_thermostat([[0.0, 0.0]] * 2, v, [1.0, 2.0], free(), 0.1, 1, 1.5, 0.1, 4)
assert ks[0] == pytest.approx(3.0, rel=1e-12)
assert kinetic(v1, [1.0, 2.0]) == pytest.approx(3.0, rel=1e-12)
def test_mean_is_right_but_kinetic_energy_fluctuations_are_suppressed():
# 20 oscillators in 1D, N_f = 20, kT = 1. In the canonical ensemble K has
# mean 10 and variance 10. The weak coupling keeps the mean near 10 and
# removes almost all of the fluctuation.
n = 20
x = [[1.0 + 0.05 * i] for i in range(n)]
v = [[0.0] for _ in range(n)]
_, _, ks = berendsen_thermostat(x, v, [1.0] * n, harmonic(1.0), 0.05, 3000, 1.0, 0.5, n)
tail = ks[1000:]
mean = sum(tail) / len(tail)
var = sum((k - mean) ** 2 for k in tail) / len(tail)
assert abs(mean - 10.0) < 0.1
assert var < 1.0 # canonical value 10
def test_weak_coupling_limit_is_velocity_verlet():
# tau much larger than the run: lambda is 1 to within h / tau.
x, v, _ = berendsen_thermostat([[1.0]], [[0.0]], [1.0], harmonic(1.0), 0.05, 200, 1.0, 1e12, 1)
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):
berendsen_thermostat([[0.0]], [[1.0]], [1.0], free(), 0.1, 1, 1.0, 0.05, 1)
History
Berendsen, Postma, van Gunsteren, DiNola and Haak (1984) proposed to couple a molecular dynamics system to an external bath by a first-order relaxation of the temperature with a time constant , and of the pressure with a time constant . The method became the default way to control temperature in biomolecular codes for many years. Its failure to give canonical fluctuations was known, and Harvey, Tan and Cheatham (1998) described the flying ice cube artefact. Bussi, Donadio and Parrinello (2007) added the missing noise and obtained a canonical method with the same structure.
References
- 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 coupling to a heat bath (the first-order equation for the temperature and the scaling factor lambda)
- Stephen C. Harvey, Robert K.-Z. Tan and Thomas E. Cheatham III, The flying ice cube, Velocity rescaling in molecular dynamics leads to violation of energy equipartition, Journal of Computational Chemistry 19(7), 1998, 726-740, the transfer of kinetic energy into the centre of mass motion under velocity rescaling
- Giovanni Bussi, Davide Donadio and Michele Parrinello, Canonical sampling through velocity rescaling, Journal of Chemical Physics 126(1), 2007, 014101, the comparison with the Berendsen thermostat, which their method contains as the limit without noise
- Michael P. Allen and Dominic J. Tildesley, Computer Simulation of Liquids, second edition, Oxford University Press, 2017, Chapter 3, molecular dynamics (the constant-temperature methods)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag VZN3KE Edit this page History Report an error Markdown