Algorithm Search⌘K

Algorithmcore

Nose-Hoover thermostat

Also called Nose-Hoover dynamics.

Adds a friction variable with its own equation of motion so that the extended dynamics, if ergodic, samples 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
deterministiciterativesymmetricnot symplectic
Origin
Shuichi Nose, William G. Hoover, 1984

The Nose-Hoover thermostat runs molecular dynamics at a fixed temperature with deterministic equations. It adds one variable, a friction coefficient ξ\xi, that slows the particles down when the kinetic energy is above its target and speeds them up when it is below. The friction has its own equation of motion with a mass QQ, so the control is smooth and has a memory. The extended system conserves an energy, and the canonical ensemble is a stationary density of its flow (a theorem). Time averages are canonical averages only if the motion is ergodic, which is a hypothesis: it fails for one harmonic oscillator and for other small or stiff systems, and Nose-Hoover chains are the usual repair.

In plain words

Think of a brake and an accelerator on every atom, both worked by one pedal. The pedal moves by itself. When the atoms move too fast on average, the pedal moves toward the brake, and when they are too slow, it moves toward the accelerator. The pedal has inertia, so it does not jump. It overshoots a little and swings back, and the temperature of the atoms swings around the target.

There is no randomness. The program can run forward and backward, and there is a total energy, which includes the pedal, that stays fixed. This is useful to check the program. The method gives the right statistics if the motion visits all states, and for some simple systems it does not.

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 kBTk_B T, the thermostat mass Q>0Q > 0, the number NfN_f of velocity components that the thermostat scales, and start values of ξ\xi and of the thermostat position η\eta (often 0). The output is the trajectory of the equations of Hoover (1985),

x˙i=vi,v˙i=fimi−ξvi,ξ˙=2K−NfkBTQ,η˙=ξ,\dot x_i = v_i, \qquad \dot v_i = \frac{f_i}{m_i} - \xi v_i, \qquad \dot \xi = \frac{2K - N_f k_B T}{Q}, \qquad \dot \eta = \xi,

with K=∑i12mi∣vi∣2K = \sum_i \frac12 m_i |v_i|^2, and the extended energy

H′=K+U+12Qξ2+NfkBT ηH' = K + U + \tfrac12 Q \xi^2 + N_f k_B T\, \eta

after each step, which the exact flow conserves. η\eta enters only H′H'. In the implementation Nf=dNN_f = dN. If the total momentum is fixed at 0, the momentum is a further conserved quantity, and the thermostat should use Nf=dN−dN_f = dN - d (see Pitfalls).

