Algorithm Search⌘K

Algorithmadvanced

Nose-Hoover chains

Couples the Nose-Hoover friction to further thermostats in a chain, curing the lack of ergodicity of one thermostat on small or stiff systems.

Time
O(S (N^2 + M)) worst
Space
O(N + M) extra
Where
M = the number of links in the chain; N = the number of particles; S = the number of time steps
Properties
deterministiciterativesymmetricnot symplectic
Origin
Glenn J. Martyna, Michael L. Klein, Mark E. Tuckerman, 1992

Nose-Hoover chains are a deterministic thermostat for molecular dynamics that extends the Nose-Hoover thermostat. The friction ξ1\xi_1 that controls the particles is itself controlled by a second friction ξ2\xi_2, which is controlled by a third, and so on, in a chain of MM links. The extended system conserves an energy, and the canonical ensemble is a stationary density of its flow (a theorem). The extra links make the motion chaotic in cases where one thermostat is not, so in practice the chain samples the canonical distribution of small and stiff systems such as one harmonic oscillator. This is a measurement, not a proof of ergodicity.

In plain words

One Nose-Hoover thermostat is a pedal that brakes or speeds up all atoms together. The pedal itself swings in a regular way, and for simple systems the atoms and the pedal fall into a fixed rhythm that never explores all the states.

The chain adds a second pedal that acts on the first one, a third that acts on the second, and so on. Each pedal tries to keep the one before it at the right temperature. The extra pedals break the fixed rhythm, so the motion becomes irregular and fills the space of states. A total energy that includes all pedals stays fixed, so the program can still be checked.

The problem

The input is as for the Nose-Hoover thermostat: positions xi∈Rdx_i \in \mathbb{R}^d, velocities viv_i, masses mim_i, forces fi=−∇iUf_i = -\nabla_i U, a time step hh, a number of steps SS, the target kBTk_B T and the number NfN_f of velocity components that link 1 scales. In addition it takes the masses Q1,…,QM>0Q_1, \ldots, Q_M > 0 of the links and start values of ξj\xi_j and ηj\eta_j (often 0). The output is the trajectory of the equations of Martyna, Klein and Tuckerman (1992):

x˙i=vi,v˙i=fimi−ξ1vi,ξ˙j=Gj−ξjξj+1 (j<M),ξ˙M=GM,η˙j=ξj,\dot x_i = v_i, \qquad \dot v_i = \frac{f_i}{m_i} - \xi_1 v_i, \qquad \dot \xi_j = G_j - \xi_j \xi_{j+1} \ (j < M), \qquad \dot \xi_M = G_M, \qquad \dot \eta_j = \xi_j,

with the thermostat forces

G1=2K−NfkBTQ1,Gj=Qj−1ξj−12−kBTQj (j≥2),G_1 = \frac{2K - N_f k_B T}{Q_1}, \qquad G_j = \frac{Q_{j-1}\xi_{j-1}^2 - k_B T}{Q_j} \ (j \ge 2),

and the extended energy after each step,

H′=K+U+∑j=1M12Qjξj2+NfkBT η1+kBT∑j=2Mηj,H' = K + U + \sum_{j=1}^{M} \tfrac12 Q_j \xi_j^2 + N_f k_B T\, \eta_1 + k_B T \sum_{j=2}^{M} \eta_j,

which the exact flow conserves. Link j≥2j \ge 2 has one degree of freedom, ξj−1\xi_{j-1}, to control, which is the reason GjG_j has kBTk_B T and not NfkBTN_f k_B T. In the implementation Nf=dNN_f = dN; with the total momentum fixed, use Nf=dN−dN_f = dN - d. The masses of Martyna, Klein and Tuckerman are Q1=NfkBTτ2Q_1 = N_f k_B T \tau^2 and Qj=kBTτ2Q_j = k_B T \tau^2 for j≥2j \ge 2, with a thermostat period τ\tau that is a choice.

