Algorithm Search⌘K

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
Properties
deterministiciterativenot symmetricnot symplectic
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 λ\lambda after each step. The factor is chosen so that the kinetic temperature relaxes toward the target as dT/dt=(T0−T)/τdT/dt = (T_0 - T)/\tau, with a coupling time τ\tau 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 xi∈Rdx_i \in \mathbb{R}^d, velocities viv_i and masses mim_i of NN particles, a force field with forces fi=−∇iUf_i = -\nabla_i U, a time step hh, a number of steps SS, the target temperature kBT0k_B T_0, the coupling time τ≥h\tau \ge h and the number of degrees of freedom NfN_f used for the kinetic temperature. The target kinetic energy is K0=12NfkBT0K_0 = \frac12 N_f k_B T_0, and the kinetic temperature of a state is kBT=2K/Nfk_B T = 2K/N_f. The output is the trajectory and the kinetic energy after each step. The goal is a temperature that follows

dTdt=T0−Tτ.\frac{dT}{dt} = \frac{T_0 - T}{\tau}.

No ensemble is the goal. This is the reason the method has no sampling guarantee.

The algorithm

  1. BERENDSEN-THERMOSTAT(x, v, m, FORCES, h, S, kT0, tau, N_f)
  2. 1(U, f) ← FORCES(x); K0 ← N_f kT0 / 2
  3. 2for step ← 1 to S do
  4. 3v_i ← v_i + (h / 2) f_i / m_i for each particle i ▷ half kick
  5. 4x_i ← x_i + h v_i for each particle i ▷ drift
  6. 5(U, f) ← FORCES(x)
  7. 6v_i ← v_i + (h / 2) f_i / m_i for each particle i ▷ half kick
  8. 7K ← sum_i m_i |v_i|^2 / 2
  9. 8lambda ← sqrt(1 + (h / tau)(K0 / K - 1))
  10. 9v_i ← lambda v_i for each particle i
  11. 10record lambda^2 K
  12. 11return (x, v, the recorded kinetic energies)

The scaling of line L9 changes the kinetic energy to λ2K=K+hτ(K0−K)\lambda^2 K = K + \frac{h}{\tau}(K_0 - K), one explicit Euler step of the relaxation equation. With τ=h\tau = h it sets K=K0K = K_0 exactly in each step, the plain velocity rescaling. As τ→∞\tau \to \infty the step becomes velocity Verlet. The implementation skips the scaling when K=0K = 0 and raises an error for τ<h\tau < h, where λ2\lambda^2 can be negative.

Example

Free particles by hand. Four free particles on a line with m=1m = 1 and v=2v = 2, so K=8K = 8. Let kBT0=1k_B T_0 = 1 and Nf=4N_f = 4, so K0=2K_0 = 2, and h=0.1h = 0.1, τ=1\tau = 1. In step 1, the Verlet part changes nothing, line L8 gives λ2=1+0.1⋅(2/8−1)=0.925\lambda^2 = 1 + 0.1 \cdot (2/8 - 1) = 0.925, and KK becomes 8⋅0.925=7.48 \cdot 0.925 = 7.4. Each step multiplies K−K0K - K_0 by 1−h/τ=0.91 - h/\tau = 0.9:

step 1 2 3 4 5
KK 7.4 6.86 6.374 5.9366 5.54294

After nn steps, K−2=6⋅0.9nK - 2 = 6 \cdot 0.9^n, and KK tends to 2 with no fluctuation at all. In the canonical ensemble, KK for Nf=4N_f = 4 has mean 2 and variance 2.

Twenty oscillators. Take 20 independent oscillators on a line with m=k=kBT0=1m = k = k_B T_0 = 1, started at xi=1+0.05ix_i = 1 + 0.05i for i=0,…,19i = 0, \ldots, 19 with v=0v = 0, so Nf=20N_f = 20. The canonical law of KK has mean 10 and variance 10. Run 3000 steps with h=0.05h = 0.05 and drop the first 1000:

