Algorithm Search⌘K

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
Properties
randomizediterativerandomizednot symmetricnot symplectic
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 xi∈Rdx_i \in \mathbb{R}^d, velocities viv_i and masses mim_i of NN particles, a force routine for fi=−∇iUf_i = -\nabla_i U, a time step hh, a number of steps SS, the target kBTk_B T, the coupling time τ>0\tau > 0, the number NfN_f of degrees of freedom and a random number source. In the implementation Nf=dNN_f = dN; with the total momentum fixed, use Nf=dN−dN_f = dN - d, and remove also one degree of freedom for each constraint. Let K0=NfkBT/2K_0 = N_f k_B T / 2. Bussi, Donadio and Parrinello (2007) let the kinetic energy follow

dK=K0−Kτ dt+2KK0Nf τ dW,dK = \frac{K_0 - K}{\tau}\, dt + 2\sqrt{\frac{K K_0}{N_f\, \tau}}\, dW,

with a Wiener process WW. The drift is the Berendsen equation for KK. The stationary law of this equation is the canonical law of KK, the gamma law with density proportional to KNf/2−1e−K/kBTK^{N_f/2 - 1} e^{-K/k_B T}. The output is the trajectory, the kinetic energy after each step and the effective energy

H~=K+U−∑(the changes of K made by the thermostat),\tilde H = K + U - \sum (\text{the changes of } K \text{ made by the thermostat}),

which is conserved up to the error of the integrator.