The algorithm

  1. NOSE-HOOVER(x, v, m, FORCES, h, S, kT, Q, N_f, xi, eta)
  2. 1(U, f) ← FORCES(x)
  3. 2for step ← 1 to S do
  4. 3(xi, eta) ← THERMOSTAT-HALF(v, xi, eta)
  5. 4v_i ← v_i + (h / 2) f_i / m_i for each particle i ▷ half kick
  6. 5x_i ← x_i + h v_i for each particle i ▷ drift
  7. 6(U, f) ← FORCES(x)
  8. 7v_i ← v_i + (h / 2) f_i / m_i for each particle i ▷ half kick
  9. 8(xi, eta) ← THERMOSTAT-HALF(v, xi, eta)
  10. 9record H' = K + U + Q xi^2 / 2 + N_f kT eta
  11. 10return (x, v, xi, eta, the recorded H')
  12. THERMOSTAT-HALF(v, xi, eta) ▷ exact flows for a time h / 2
  13. 11xi ← xi + (h / 4)(2K - N_f kT) / Q
  14. 12v_i ← exp(-xi h / 2) v_i for each particle i
  15. 13eta ← eta + (h / 2) xi
  16. 14xi ← xi + (h / 4)(2K - N_f kT) / Q ▷ K after the scaling

This is the splitting of Martyna, Tuckerman, Tobias and Klein (1996). The thermostat part is split into two exact flows: with vv fixed, ξ\xi moves at a constant rate (L11, L14), and with ξ\xi fixed, the velocities decay as e−ξte^{-\xi t} and η\eta grows as ξt\xi t (L12, L13). The palindrome of exact flows makes the step time-reversible and of order 2.

Example

One step by hand. One particle on a spring with m=k=kBT=Q=1m = k = k_B T = Q = 1 in reduced units, Nf=1N_f = 1, x=1x = 1, v=0v = 0, ξ=η=0\xi = \eta = 0 and h=0.1h = 0.1, so H′=0.5H' = 0.5.

line update value
L11 ξ←0+0.025(0−1)\xi \leftarrow 0 + 0.025 (0 - 1) ξ=−0.025\xi = -0.025
L12, L13 v=0v = 0 stays 0; η←0.05⋅(−0.025)\eta \leftarrow 0.05 \cdot (-0.025) η=−0.00125\eta = -0.00125
L14 ξ←−0.025−0.025\xi \leftarrow -0.025 - 0.025 ξ=−0.05\xi = -0.05
L4 to L7 velocity Verlet x=0.995x = 0.995, v=−0.09975v = -0.09975
L11 2K=0.00995002K = 0.0099500, ξ←−0.05+0.025(0.00995−1)\xi \leftarrow -0.05 + 0.025(0.00995 - 1) ξ=−0.0747512\xi = -0.0747512
L12 v←e0.0037376⋅(−0.09975)v \leftarrow e^{0.0037376} \cdot (-0.09975) v=−0.1001235v = -0.1001235
L13 η←−0.00125+0.05⋅(−0.0747512)\eta \leftarrow -0.00125 + 0.05 \cdot (-0.0747512) η=−0.0049876\eta = -0.0049876
L14 ξ←−0.0747512+0.025(0.0100247−1)\xi \leftarrow -0.0747512 + 0.025(0.0100247 - 1) ξ=−0.0995006\xi = -0.0995006

The particle is colder than the target, so ξ\xi becomes negative and the scaling speeds it up: ∣v∣|v| is larger than the 0.09975 of plain Verlet. The extended energy after the step is H′=0.4999875H' = 0.4999875.

The extended energy is conserved to second order. Two oscillators with k=1k = 1, masses 1 and 2, started at x=(1,0.3)x = (1, 0.3), v=(0,0.7)v = (0, 0.7), with Q=0.5Q = 0.5, kBT=1k_B T = 1 and Nf=2N_f = 2, run to t=20t = 20. The spread max⁡H′−min⁡H′\max H' - \min H' is

hh 0.1 0.05 0.025
spread of H′H' 0.03168 0.008336 0.002110

so it falls by a factor of about 4 when hh is halved. Running 300 steps forward, flipping vv and ξ\xi, and running 300 steps back recovers the start to 10−910^{-9}.

One oscillator is not ergodic. One oscillator with m=k=kBT=Q=1m = k = k_B T = Q = 1, Nf=1N_f = 1, from x=1x = 1, v=0v = 0, with h=0.05h = 0.05 and a sample every 10 steps to t=104t = 10^4, gives ⟨x2⟩=0.793\langle x^2 \rangle = 0.793 and ⟨x4⟩/⟨x2⟩2=1.538\langle x^4 \rangle / \langle x^2 \rangle^2 = 1.538. The canonical values are 1 and 3. The mean of 2K2K is 0.99915, close to NfkBT=1N_f k_B T = 1, as it must be for any bounded run. These are measurements: the trajectory stays near a torus and does not fill the phase space. The right mean temperature does not show that the distribution is right.

Correctness

The proof in proofs/correctness.md shows:

  1. The extended energy H′H' is conserved by the exact flow.
  2. The canonical density is stationary. The density exp⁡(−β(K+U+12Qξ2))\exp(-\beta(K + U + \frac12 Q\xi^2)) on (x,v,ξ)(x, v, \xi) solves the stationary Liouville equation, since the flow has divergence −Nfξ-N_f \xi. Its marginal in (x,v)(x, v) is canonical.
  3. The step is a palindrome of exact flows, so it is time-reversible and has order 2.
  4. Time reversal. With R(x,v,ξ,η)=(x,−v,−ξ,η)R(x, v, \xi, \eta) = (x, -v, -\xi, \eta), Ψh∘R∘Ψh=R\Psi_h \circ R \circ \Psi_h = R.
  5. The mean kinetic energy. The mean of 2K−NfkBT2K - N_f k_B T over the 4n4n updates of ξ\xi in nn steps is exactly Q(ξn−ξ0)/(nh)Q(\xi_n - \xi_0)/(nh), which tends to 0 if ξ\xi stays bounded. This needs no ergodicity.

So the method samples the canonical ensemble if the extended flow is ergodic on the set where H′H' and the other conserved quantities are fixed. This is a hypothesis, and it fails on the examples above. The dynamics are not physical in a strict sense, since the friction acts on all particles at once. The rule of thumb is that for a large system and a slow thermostat the effect on time correlations is small; this is not a theorem.

Proof: The Nose-Hoover equations keep the extended energy and the canonical density, and the splitting is reversiblefull

The Nose-Hoover equations for NN particles with NfN_f velocity components, the friction ξ\xi and the thermostat mass QQ are

x˙i=vi,miv˙i=fi(x)−ξmivi,Qξ˙=2K−NfkBT,η˙=ξ.(1)\dot x_i = v_i, \qquad m_i \dot v_i = f_i(x) - \xi m_i v_i, \qquad Q \dot \xi = 2K - N_f k_B T, \qquad \dot \eta = \xi. \qquad (1)

Here K=∑i12mi∣vi∣2K = \sum_i \frac12 m_i |v_i|^2 and f=−∇Uf = -\nabla U. In this proof NfN_f is the number of velocity components that the thermostat scales, which is NdN d in the implementation.

Claim 1 (the extended energy). The exact flow of (1) keeps H′=K+U+12Qξ2+NfkBTηH' = K + U + \frac12 Q \xi^2 + N_f k_B T \eta.

Proof. Along (1),

dH′dt=∑ivi⋅(fi−ξmivi)−∑ifi⋅vi+ξ(2K−NfkBT)+NfkBTξ=−2Kξ+2Kξ=0.□\frac{dH'}{dt} = \sum_i v_i \cdot (f_i - \xi m_i v_i) - \sum_i f_i \cdot v_i + \xi (2K - N_f k_B T) + N_f k_B T \xi = -2K\xi + 2K\xi = 0. \qquad \square

Claim 2 (the canonical density is stationary). The density ρ(x,v,ξ)∝exp⁡(−β(K+U+12Qξ2))\rho(x, v, \xi) \propto \exp\bigl(-\beta (K + U + \frac12 Q \xi^2)\bigr) satisfies the Liouville equation ∂tρ+∇⋅(ρF)=0\partial_t \rho + \nabla \cdot (\rho F) = 0 with ∂tρ=0\partial_t \rho = 0, where FF is the vector field of (1) on (x,v,ξ)(x, v, \xi).

Proof. We must show F⋅∇ln⁡ρ+∇⋅F=0F \cdot \nabla \ln \rho + \nabla \cdot F = 0. Only the velocity equations depend on their own variable: ∂v˙ia/∂via=−ξ\partial \dot v_{ia} / \partial v_{ia} = -\xi for each of the NfN_f components, so ∇⋅F=−Nfξ\nabla \cdot F = -N_f \xi. Next, ln⁡ρ=−β(K+U+12Qξ2)+const\ln \rho = -\beta (K + U + \frac12 Q\xi^2) + \text{const}, so

F⋅∇ln⁡ρ=−β(∑i∇iU⋅vi+∑imivi⋅(fimi−ξvi)+Qξ⋅2K−NfkBTQ)=−β(−2Kξ+2Kξ−NfkBTξ)=Nfξ.F \cdot \nabla \ln \rho = -\beta \Bigl( \sum_i \nabla_i U \cdot v_i + \sum_i m_i v_i \cdot \bigl(\tfrac{f_i}{m_i} - \xi v_i\bigr) + Q \xi \cdot \tfrac{2K - N_f k_B T}{Q} \Bigr) = -\beta \bigl( -2K\xi + 2K\xi - N_f k_B T \xi \bigr) = N_f \xi.

The sum is 0. □\square

The marginal of ρ\rho in (x,v)(x, v) is the canonical density. So time averages along (1) are canonical averages if the flow is ergodic on the set where H′H' and the other conserved quantities are fixed. This is a hypothesis. It fails for one harmonic oscillator, and for systems with extra conservation laws such as the total momentum without external forces.

Claim 3 (the splitting). Write (1) as the sum of three vector fields: VV, the kick v˙i=fi/mi\dot v_i = f_i / m_i; AA, the drift x˙i=vi\dot x_i = v_i; and TT, the thermostat part v˙i=−ξvi\dot v_i = -\xi v_i, ξ˙=(2K−NfkBT)/Q\dot \xi = (2K - N_f k_B T) / Q, η˙=ξ\dot \eta = \xi. One step of the algorithm is

Ψh=Th/2∘Vh/2∘Ah∘Vh/2∘Th/2,\Psi_h = T_{h/2} \circ V_{h/2} \circ A_h \circ V_{h/2} \circ T_{h/2},

where VtV_t and AtA_t are the exact flows and TtT_t is the symmetric composition Gt/2∘St∘Gt/2G_{t/2} \circ S_t \circ G_{t/2} of two exact flows: GsG_s, the flow of ξ˙=(2K−NfkBT)/Q\dot \xi = (2K - N_f k_B T)/Q with vv fixed, and StS_t, the flow of v˙i=−ξvi\dot v_i = -\xi v_i, η˙=ξ\dot \eta = \xi with ξ\xi fixed.

Proof. With vv fixed, KK is fixed, so GsG_s adds s(2K−NfkBT)/Qs (2K - N_f k_B T)/Q to ξ\xi: these are lines L11 and L14 with s=h/4s = h/4. With ξ\xi fixed, StS_t multiplies each velocity by e−ξte^{-\xi t} and adds ξt\xi t to η\eta: these are lines L12 and L13 with t=h/2t = h/2. Line L14 uses the kinetic energy after the scaling, as GG must. Lines L4 to L7 are Vh/2AhVh/2V_{h/2} A_h V_{h/2}, with the forces kept from the last evaluation as on the molecular dynamics page. Line L3 is Th/2T_{h/2} before the Verlet part and line L8 is Th/2T_{h/2} after it. □\square

Claim 4 (time reversal). Let R(x,v,ξ,η)=(x,−v,−ξ,η)R(x, v, \xi, \eta) = (x, -v, -\xi, \eta). Then Ψh∘R∘Ψh=R\Psi_h \circ R \circ \Psi_h = R.

Proof. For each of the exact flows ϕt\phi_t above, R∘ϕt∘R=ϕ−tR \circ \phi_t \circ R = \phi_{-t}: under v→−vv \to -v, ξ→−ξ\xi \to -\xi each equation of (1) changes sign on the left exactly when the time direction changes, and η\eta is a sum of ξ dt\xi\,dt, which also changes sign twice. So R∘Ψh∘RR \circ \Psi_h \circ R is the same composition with each tt replaced by −t-t, taken in the same order. Because the composition is a palindrome, this is the inverse Ψh−1\Psi_h^{-1}. □\square

A symmetric composition of flows of a split vector field is a method of order 2 (see operator splitting), so H′H' is kept up to O(h2)O(h^2) over a fixed time. The tests show the error falling by a factor 4 when hh is halved.

Claim 5 (the mean kinetic energy). Let KjK_j, j=1,…,4nj = 1, \ldots, 4n, be the kinetic energies used by the 4n4n applications of Gh/4G_{h/4} in nn steps, and ξn\xi_n the friction after step nn. Then

14n∑j=14n(2Kj−NfkBT)=Q(ξn−ξ0)nh.\frac{1}{4n} \sum_{j=1}^{4n} \bigl(2K_j - N_f k_B T\bigr) = \frac{Q (\xi_n - \xi_0)}{n h}.

So if ξ\xi stays bounded, the mean of 2Kj2K_j tends to NfkBTN_f k_B T as n→∞n \to \infty.

Proof. Only GG changes ξ\xi, and each application adds h4(2Kj−NfkBT)/Q\frac{h}{4}(2K_j - N_f k_B T)/Q. Sum over jj and multiply by 4Q/(4nh)4 Q / (4 n h). □\square

Claim 5 needs no ergodicity. So a run with the right mean temperature does not show that the distribution is canonical. The test of the page shows a single oscillator with the right mean of 2K2K and a wrong distribution of xx.

Claim 6 (large mass). As Q→∞Q \to \infty with ξ0=0\xi_0 = 0, ξ\xi stays 0 to within O(1/Q)O(1/Q), the scaling factors tend to 1, and the step tends to velocity Verlet. This follows from lines L11 to L14. □\square

Complexity

Each step does one force evaluation and O(N)O(N) other work, including two computations of KK. 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) and two numbers.

Properties

  • Ensemble. Canonical (NVT) for the (x,v)(x, v) marginal, if the extended dynamics is ergodic, up to the time step error. The extended energy H′H' is conserved.
  • Deterministic and time-reversible. The step is a palindrome of exact flows.
  • Not symplectic in the usual sense. The flow does not keep the volume dx dv dξdx\,dv\,d\xi; it keeps the measure eNfη dx dv dξ dηe^{N_f \eta}\,dx\,dv\,d\xi\,d\eta, which is the reason a canonical density can be stationary.
  • A quantity to monitor. A drift of H′H' shows an integration error, as HH does in NVE.
  • Momentum. The friction scales all velocities, so a total momentum of 0 stays 0, and a nonzero one decays or grows with ξ\xi.

Variants and improvements

  • Nose-Hoover chains. Nose-Hoover chains thermostat ξ\xi with a second thermostat, and so on. This repairs the lack of ergodicity in many cases.
  • Nose's form. Nose (1984) used a variable ss that scales time and a Hamiltonian in the extended variables. Hoover's equations are the same dynamics in real time. With Nose's virtual time the sampling needs Nf+1N_f + 1 in place of NfN_f in the logarithm term.
  • Massive thermostats. One thermostat for each degree of freedom, or for each group of atoms, makes the method much more robust, at the price of a stronger effect on the dynamics.
  • Barostats. The same idea with a variable for the volume or for the box gives constant pressure methods. The Parrinello-Rahman barostat is the version without a thermostat; with a Nose-Hoover thermostat on top it samples a form of NPT.
  • Stochastic thermostats. Langevin dynamics and stochastic velocity rescaling add noise, which makes ergodicity much easier to prove.

When to use it

Use the Nose-Hoover thermostat for canonical sampling of large systems with many degrees of freedom, such as liquids and solvated proteins, where the motion is chaotic enough. It disturbs the dynamics only a little when QQ is not too small, so it is common in runs that also measure dynamical properties. For small or stiff systems, harmonic solids or systems with few degrees of freedom, use Nose-Hoover chains or a stochastic thermostat.

Pitfalls

  • Non-ergodic systems. One oscillator, a harmonic crystal at low temperature, or a molecule in vacuum can give wrong distributions with the right mean temperature.
  • The choice of QQ. A small QQ gives fast temperature swings and strong coupling, and a large QQ gives slow swings that need long runs. Martyna, Klein and Tuckerman (1992) relate Q=NfkBTτ2Q = N_f k_B T \tau^2 to a thermostat period τ\tau, which is a choice, often a little longer than the period of a typical vibration.
  • Extra conservation laws. Without external forces the total momentum is conserved, and the sampled distribution is not canonical in the full space. Use Nf=dN−dN_f = dN - d with the centre of mass fixed at rest.
  • Start far from the target. Large swings of the temperature at the start can take long to die out, because the thermostat has no damping. Equilibrate first, for example with a Berendsen thermostat.
  • Monitoring the wrong energy. H=K+UH = K + U is not conserved. Monitor H′H'.

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.

nose_hoover_thermostat.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/nose-hoover-thermostat/. The authors are listed in prov/GC1X6T.jsonl.
"""Molecular dynamics with the Nose-Hoover thermostat.

The equations of motion of Hoover (1985) for N particles in d dimensions are

    dx_i/dt = v_i,
    dv_i/dt = f_i / m_i - xi v_i,
    dxi/dt  = (2 K - N_f kT) / Q,
    deta/dt = xi,

with the kinetic energy K, the number of degrees of freedom N_f, the target
temperature kT and the thermostat mass Q. The extended energy

    H' = K + U + Q xi^2 / 2 + N_f kT eta

is conserved by the exact flow.

One step of length h is the symmetric splitting of Martyna, Tuckerman,
Tobias and Klein (1996): a half step of the thermostat, a velocity Verlet step
of the particles, and a second half step of the thermostat. The thermostat
half step updates xi by a quarter step, scales the velocities by
exp(-xi h / 2), and updates xi by another quarter step. Each piece is the
exact flow of a part of the equations, so the step is time-reversible.

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 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 _thermostat_half(v, m, xi, eta, h, kT, q, nf):
    """Exact flows of the thermostat part for a time h / 2 (Trotter split)."""
    k = kinetic(v, m)
    xi += 0.25 * h * (2.0 * k - nf * kT) / q  # @line L11
    s = math.exp(-0.5 * h * xi)  # @line L12
    for vi in v:
        for a in range(len(vi)):
            vi[a] *= s
    k *= s * s
    eta += 0.5 * h * xi  # @line L13
    xi += 0.25 * h * (2.0 * k - nf * kT) / q  # @line L14
    return xi, eta


def nose_hoover_thermostat(
    x: list[Vec], v: list[Vec], m: list[float], forces: ForceField, h: float,
    steps: int, kT: float, q: float, nf: int, xi: float = 0.0, eta: float = 0.0,
) -> tuple[list[Vec], list[Vec], float, float, list[float]]:
    """Run steps of Nose-Hoover dynamics.

    Returns the final positions, velocities, xi and eta, and the extended
    energy H' after each step. The inputs are not changed.
    """
    if h <= 0 or q <= 0 or kT <= 0 or nf <= 0:
        raise ValueError("need h > 0, q > 0, kT > 0 and nf > 0")
    x = [list(p) for p in x]
    v = [list(p) for p in v]
    n = len(x)
    u, f = forces(x)  # @line L1
    energies = []
    for _ in range(steps):  # @line L2
        xi, eta = _thermostat_half(v, m, xi, eta, h, kT, q, nf)  # @line L3
        for i in range(n):
            for a in range(len(x[i])):
                v[i][a] += 0.5 * h * f[i][a] / m[i]  # @line L4
                x[i][a] += h * v[i][a]  # @line L5
        u, f = forces(x)  # @line L6
        for i in range(n):
            for a in range(len(x[i])):
                v[i][a] += 0.5 * h * f[i][a] / m[i]  # @line L7
        xi, eta = _thermostat_half(v, m, xi, eta, h, kT, q, nf)  # @line L8
        energies.append(kinetic(v, m) + u + 0.5 * q * xi * xi + nf * kT * eta)  # @line L9
    return x, v, xi, eta, energies  # @line L10
test_nose_hoover_thermostat.py 66 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/nose-hoover-thermostat/. The authors are listed in prov/GC1X6T.jsonl.
import pytest

from nose_hoover_thermostat import harmonic, kinetic, nose_hoover_thermostat


def sample_oscillator(steps_per_sample, samples, h=0.05, q=1.0):
    """One oscillator, m = k = kT = 1, from x = 1, v = 0; returns (x, v) samples."""
    x, v, xi, eta = [[1.0]], [[0.0]], 0.0, 0.0
    out = []
    for _ in range(samples):
        x, v, xi, eta, _ = nose_hoover_thermostat(x, v, [1.0], harmonic(1.0), h, steps_per_sample, 1.0, q, 1, xi, eta)
        out.append((x[0][0], v[0][0]))
    return out


def test_extended_energy_is_conserved_with_second_order_error():
    spreads = []
    for h in (0.1, 0.05, 0.025):
        n = round(20 / h)
        _, _, _, _, es = nose_hoover_thermostat([[1.0], [0.3]], [[0.0], [0.7]], [1.0, 2.0], harmonic(1.0), h, n, 1.0, 0.5, 2)
        spreads.append(max(es) - min(es))
    assert spreads[0] / spreads[1] == pytest.approx(4.0, rel=0.15)
    assert spreads[1] / spreads[2] == pytest.approx(4.0, rel=0.15)
    assert spreads[2] < 5e-3


def test_time_reversible():
    m = [1.0, 2.0]
    x0, v0 = [[1.0], [0.3]], [[0.0], [0.7]]
    x, v, xi, eta, _ = nose_hoover_thermostat(x0, v0, m, harmonic(1.0), 0.05, 300, 1.0, 0.5, 2)
    x, v, xi, eta, _ = nose_hoover_thermostat(x, [[-c for c in p] for p in v], m, harmonic(1.0), 0.05, 300, 1.0, 0.5, 2, -xi, eta)
    assert x == [pytest.approx(p, abs=1e-9) for p in x0]
    assert [[-c for c in p] for p in v] == [pytest.approx(p, abs=1e-9) for p in v0]
    assert xi == pytest.approx(0.0, abs=1e-9)


def test_time_average_of_kinetic_energy_matches_target():
    # Q dxi/dt = 2K - N_f kT and xi stays bounded, so the time average of
    # 2K tends to N_f kT, here 1.
    out = sample_oscillator(5, 2000)
    mean_2k = sum(v * v for _, v in out) / len(out)
    assert mean_2k == pytest.approx(1.0, abs=0.05)


def test_single_oscillator_is_not_canonical():
    # The canonical law gives <x^2> = 1 and <x^4> / <x^2>^2 = 3. One
    # oscillator with one Nose-Hoover thermostat is not ergodic: its
    # trajectory stays near a torus and gives other values.
    out = sample_oscillator(10, 1000)
    x2 = sum(x * x for x, _ in out) / len(out)
    x4 = sum(x ** 4 for x, _ in out) / len(out)
    assert x2 < 0.9
    assert x4 / (x2 * x2) < 2.0


def test_large_thermostat_mass_is_velocity_verlet():
    x, v, xi, _, _ = nose_hoover_thermostat([[1.0]], [[0.0]], [1.0], harmonic(1.0), 0.05, 200, 1.0, 1e15, 1)
    assert abs(xi) < 1e-12
    assert kinetic(v, [1.0]) + 0.5 * x[0][0] ** 2 == pytest.approx(0.5, abs=1e-3)


def test_bad_arguments_raise():
    with pytest.raises(ValueError):
        nose_hoover_thermostat([[1.0]], [[0.0]], [1.0], harmonic(1.0), 0.05, 1, 1.0, 0.0, 1)

History

Nose (1984) introduced an extended Hamiltonian with a variable that scales time, and proved that its microcanonical ensemble gives canonical averages for the physical variables. In a second paper he gave the equations in real time and related them to other constant-temperature methods. Hoover (1985) simplified the real-time equations to the friction form of this page, derived the stationary canonical density from the Liouville equation, and showed that one harmonic oscillator does not fill its phase space. Martyna, Klein and Tuckerman (1992) added the chains, and Martyna, Tuckerman, Tobias and Klein (1996) gave the reversible splitting into exact flows that is used here.

References

  1. Shuichi Nose, A molecular dynamics method for simulations in the canonical ensemble, Molecular Physics 52(2), 1984, 255-268, the extended Hamiltonian with the time scaling variable s and the proof that it gives canonical averages
  2. Shuichi Nose, A unified formulation of the constant temperature molecular dynamics methods, Journal of Chemical Physics 81(1), 1984, 511-519, the equations in real time and the relation to other constant-temperature methods
  3. William G. Hoover, Canonical dynamics, Equilibrium phase-space distributions, Physical Review A 31(3), 1985, 1695-1697, the equations with the friction coefficient, the stationary canonical density and the harmonic oscillator
  4. Glenn J. Martyna, Mark E. Tuckerman, Douglas J. Tobias and Michael L. Klein, Explicit reversible integrators for extended systems dynamics, Molecular Physics 87(5), 1996, 1117-1157, the factorization of the Liouville operator into exact flows, which gives the time-reversible step of this page
  5. Mark E. Tuckerman, Statistical Mechanics, Theory and Molecular Simulation, Oxford University Press, 2010, Chapter 4, the canonical ensemble (non-Hamiltonian extended phase-space methods)
  6. Ben Leimkuhler and Charles Matthews, Molecular Dynamics, With Deterministic and Stochastic Numerical Methods, Springer, 2015, Chapter 8, extended variable 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