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
- Model
- Real RAM
- Properties
- deterministiciterativesymmetricnot symplectic
- Evidence
- Proof sketchCode in 1 languages
- 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 , 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 , 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 , velocities and masses of particles, a force field with forces , a time step , a number of steps , the target , the thermostat mass , the number of velocity components that the thermostat scales, and start values of and of the thermostat position (often 0). The output is the trajectory of the equations of Hoover (1985),
with , and the extended energy
after each step, which the exact flow conserves. enters only . In the implementation . If the total momentum is fixed at 0, the momentum is a further conserved quantity, and the thermostat should use (see Pitfalls).
The algorithm
NOSE-HOOVER(x, v, m, FORCES, h, S, kT, Q, N_f, xi, eta)- 1
(U, f) ← FORCES(x) - 2
for step ← 1 to S do - 3
(xi, eta) ← THERMOSTAT-HALF(v, xi, eta) - 4
v_i ← v_i + (h / 2) f_i / m_i for each particle i ▷ half kick - 5
x_i ← x_i + h v_i for each particle i ▷ drift - 6
(U, f) ← FORCES(x) - 7
v_i ← v_i + (h / 2) f_i / m_i for each particle i ▷ half kick - 8
(xi, eta) ← THERMOSTAT-HALF(v, xi, eta) - 9
record H' = K + U + Q xi^2 / 2 + N_f kT eta - 10
return (x, v, xi, eta, the recorded H') THERMOSTAT-HALF(v, xi, eta) ▷ exact flows for a time h / 2- 11
xi ← xi + (h / 4)(2K - N_f kT) / Q - 12
v_i ← exp(-xi h / 2) v_i for each particle i - 13
eta ← eta + (h / 2) xi - 14
xi ← 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 fixed, moves at a constant rate (L11, L14), and with fixed, the velocities decay as and grows as (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 in reduced units, , , , and , so .
| line | update | value |
|---|---|---|
| L11 | ||
| L12, L13 | stays 0; | |
| L14 | ||
| L4 to L7 | velocity Verlet | , |
| L11 | , | |
| L12 | ||
| L13 | ||
| L14 |
The particle is colder than the target, so becomes negative and the scaling speeds it up: is larger than the 0.09975 of plain Verlet. The extended energy after the step is .
The extended energy is conserved to second order. Two oscillators with , masses 1 and 2, started at , , with , and , run to . The spread is
| 0.1 | 0.05 | 0.025 | |
|---|---|---|---|
| spread of | 0.03168 | 0.008336 | 0.002110 |
so it falls by a factor of about 4 when is halved. Running 300 steps forward, flipping and , and running 300 steps back recovers the start to .
One oscillator is not ergodic. One oscillator with , , from , , with and a sample every 10 steps to , gives and . The canonical values are 1 and 3. The mean of is 0.99915, close to , 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:
- The extended energy is conserved by the exact flow.
- The canonical density is stationary. The density on solves the stationary Liouville equation, since the flow has divergence . Its marginal in is canonical.
- The step is a palindrome of exact flows, so it is time-reversible and has order 2.
- Time reversal. With , .
- The mean kinetic energy. The mean of over the updates of in steps is exactly , which tends to 0 if stays bounded. This needs no ergodicity.
So the method samples the canonical ensemble if the extended flow is ergodic on the set where 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 particles with velocity components, the friction and the thermostat mass are
Here and . In this proof is the number of velocity components that the thermostat scales, which is in the implementation.
Claim 1 (the extended energy). The exact flow of (1) keeps .
Proof. Along (1),
Claim 2 (the canonical density is stationary). The density satisfies the Liouville equation with , where is the vector field of (1) on .
Proof. We must show . Only the velocity equations depend on their own variable: for each of the components, so . Next, , so
The sum is 0.
The marginal of in is the canonical density. So time averages along (1) are canonical averages if the flow is ergodic on the set where 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: , the kick ; , the drift ; and , the thermostat part , , . One step of the algorithm is
where and are the exact flows and is the symmetric composition of two exact flows: , the flow of with fixed, and , the flow of , with fixed.
Proof. With fixed, is fixed, so adds to : these are lines L11 and L14 with . With fixed, multiplies each velocity by and adds to : these are lines L12 and L13 with . Line L14 uses the kinetic energy after the scaling, as must. Lines L4 to L7 are , with the forces kept from the last evaluation as on the molecular dynamics page. Line L3 is before the Verlet part and line L8 is after it.
Claim 4 (time reversal). Let . Then .
Proof. For each of the exact flows above, : under , each equation of (1) changes sign on the left exactly when the time direction changes, and is a sum of , which also changes sign twice. So is the same composition with each replaced by , taken in the same order. Because the composition is a palindrome, this is the inverse .
A symmetric composition of flows of a split vector field is a method of order 2 (see operator splitting), so is kept up to over a fixed time. The tests show the error falling by a factor 4 when is halved.
Claim 5 (the mean kinetic energy). Let , , be the kinetic energies used by the applications of in steps, and the friction after step . Then
So if stays bounded, the mean of tends to as .
Proof. Only changes , and each application adds . Sum over and multiply by .
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 and a wrong distribution of .
Claim 6 (large mass). As with , stays 0 to within , the scaling factors tend to 1, and the step tends to velocity Verlet. This follows from lines L11 to L14.
Complexity
Each step does one force evaluation and other work, including two computations of . With the all-pairs forces of the molecular dynamics page, steps cost time, and the thermostat adds . The extra space is and two numbers.
Properties
- Ensemble. Canonical (NVT) for the marginal, if the extended dynamics is ergodic, up to the time step error. The extended energy 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 ; it keeps the measure , which is the reason a canonical density can be stationary.
- A quantity to monitor. A drift of shows an integration error, as 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 .
Variants and improvements
- Nose-Hoover chains. Nose-Hoover chains thermostat with a second thermostat, and so on. This repairs the lack of ergodicity in many cases.
- Nose's form. Nose (1984) used a variable 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 in place of 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 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 . A small gives fast temperature swings and strong coupling, and a large gives slow swings that need long runs. Martyna, Klein and Tuckerman (1992) relate to a thermostat period , 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 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. is not conserved. Monitor .
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/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
- 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
- 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
- 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
- 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
- Mark E. Tuckerman, Statistical Mechanics, Theory and Molecular Simulation, Oxford University Press, 2010, Chapter 4, the canonical ensemble (non-Hamiltonian extended phase-space methods)
- 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.
| 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 GC1X6T Edit this page History Report an error Markdown