The algorithm

  1. STOCHASTIC-VELOCITY-RESCALING(x, v, m, FORCES, h, S, kT, tau, N_f)
  2. 1(U, f) ← FORCES(x); K_0 ← N_f kT / 2; c ← exp(-h / tau); sigma² ← (1 - c) K_0 / N_f; Q ← 0
  3. 2for step ← 1 to S do
  4. 3v_i ← v_i + (h / 2) f_i / m_i for each particle i ▷ velocity Verlet
  5. 4x_i ← x_i + h v_i for each particle i
  6. 5(U, f) ← FORCES(x)
  7. 6v_i ← v_i + (h / 2) f_i / m_i for each particle i
  8. 7K ← Σ_i m_i |v_i|² / 2
  9. 8R_1 ← a standard normal number
  10. 9S_g ← 2 GAMMA((N_f - 1) / 2, 1), or 0 if N_f = 1 ▷ chi-squared with N_f - 1 degrees of freedom
  11. 10K' ← (sqrt(c K) + sigma R_1)² + sigma² S_g
  12. 11alpha ← sqrt(K' / K), with the sign of sqrt(c K) + sigma R_1
  13. 12v_i ← alpha v_i for each particle i
  14. 13Q ← Q + (K' - K) ▷ heat from the bath
  15. 14record K' and the effective energy K' + U - Q
  16. 15return (x, v, the recorded K', the recorded effective energies)

Lines L8 to L10 draw the exact solution of the equation for KK over a time hh. The equation is the law of ∑aya2\sum_a y_a^2 for NfN_f independent Ornstein-Uhlenbeck processes yay_a, and by symmetry one of them can be taken along the current direction: it gives the term with R1R_1, and the other Nf−1N_f - 1 give the chi-squared term. For τ→∞\tau \to \infty, c=1c = 1 and K′=KK' = K, so the method is plain velocity Verlet. For τ→0\tau \to 0, c=0c = 0 and K′K' is a fresh draw from the canonical law at each step.

Example

One rescaling by hand. Take K=4K = 4, K0=1K_0 = 1, Nf=2N_f = 2 and h/τ=0.5h/\tau = 0.5, so c=e−0.5=0.606531c = e^{-0.5} = 0.606531 and σ2=(1−c)K0/Nf=0.196735\sigma^2 = (1 - c) K_0 / N_f = 0.196735, σ=0.443548\sigma = 0.443548. With the draws R1=0.5R_1 = 0.5 and Sg=1S_g = 1:

quantity cK\sqrt{cK} cK+σR1\sqrt{cK} + \sigma R_1 K′K' α\alpha
value 1.557602 1.779375 3.362912 0.916912

Over many draws the mean of K′K' is cK+(1−c)K0=2.819592cK + (1 - c)K_0 = 2.819592, the Berendsen value, and the variance is 2(1−c)(K0/Nf)(2cK+(1−c)K0)=2.0640282(1 - c)(K_0/N_f)(2cK + (1 - c)K_0) = 2.064028. Berendsen gives the same mean with variance 0.

Canonical fluctuations. 20 harmonic oscillators in one dimension with m=k=kBT=1m = k = k_B T = 1 in reduced units, Nf=20N_f = 20, random normal start values (seed 4), h=0.05h = 0.05 and 40000 steps, of which the first 2000 are dropped. The canonical law of KK is gamma with mean and variance Nf/2=10N_f/2 = 10. Errors are batch-means standard errors with 20 batches.

τ\tau mean of KK variance of KK spread of H~\tilde H
0.1 10.006±0.04310.006 \pm 0.043 9.93±0.169.93 \pm 0.16 0.0167
1 9.997±0.1139.997 \pm 0.113 9.41±0.319.41 \pm 0.31 0.0148
10 10.014±0.31710.014 \pm 0.317 9.29±0.839.29 \pm 0.83 0.0126

These are measurements. The mean and the variance agree with 10 for all τ\tau. A larger τ\tau 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 h=1h = 1, τ=0.2\tau = 0.2 and 8000 steps (seed 8) give a mean of KK of 2.461±0.0182.461 \pm 0.018 and a variance of 2.40±0.062.40 \pm 0.06, against 2.5 and 2.5.

Correctness

The proof in proofs/correctness.md shows:

  1. A representation. K=∑aya2K = \sum_a y_a^2 for NfN_f independent Ornstein-Uhlenbeck processes solves the equation for KK in law.
  2. The exact step. Lines L8 to L10 draw K′K' with the law of the solution at time hh, for any hh and τ\tau.
  3. The canonical law of KK is stationary. It is the gamma law with shape Nf/2N_f / 2 and scale kBTk_B T.
  4. The canonical distribution is kept by the rescaling. Under the canonical law, KK and the direction of the scaled velocity vector are independent, and the rescaling changes only KK.
  5. The effective energy changes only in the Verlet parts.
  6. The sign of α\alpha does not change the law; it keeps the velocity path continuous as h→0h \to 0.

So the method samples the canonical ensemble up to the O(h2)O(h^2) 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 K0=NfkBT/2K_0 = N_f k_B T / 2, c=e−h/τc = e^{-h/\tau} and σ2=(1−c)K0/Nf\sigma^2 = (1 - c) K_0 / N_f. The thermostat of Bussi, Donadio and Parrinello (2007) lets KK follow the stochastic differential equation

dK=K0−Kτ dt+2KK0Nfτ dW.(1)dK = \frac{K_0 - K}{\tau}\, dt + 2 \sqrt{\frac{K K_0}{N_f \tau}}\, dW. \qquad (1)

Claim 1 (a representation of (1)). Let y1,…,yNfy_1, \ldots, y_{N_f} be independent Ornstein-Uhlenbeck processes dya=−ya2τdt+K0Nfτ dBady_a = -\frac{y_a}{2\tau} dt + \sqrt{\frac{K_0}{N_f \tau}}\, dB_a. Then K=∑aya2K = \sum_a y_a^2 solves (1) in law.

Proof. By the Ito formula,

dK=∑a(2ya dya+K0Nfτdt)=K0−Kτdt+2K0Nfτ∑aya dBa.dK = \sum_a \bigl(2 y_a\, dy_a + \tfrac{K_0}{N_f \tau} dt\bigr) = \frac{K_0 - K}{\tau} dt + 2\sqrt{\frac{K_0}{N_f \tau}} \sum_a y_a\, dB_a.

The martingale ∑aya dBa\sum_a y_a\, dB_a has quadratic variation ∑aya2 dt=K dt\sum_a y_a^2\, dt = K\, dt, so it is K dW\sqrt{K}\, dW for a Brownian motion WW (Levy's characterization). This gives (1). The coefficients of (1) satisfy the Yamada-Watanabe condition, so the solution is unique in law. □\square

Claim 2 (the exact step). Given K(0)=KK(0) = K, the law of K(h)K(h) is the law of

K′=(cK+σR1)2+σ2S,K' = \bigl(\sqrt{cK} + \sigma R_1\bigr)^2 + \sigma^2 S,

with R1R_1 standard normal and SS chi-squared with Nf−1N_f - 1 degrees of freedom, independent. Lines L8 to L10 draw K′K' this way.

Proof. The law of (ya)(y_a) is invariant under rotations of RNf\mathbb{R}^{N_f}, so we may start from y(0)=(K,0,…,0)y(0) = (\sqrt K, 0, \ldots, 0). The exact Ornstein-Uhlenbeck step is ya(h)=e−h/(2τ)ya(0)+sRay_a(h) = e^{-h/(2\tau)} y_a(0) + s R_a, with s2=K0Nfτ⋅τ(1−e−h/τ)=σ2s^2 = \frac{K_0}{N_f \tau} \cdot \tau (1 - e^{-h/\tau}) = \sigma^2 and independent standard normals RaR_a. So K(h)=(cK+σR1)2+σ2∑a≥2Ra2K(h) = (\sqrt{c K} + \sigma R_1)^2 + \sigma^2 \sum_{a \ge 2} R_a^2, and ∑a≥2Ra2\sum_{a \ge 2} R_a^2 is chi-squared with Nf−1N_f - 1 degrees of freedom. Line L9 draws it as 2 Γ((Nf−1)/2,1)2\,\Gamma((N_f - 1)/2, 1), which has this law. □\square

So the rescaling has no time step error: for any hh and τ\tau it draws the solution of (1) at time hh. From Claim 2, E[K′]=cK+(1−c)K0\mathbb{E}[K'] = cK + (1 - c)K_0 and Var⁡[K′]=4cKσ2+2Nfσ4\operatorname{Var}[K'] = 4cK\sigma^2 + 2N_f\sigma^4, the values the tests check.

Claim 3 (the canonical law of KK is stationary). If KK has the gamma law with shape Nf/2N_f/2 and scale kBTk_B T, so does K′K'.

Proof. The stationary law of each yay_a is normal with variance K0/(Nfτ)2⋅1/(2τ)=K0/Nf=kBT/2\frac{K_0/(N_f\tau)}{2 \cdot 1/(2\tau)} = K_0/N_f = k_B T/2. So the stationary law of K=∑aya2K = \sum_a y_a^2 is kBT2χNf2\frac{k_B T}{2} \chi^2_{N_f}, the gamma law with shape Nf/2N_f/2 and scale kBTk_B T. Under the canonical distribution, uia=mi/2 viau_{ia} = \sqrt{m_i/2}\, v_{ia} are independent normals with variance kBT/2k_B T/2, and K=∑uia2K = \sum u_{ia}^2 has this law. □\square

Claim 4 (the canonical distribution is kept). If (x,v)(x, v) has the canonical density before line L7, then after line L12 it still has it.

Proof. Write uu for the vector of the uiau_{ia}, of dimension NfN_f. Under the canonical density, xx is independent of uu, and uu is a centered normal vector with covariance kBT2I\frac{k_B T}{2} I. So ∣u∣2=K|u|^2 = K and the direction u/∣u∣u / |u| are independent, and the direction is uniform on the sphere. Line L12 multiplies uu by α\alpha with α2=K′/K\alpha^2 = K'/K, so the direction stays the same up to a sign that does not depend on the direction, and KK becomes K′K'. By Claim 3, K′K' has the gamma law, and it is independent of the direction and of xx. So the new uu has the same law as before. □\square

The velocity Verlet part keeps the canonical density only up to its O(h2)O(h^2) 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 Qn=∑k≤n(Kk′−Kk)Q_n = \sum_{k \le n} (K'_k - K_k) be the sum of the changes of KK made by the thermostat in the first nn steps (line L13). Then H~n=K+U−Qn\tilde H_n = K + U - Q_n (line L14) changes only in the Verlet parts: H~n−H~n−1\tilde H_n - \tilde H_{n-1} is the change of K+UK + U in the Verlet part of step nn.

Proof. In step nn the thermostat changes KK by Kn′−KnK'_n - K_n and adds the same amount to QQ. □\square

So a drift of H~\tilde H measures the integration error alone, as the drift of HH does in a run without a thermostat.

Claim 6 (the sign). The sign of α\alpha is the sign of cK+σR1\sqrt{cK} + \sigma R_1, the first component of y(h)y(h) in Claim 2. The law of K′K' does not depend on this choice, and Claim 4 holds for either sign; the sign keeps the velocity path continuous in the limit h→0h \to 0. □\square

Complexity

Each step does one force evaluation, O(N)O(N) work for the kinetic energy and the scaling, one normal draw and one gamma draw. A gamma draw takes O(1)O(1) expected time with the usual rejection methods. With the all-pairs forces of the molecular dynamics page, SS steps take O(SN2)O(S N^2) time. The extra space is O(N)O(N) for the copies of xx and vv.

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 NfN_f is large, since the relative fluctuation of KK is 2/Nf\sqrt{2/N_f}. 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 τ\tau (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 NfN_f.
  • 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 KK with the Euler-Maruyama method works for small h/τh/\tau, 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 NfN_f. The target is K0=NfkBT/2K_0 = N_f k_B T / 2, so constraints and a fixed centre of mass must be counted, or the temperature is wrong.
  • Zero kinetic energy. The factor K′/K\sqrt{K'/K} needs K>0K > 0. 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 NfN_f, summing Nf−1N_f - 1 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 H~\tilde H 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.

stochastic_velocity_rescaling.pyI0RawGitHub
# 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

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

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