τ\tau mean of KK variance of KK
0.1 10.0025 0.00477
0.5 10.0000 6.1×10−136.1 \times 10^{-13}
2 9.99976 1.0×10−41.0 \times 10^{-4}

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 KK 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:

  1. The factor is real for K>0K > 0 and τ≥h\tau \ge h.
  2. One scaling gives K′=K+hτ(K0−K)K' = K + \frac{h}{\tau}(K_0 - K), the explicit Euler step of dK/dt=(K0−K)/τdK/dt = (K_0 - K)/\tau.
  3. Free particles relax as Kn−K0=(Kinit−K0)(1−h/τ)nK_n - K_0 = (K_{\text{init}} - K_0)(1 - h/\tau)^n, exactly.
  4. Not canonical. For free particles the law of KnK_n tends to a point mass at K0K_0, while the canonical law of KK is a gamma law with variance 12Nf(kBT0)2\frac12 N_f (k_B T_0)^2.
  5. Weak coupling limit. As τ→∞\tau \to \infty 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 K0=NfkBT/2K_0 = N_f k_B T / 2 the target kinetic energy and τ≥h\tau \ge h the coupling time.

Claim 1 (the scale factor is real). If K>0K > 0 and τ≥h\tau \ge h, then λ2=1+hτ(K0K−1)≥0\lambda^2 = 1 + \frac{h}{\tau}\bigl(\frac{K_0}{K} - 1\bigr) \ge 0, so line L8 is defined.

Proof. K0/K>0K_0 / K > 0, so λ2>1−h/τ≥0\lambda^2 > 1 - h / \tau \ge 0. □\square

For τ<h\tau < h and KK much larger than K0K_0, λ2\lambda^2 is negative. The implementation raises an error for τ<h\tau < h.

Claim 2 (one scaling). Let KK be the kinetic energy after the Verlet part of a step (line L7). After line L9 the kinetic energy is

K′=λ2K=K+hτ(K0−K).K' = \lambda^2 K = K + \frac{h}{\tau}(K_0 - K).

Proof. Line L9 multiplies each velocity by λ\lambda, and KK is quadratic in the velocities, so K′=λ2KK' = \lambda^2 K. Insert λ2\lambda^2 from line L8. □\square

So the scaling is the explicit Euler step, with step hh, for dK/dt=(K0−K)/τdK / dt = (K_0 - K) / \tau. This is the equation that Berendsen et al. (1984) give for the temperature.

Claim 3 (free particles). If f=0f = 0, then after nn steps Kn−K0=(Kinit−K0)(1−h/τ)nK_n - K_0 = (K_{\text{init}} - K_0)(1 - h/\tau)^n.

Proof. With f=0f = 0 the Verlet part does not change vv, so KK before line L9 of step nn is Kn−1K_{n-1}. Claim 2 gives Kn−K0=(1−h/τ)(Kn−1−K0)K_n - K_0 = (1 - h/\tau)(K_{n-1} - K_0). Induction on nn gives the claim. □\square

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, KK has the gamma law with shape Nf/2N_f / 2 and scale kBTk_B T, with variance Nf(kBT)2/2>0N_f (k_B T)^2 / 2 > 0. For free particles and h≤τh \le \tau, Claim 3 gives ∣Kn−K0∣≤∣Kinit−K0∣(1−h/τ)n|K_n - K_0| \le |K_{\text{init}} - K_0| (1 - h/\tau)^n. For h<τh < \tau this tends to 0 for every start, so the law of KnK_n tends to the point mass at K0K_0, with variance 0. For h=τh = \tau, Kn=K0K_n = K_0 after one step. In both cases the limit is not the gamma law. □\square

The free gas is a simple case, but the cause is general: the scaling is deterministic and always pushes KK toward K0K_0, and nothing adds the fluctuations back. On the harmonic test of the page, the variance of KK 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 τ→∞\tau \to \infty with KK bounded away from 0, λ→1\lambda \to 1, and the step tends to the velocity Verlet step.

Proof. ∣λ2−1∣=hτ∣K0/K−1∣|\lambda^2 - 1| = \frac{h}{\tau} |K_0 / K - 1|, which tends to 0. □\square

Complexity

Each step does one force evaluation and O(N)O(N) other work. With the all-pairs forces of the molecular dynamics page, SS steps cost O(SN2)O(S N^2) time and the thermostat adds O(SN)O(S N). The extra space is O(N)O(N).

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 KK tends to K0K_0.
  • Deterministic. The same input gives the same run.
  • Not time-reversible and not symplectic. The factor depends on KK, and the step does not keep phase-space volume.
  • Momentum. A uniform scaling keeps ∑imivi=0\sum_i m_i v_i = 0 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 KK 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. τ=h\tau = h sets K=K0K = K_0 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 NfN_f. The target K0K_0 uses NfN_f. 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 τ\tau close to hh, the method is nearly plain rescaling, and the dynamics are disturbed strongly. Values of τ\tau 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.

berendsen_thermostat.pyI0RawGitHub
# 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 τ\tau, and of the pressure with a time constant τP\tau_P. 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

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

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