The algorithm

  1. NOSE-HOOVER-CHAINS(x, v, m, FORCES, h, S, kT, Q_1..Q_M, N_f, xi, eta)
  2. 1(U, f) ← FORCES(x)
  3. 2for step ← 1 to S do
  4. 3CHAIN-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. 8CHAIN-HALF(v, xi, eta)
  10. 9record H'
  11. 10return (x, v, xi, eta, the recorded H')
  12. LINK-QUARTER(j) ▷ exact flows of link j for a time h / 4
  13. 11if j = M then xi_M ← xi_M + (h / 4) G_M and return
  14. 12s ← exp(-xi_{j+1} h / 8)
  15. 13xi_j ← s xi_j
  16. 14xi_j ← xi_j + (h / 4) G_j
  17. 15xi_j ← s xi_j
  18. CHAIN-HALF(v, xi, eta) ▷ exact flows of the chain for a time h / 2
  19. 16for j ← M down to 1 do LINK-QUARTER(j)
  20. 17v_i ← exp(-xi_1 h / 2) v_i for each particle i, and update K
  21. 18eta_j ← eta_j + (h / 2) xi_j for j ← 1 to M
  22. 19for j ← 1 to M do LINK-QUARTER(j)

Each line is the exact flow of a part of the equations with the other variables fixed. GjG_j does not depend on ξj\xi_j, so line L14 is exact, and the friction term −ξjξj+1-\xi_j \xi_{j+1} alone is the exponential decay of lines L13 and L15. The order of the sweep, from the end of the chain to the particles and back, makes CHAIN-HALF a palindrome, and with the Verlet step in the middle the whole step is time-reversible and of order 2. This is the splitting of Martyna, Tuckerman, Tobias and Klein (1996), with one stage per half step. With M=1M = 1, LINK-QUARTER is one quarter kick, and the step is the Nose-Hoover step.

Example

One step by hand. One particle on a spring with m=k=kBT=1m = k = k_B T = 1 in reduced units, Nf=1N_f = 1, M=2M = 2, Q1=Q2=1Q_1 = Q_2 = 1, x=1x = 1, v=0v = 0, all ξj=ηj=0\xi_j = \eta_j = 0 and h=0.1h = 0.1, so H′=0.5H' = 0.5. In the first CHAIN-HALF, K=0K = 0, so link 2 gets G2=(0−1)/1G_2 = (0 - 1)/1 and ξ2=−0.025\xi_2 = -0.025 (L11). Link 1 is scaled by e0.025⋅0.1/8e^{0.025 \cdot 0.1/8}, which changes nothing since ξ1=0\xi_1 = 0, kicked by G1=−1G_1 = -1 to ξ1=−0.025\xi_1 = -0.025 (L14), and scaled again to −0.0250078-0.0250078 (L15). The rest of the step goes as on the Nose-Hoover page, and after it

variable xx vv ξ1\xi_1 ξ2\xi_2 η1\eta_1 η2\eta_2 H′H'
value 0.995 −0.1001243-0.1001243 −0.0998123-0.0998123 −0.0996258-0.0996258 −0.0049954-0.0049954 −0.0049937-0.0049937 0.4999797

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 kBT=1k_B T = 1, Nf=2N_f = 2 and M=3M = 3 links with the masses Q=(2,1,1)Q = (2, 1, 1) of Martyna, Klein and Tuckerman for τ=1\tau = 1, run to t=20t = 20:

hh 0.1 0.05 0.025
spread of H′H' 0.02196 0.005495 0.001375

The spread falls by a factor of 4 when hh is halved. A run of 300 steps forward and 300 back with vv and all ξj\xi_j flipped recovers the start to 10−910^{-9}.

One oscillator becomes canonical. One oscillator with m=k=kBT=1m = k = k_B T = 1 and Nf=1N_f = 1, from x=1x = 1, v=0v = 0, with h=0.05h = 0.05 and a sample every 10 steps:

thermostat run length ⟨x2⟩\langle x^2 \rangle ⟨x4⟩/⟨x2⟩2\langle x^4 \rangle / \langle x^2 \rangle^2
one Nose-Hoover, Q=1Q = 1 10410^4 0.793 1.538
chain, M=4M = 4, all Qj=1Q_j = 1 500 0.993 2.890
chain, M=4M = 4, all Qj=1Q_j = 1 10410^4 0.980 2.913

The canonical values are 1 and 3. These are measurements: the chain gives the canonical moments within the sampling error, and one thermostat does not.

Correctness

The proof in proofs/correctness.md shows:

  1. The extended energy H′H' is conserved: in ∑jQjξjξ˙j\sum_j Q_j \xi_j \dot\xi_j the coupling terms cancel in pairs, and the η\eta terms cancel the rest.
  2. The canonical density is stationary. The density exp⁡(−β(K+U+∑j12Qjξj2))\exp(-\beta(K + U + \sum_j \frac12 Q_j \xi_j^2)) solves the stationary Liouville equation, since the flow has divergence −Nfξ1−∑j≥2ξj-N_f\xi_1 - \sum_{j \ge 2}\xi_j. Its marginal in (x,v)(x, v) is canonical, and each ξj\xi_j is normal with variance kBT/Qjk_B T / Q_j.
  3. The step is a palindrome of exact flows, so it is time-reversible and of order 2.
  4. Length 1 gives the Nose-Hoover step.

So the method samples the canonical ensemble if the extended flow is ergodic. This is still a hypothesis. The chain does not prove ergodicity; it makes it much more likely in practice, as the measurements show. The dynamics of the particles are disturbed as little as with one thermostat, since only ξ1\xi_1 acts on them.

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

The equations of Martyna, Klein and Tuckerman (1992) for a chain of M≥1M \ge 1 thermostats with masses Q1,…,QMQ_1, \ldots, Q_M are

x˙i=vi,v˙i=fimi−ξ1vi,η˙j=ξj,\dot x_i = v_i, \qquad \dot v_i = \frac{f_i}{m_i} - \xi_1 v_i, \qquad \dot \eta_j = \xi_j,
ξ˙j=Gj−ξjξj+1 (j<M),ξ˙M=GM,(1)\dot \xi_j = G_j - \xi_j \xi_{j+1} \ (j < M), \qquad \dot \xi_M = G_M, \qquad (1)

with the thermostat forces

G1=2K−NfkBTQ1,Gj=Qj−1ξj−12−kBTQj (j≥2).G_1 = \frac{2K - N_f k_B T}{Q_1}, \qquad G_j = \frac{Q_{j-1}\xi_{j-1}^2 - k_B T}{Q_j} \ (j \ge 2).

NfN_f is the number of velocity components that link 1 scales.

Claim 1 (the extended energy). The exact flow of (1) keeps

H′=K+U+∑j=1M12Qjξj2+NfkBTη1+kBT∑j=2Mηj.H' = K + U + \sum_{j=1}^{M} \tfrac12 Q_j \xi_j^2 + N_f k_B T \eta_1 + k_B T \sum_{j=2}^{M} \eta_j.

Proof. The particle terms give ddt(K+U)=−2Kξ1\frac{d}{dt}(K + U) = -2K\xi_1, as for one thermostat. For the chain,

∑jQjξjξ˙j=ξ1(2K−NfkBT)+∑j=2Mξj(Qj−1ξj−12−kBT)−∑j=1M−1Qjξj2ξj+1.\sum_j Q_j \xi_j \dot \xi_j = \xi_1 (2K - N_f k_B T) + \sum_{j=2}^{M} \xi_j (Q_{j-1}\xi_{j-1}^2 - k_B T) - \sum_{j=1}^{M-1} Q_j \xi_j^2 \xi_{j+1}.

The term ξjQj−1ξj−12\xi_j Q_{j-1} \xi_{j-1}^2 for j≥2j \ge 2 cancels the term Qj−1ξj−12ξjQ_{j-1}\xi_{j-1}^2 \xi_j of the last sum. What is left is 2Kξ1−NfkBTξ1−kBT∑j≥2ξj2K\xi_1 - N_f k_B T \xi_1 - k_B T \sum_{j \ge 2} \xi_j. The η\eta terms give NfkBTξ1+kBT∑j≥2ξjN_f k_B T \xi_1 + k_B T \sum_{j \ge 2} \xi_j. The total is 0. □\square

Claim 2 (the canonical density is stationary). The density ρ∝exp⁡(−β(K+U+∑j12Qjξj2))\rho \propto \exp\bigl(-\beta(K + U + \sum_j \frac12 Q_j \xi_j^2)\bigr) on (x,v,ξ1,…,ξM)(x, v, \xi_1, \ldots, \xi_M) is stationary for (1).

Proof. We show F⋅∇ln⁡ρ+∇⋅F=0F \cdot \nabla \ln \rho + \nabla \cdot F = 0 for the vector field FF of (1). The divergence comes from ∂v˙ia/∂via=−ξ1\partial \dot v_{ia} / \partial v_{ia} = -\xi_1 (NfN_f times) and ∂ξ˙j/∂ξj=−ξj+1\partial \dot \xi_j / \partial \xi_j = -\xi_{j+1} for j<Mj < M; GjG_j does not depend on ξj\xi_j. So ∇⋅F=−Nfξ1−∑j=2Mξj\nabla \cdot F = -N_f \xi_1 - \sum_{j=2}^{M} \xi_j. Next,

F⋅∇ln⁡ρ=−β(−2Kξ1+∑jQjξjξ˙j)=−β(−NfkBTξ1−kBT∑j≥2ξj)=Nfξ1+∑j≥2ξj,F \cdot \nabla \ln \rho = -\beta \Bigl( -2K\xi_1 + \sum_j Q_j \xi_j \dot \xi_j \Bigr) = -\beta \Bigl( -N_f k_B T \xi_1 - k_B T \sum_{j \ge 2} \xi_j \Bigr) = N_f \xi_1 + \sum_{j \ge 2} \xi_j,

by the computation in Claim 1. The sum is 0. □\square

As for one thermostat, the marginal of ρ\rho in (x,v)(x, v) is canonical, and time averages are canonical averages only if the flow is ergodic. The chain does not prove ergodicity. It adds variables that make the dynamics chaotic in cases where one thermostat is not, such as one harmonic oscillator (a measurement on the page).

Claim 3 (the splitting). One step is Ch/2∘Vh/2∘Ah∘Vh/2∘Ch/2C_{h/2} \circ V_{h/2} \circ A_h \circ V_{h/2} \circ C_{h/2}, where VV and AA are the exact kick and drift and Ch/2C_{h/2} is a palindrome of exact flows of parts of the chain field:

Ch/2=PM∘⋯∘P1∘S∘P1∘⋯∘PM,C_{h/2} = P_M \circ \cdots \circ P_1 \circ S \circ P_1 \circ \cdots \circ P_M,

read from right to left. Here SS is the exact flow for a time h/2h/2 of v˙i=−ξ1vi\dot v_i = -\xi_1 v_i, η˙j=ξj\dot \eta_j = \xi_j with all ξ\xi fixed. For j<Mj < M, Pj=Ej∘Bj∘EjP_j = E_j \circ B_j \circ E_j, with EjE_j the exact flow for a time h/8h/8 of ξ˙j=−ξjξj+1\dot \xi_j = -\xi_j \xi_{j+1} and BjB_j the exact flow for a time h/4h/4 of ξ˙j=Gj\dot \xi_j = G_j, all other variables fixed; and PM=BMP_M = B_M.

Proof. EjE_j multiplies ξj\xi_j by e−ξj+1h/8e^{-\xi_{j+1} h/8}: lines L12, L13 and L15. GjG_j depends on KK or ξj−1\xi_{j-1} and not on ξj\xi_j, so BjB_j adds h4Gj\frac{h}{4} G_j to ξj\xi_j: line L14, and line L11 for j=Mj = M. Line L16 applies PM,…,P1P_M, \ldots, P_1 in this order, line L17 scales the velocities by e−ξ1h/2e^{-\xi_1 h/2} and line L18 adds h2ξj\frac{h}{2}\xi_j to each ηj\eta_j, which is SS, and line L19 applies P1,…,PMP_1, \ldots, P_M. The kinetic energy is updated after the scaling, so the second B1B_1 uses the new KK. Lines L4 to L7 are the Verlet part. □\square

Claim 4 (time reversal). With R(x,v,ξ,η)=(x,−v,−ξ,η)R(x, v, \xi, \eta) = (x, -v, -\xi, \eta), each exact flow ϕt\phi_t above satisfies R∘ϕt∘R=ϕ−tR \circ \phi_t \circ R = \phi_{-t}, and the step Ψh\Psi_h is a palindrome of such flows, so Ψh∘R∘Ψh=R\Psi_h \circ R \circ \Psi_h = R.

Proof. Under RR, G1G_1 and GjG_j are unchanged (they depend on KK and on ξj−12\xi_{j-1}^2), so BjB_j changes the sign of its increment; EjE_j multiplies by e−ξj+1te^{-\xi_{j+1} t}, and with ξj+1→−ξj+1\xi_{j+1} \to -\xi_{j+1} this is EjE_j for −t-t; the same holds for SS, VV and AA. A palindrome of maps with this property is reversed by RR, as in the proof for one thermostat. □\square

A symmetric composition of the flows of a split field has order 2, so H′H' is kept up to O(h2)O(h^2) over a fixed time.

Claim 5 (length 1). For M=1M = 1 the step is the Nose-Hoover step with Q=Q1Q = Q_1.

Proof. With M=1M = 1 there are no EE maps, and Ch/2=B1∘S∘B1C_{h/2} = B_1 \circ S \circ B_1: a quarter kick of ξ1\xi_1 by (2K−NfkBT)/Q1(2K - N_f k_B T)/Q_1, the scaling of vv by e−ξ1h/2e^{-\xi_1 h/2} with η1+=h2ξ1\eta_1 \mathrel{+}= \frac{h}{2}\xi_1, and a quarter kick with the new KK. These are lines L11 to L14 of the Nose-Hoover page, and H′H' reduces to K+U+12Q1ξ12+NfkBTη1K + U + \frac12 Q_1 \xi_1^2 + N_f k_B T \eta_1. □\square

Complexity

Each step does one force evaluation, O(N)O(N) work for the particles and O(M)O(M) work for the chain, with four exponentials per link. With the all-pairs forces of the molecular dynamics page, SS steps cost O(S(N2+M))O(S(N^2 + M)) time. The extra space is O(N+M)O(N + M). In practice MM is a small number such as 3 to 5, which is a choice, and the chain costs nothing next to the forces.

Properties

  • Ensemble. Canonical (NVT) for the (x,v)(x, v) marginal, if the extended dynamics is ergodic, up to the time step error.
  • Deterministic and time-reversible. The step is a palindrome of exact flows.
  • A conserved quantity to monitor. H′H' drifts only by integration error.
  • Not symplectic. The flow does not keep phase-space volume; it keeps the measure exp⁡(Nfη1+∑j≥2ηj)\exp(N_f \eta_1 + \sum_{j \ge 2}\eta_j) times the volume.
  • Robust where one thermostat fails. On one harmonic oscillator and on harmonic solids, measured moments agree with the canonical values.

Variants and improvements

  • Multiple time steps in the chain. Martyna, Tuckerman, Tobias and Klein (1996) split the chain part further, into several stages with Suzuki-Yoshida weights, for stiff chains. This page uses one stage per half step. The same idea for the forces is RESPA.
  • Massive chains. One chain for each degree of freedom, as in path integral simulations, makes the thermostat act locally.
  • Barostats. The constant pressure methods of Martyna, Tobias and Klein put chains on the particles and on the volume or cell variables. The Parrinello-Rahman barostat needs such a thermostat to sample NPT.
  • Stochastic thermostats. Langevin dynamics and stochastic velocity rescaling reach ergodicity with noise, and there is a proof for them. A Langevin thermostat on the last link of a chain is a hybrid that some codes use.

When to use it

Use Nose-Hoover chains when a deterministic, time-reversible thermostat with a conserved quantity is wanted and the system is small, stiff or close to harmonic: crystals at low temperature, small molecules, path integral beads. For large disordered systems, one thermostat often works as well. When a proof of ergodicity matters more than a deterministic trajectory, use a stochastic thermostat.

Pitfalls

  • Chain masses that are too small. The links then move fast, and the time step must resolve them. Check the spread of H′H'.
  • Reporting the wrong energy. Only H′H' with all ηj\eta_j terms is conserved.
  • A wrong NfN_f. The first link targets NfkBTN_f k_B T, and NfN_f must count the constraints and a fixed centre of mass.
  • Assuming ergodicity. The chain is a remedy that works well in tests, not a theorem. Check the distribution, not only the mean temperature, for example with ⟨x4⟩/⟨x2⟩2\langle x^4 \rangle / \langle x^2 \rangle^2 on a harmonic test.

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_chains.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/nose-hoover-chains/. The authors are listed in prov/KYF8ST.jsonl.
"""Molecular dynamics with a Nose-Hoover chain thermostat.

The equations of Martyna, Klein and Tuckerman (1992) for N particles in d
dimensions, with a chain of M thermostats of masses Q_1, ..., Q_M, are

    dx_i/dt   = v_i,
    dv_i/dt   = f_i / m_i - xi_1 v_i,
    dxi_1/dt  = G_1 - xi_1 xi_2,         G_1 = (2 K - N_f kT) / Q_1,
    dxi_j/dt  = G_j - xi_j xi_(j+1),     G_j = (Q_(j-1) xi_(j-1)^2 - kT) / Q_j,
    dxi_M/dt  = G_M,
    deta_j/dt = xi_j.

The extended energy

    H' = K + U + sum_j Q_j xi_j^2 / 2 + N_f kT eta_1 + kT (eta_2 + ... + eta_M)

is conserved by the exact flow. With M = 1 the chain is the Nose-Hoover
thermostat.

One step of length h is the symmetric splitting of Martyna, Tuckerman,
Tobias and Klein (1996): a half step of the chain, a velocity Verlet step of
the particles, and a second half step of the chain. In the half step of the
chain, each xi_j gets a quarter step kick by G_j between two scalings by
exp(-xi_(j+1) h / 8), from the end of the chain to its start; then the
velocities are scaled by exp(-xi_1 h / 2) and all eta_j move by xi_j h / 2;
then the kicks are repeated from the start of the chain to its end. Each
piece is the exact flow of a part of the equations, so the step is
time-reversible. One Suzuki-Yoshida stage is used (no multiple time steps
inside the chain).

Cost: one force evaluation and Theta(N d + M) 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 chain_masses(nf: int, kT: float, tau: float, length: int) -> list[float]:
    """The masses of Martyna et al. (1992): Q_1 = N_f kT tau^2, Q_j = kT tau^2."""
    return [nf * kT * tau * tau] + [kT * tau * tau] * (length - 1)


def _force(j, xi, q, k, kT, nf):
    """G_j: the thermostat force on link j (0-based)."""
    if j == 0:
        return (2.0 * k - nf * kT) / q[0]
    return (q[j - 1] * xi[j - 1] ** 2 - kT) / q[j]


def _kick(j, xi, q, k, kT, nf, h):
    """A quarter step of link j: scale, kick by G_j, scale."""
    mm = len(xi)
    if j == mm - 1:
        xi[j] += 0.25 * h * _force(j, xi, q, k, kT, nf)  # @line L11
        return
    s = math.exp(-0.125 * h * xi[j + 1])  # @line L12
    xi[j] *= s  # @line L13
    xi[j] += 0.25 * h * _force(j, xi, q, k, kT, nf)  # @line L14
    xi[j] *= s  # @line L15


def _chain_half(v, m, xi, eta, q, h, kT, nf):
    """The exact flows of the chain part for a time h / 2."""
    mm = len(xi)
    k = kinetic(v, m)
    for j in range(mm - 1, -1, -1):  # @line L16
        _kick(j, xi, q, k, kT, nf, h)
    s = math.exp(-0.5 * h * xi[0])  # @line L17
    for vi in v:
        for a in range(len(vi)):
            vi[a] *= s
    k *= s * s
    for j in range(mm):
        eta[j] += 0.5 * h * xi[j]  # @line L18
    for j in range(mm):  # @line L19
        _kick(j, xi, q, k, kT, nf, h)


def extended_energy(x, v, m, u, xi, eta, q, kT, nf) -> float:
    """H' = K + U + sum Q_j xi_j^2 / 2 + N_f kT eta_1 + kT sum_(j >= 2) eta_j."""
    e = kinetic(v, m) + u + sum(0.5 * qj * z * z for qj, z in zip(q, xi))
    return e + nf * kT * eta[0] + kT * sum(eta[1:])


def nose_hoover_chains(
    x: list[Vec], v: list[Vec], m: list[float], forces: ForceField, h: float,
    steps: int, kT: float, q: list[float], nf: int,
    xi: list[float] | None = None, eta: list[float] | None = None,
) -> tuple[list[Vec], list[Vec], list[float], list[float], list[float]]:
    """Run steps of Nose-Hoover chain dynamics with masses q (the chain length is len(q)).

    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 not q or min(q) <= 0 or kT <= 0 or nf <= 0:
        raise ValueError("need h > 0, positive masses q, kT > 0 and nf > 0")
    mm = len(q)
    xi = list(xi) if xi is not None else [0.0] * mm
    eta = list(eta) if eta is not None else [0.0] * mm
    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
        _chain_half(v, m, xi, eta, q, h, kT, 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
        _chain_half(v, m, xi, eta, q, h, kT, nf)  # @line L8
        energies.append(extended_energy(x, v, m, u, xi, eta, q, kT, nf))  # @line L9
    return x, v, xi, eta, energies  # @line L10
test_nose_hoover_chains.py 66 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/nose-hoover-chains/. The authors are listed in prov/KYF8ST.jsonl.
import pytest

from nose_hoover_chains import chain_masses, harmonic, kinetic, nose_hoover_chains


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


def test_single_oscillator_becomes_canonical_with_a_chain():
    # Canonical values: <x^2> = 1 and <x^4> / <x^2>^2 = 3. A single
    # Nose-Hoover thermostat gives about 0.79 and 1.54 on this system.
    xs = sample_oscillator([1.0] * 4, 10, 1000)
    x2 = sum(x * x for x in xs) / len(xs)
    x4 = sum(x ** 4 for x in xs) / len(xs)
    assert x2 == pytest.approx(1.0, abs=0.15)
    assert x4 / (x2 * x2) == pytest.approx(3.0, abs=0.4)


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


def test_time_reversible():
    q = [0.5, 1.0, 2.0]
    m = [1.0, 2.0]
    x0, v0 = [[1.0], [0.3]], [[0.0], [0.7]]
    x, v, xi, eta, _ = nose_hoover_chains(x0, v0, m, harmonic(1.0), 0.05, 300, 1.0, q, 2)
    back = [[-c for c in p] for p in v]
    x, v, xi, eta, _ = nose_hoover_chains(x, back, m, harmonic(1.0), 0.05, 300, 1.0, q, 2, [-z for z in 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, 0.0, 0.0], abs=1e-9)


def test_chain_of_length_one_is_nose_hoover():
    # With one link the update is the Nose-Hoover update: the extended
    # energy K + U + Q xi^2 / 2 + N_f kT eta is conserved.
    x, v, xi, eta, es = nose_hoover_chains([[1.0]], [[0.0]], [1.0], harmonic(1.0), 0.02, 500, 1.0, [1.0], 1)
    assert max(abs(e - 0.5) for e in es) < 1e-3
    e = kinetic(v, [1.0]) + 0.5 * x[0][0] ** 2 + 0.5 * xi[0] ** 2 + eta[0]
    assert e == pytest.approx(es[-1], abs=1e-12)


def test_chain_masses_follow_martyna_klein_tuckerman():
    assert chain_masses(30, 2.0, 0.5, 3) == pytest.approx([15.0, 0.5, 0.5])


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

History

Hoover (1985) showed that one Nose-Hoover thermostat does not give the canonical distribution of one harmonic oscillator. Martyna, Klein and Tuckerman (1992) proposed to thermostat the thermostat, proved that the chain keeps the canonical density, and showed in numerical tests that it samples the harmonic oscillator correctly. Martyna, Tuckerman, Tobias and Klein (1996) gave the reversible integrators built from exact flows, including those for the chains and for constant pressure. The method is a standard option in many molecular dynamics codes.

References

  1. Glenn J. Martyna, Michael L. Klein and Mark Tuckerman, Nose-Hoover chains, The canonical ensemble via continuous dynamics, Journal of Chemical Physics 97(4), 1992, 2635-2643, the equations of the chain, the conserved energy, the proof of the stationary canonical density and the harmonic oscillator test
  2. 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 chain part into exact flows, which gives the reversible step of this page
  3. Mark E. Tuckerman, Statistical Mechanics, Theory and Molecular Simulation, Oxford University Press, 2010, Chapter 4, the canonical ensemble (Nose-Hoover chains and their integration)
  4. Ben Leimkuhler and Charles Matthews, Molecular Dynamics, With Deterministic and Stochastic Numerical Methods, Springer, 2015, Chapter 8, extended variable methods

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