Algorithmadvanced
Parrinello-Rahman barostat
Also called Parrinello-Rahman method.
Lets the shape and size of the periodic box evolve as dynamical variables driven by the pressure tensor. Alone it samples NPH; with a thermostat added it samples NPT.
- 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
- deterministiciterativesymmetricsymplectic
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Michele Parrinello, Aneesur Rahman, 1980
The Parrinello-Rahman barostat controls the pressure in molecular dynamics with periodic boundary conditions. It makes the matrix of the cell vectors a dynamical variable with a mass . The cell feels a force equal to the difference between the internal pressure tensor and the external pressure, so it can change both its volume and its shape. That makes it the standard method for solids, where a crystal may need a box of a new shape to change its structure. The equations alone conserve an enthalpy, so they sample the isoenthalpic-isobaric (NPH) ensemble if they are ergodic. For the isothermal-isobaric (NPT) ensemble a thermostat must act as well, for example a Nose-Hoover chain or stochastic velocity rescaling.
In plain words
In a normal simulation the box has a fixed size and shape. In a lab, a sample is pushed by the air around it at a fixed pressure, and it can grow, shrink or shear.
This method gives the walls of the box a mass and lets them move. If the atoms push outward harder than the outside pressure, the box grows; if they push less, it shrinks. If they push harder in one direction, the box stretches that way, and a shear stress tilts it. The box overshoots and swings like a heavy spring, so the mass of the walls sets how fast it swings.
The total of the energy of the atoms, the work against the outside pressure and the energy of the moving walls stays fixed. To also keep the temperature fixed, a thermostat must be added.
The problem
The input is particles in dimensions with positions , velocities and masses , a periodic cell with the matrix whose columns are the cell vectors (volume ), a cell velocity , a pair potential, a time step , a number of steps , the external pressure and the cell mass . The particles use scaled coordinates . With , the Lagrangian of Parrinello and Rahman gives the Hamiltonian
with the momenta and . The first term is the kinetic energy of the particles in Cartesian velocities . Its equations give the cell equation
with the internal pressure tensor . The output is the trajectory and, after each step, , and . The implementation works in with a force-shifted Lennard-Jones potential. For the kinetic temperature, , since the flow keeps , and with it the total momentum, at 0.
The algorithm
PARRINELLO-RAHMAN(s, pi, H, P_H, m, h, S, P, W)- 1
(U, f, F) ← FORCES(s, H) ▷ F = Σ_pairs f_ij s_ij^T, with minimum images - 2
for step ← 1 to S do - 3
pi_i ← pi_i + (h/2) H^T f_i; P_H ← P_H + (h/2)(F - P det(H) H^-T) ▷ V: potential and P V - 4
for each i: v_i ← H^-T pi_i / m_i; s_i ← s_i + (h/2) H^-1 v_i; P_H ← P_H + (h/2) m_i v_i (H^-1 v_i)^T ▷ T - 5
H ← H + h P_H / W ▷ C: cell drift - 6
repeat line L4 with the new H ▷ T - 7
(U, f, F) ← FORCES(s, H) - 8
repeat line L3 ▷ V - 9
record E, det(H) and the pressure tensor Pi - 10
return (H s, the velocities, H, P_H / W, the records)
The energy is split into three parts: , the particle kinetic energy , and the cell kinetic energy. Each part has an exact flow. In the part the Cartesian velocities stay fixed while the scaled positions move, so line L4 is exact. The step V T C T V is a palindrome, so it is symplectic, time-reversible and of order 2, with one force evaluation per step. With the cell stays fixed and the step is velocity Verlet.
Example
The test system. 24 particles with on a triangular lattice with spacing 1.12, in reduced Lennard-Jones units, with the cutoff , so the cell is and . The velocities are normal with standard deviation 0.3 (seed 3), less their mean. Then , , and . The internal pressure is , with off-diagonal entries of .
Second order energy error. With , and the cell at rest, run to :
| 0.01 | 0.005 | 0.0025 | |
|---|---|---|---|
| spread of |
The spread falls by a factor of 4 when is halved. A run of 150 steps forward and 150 back with the velocities flipped recovers the start to . With the positions agree with velocity Verlet in the fixed cell to .
The pressure follows the external pressure. With , and 400 steps:
| mean of | range of | |
|---|---|---|
| 0.5 | 0.4917 | 26.07 to 26.78 |
| 1.5 | 1.4987 | 25.73 to 26.09 |
At , less than the initial internal pressure, the cell grows. At it shrinks. These are measurements. The time average of tends to because stays bounded in the cell equation.
Correctness
The proof in proofs/correctness.md shows:
- The three flows are exact, so the step is symplectic.
- Time reversal. The step is a palindrome of flows that the flip of all momenta reverses.
- The cell equation of the flow is .
- Conserved momenta. The flow and the step keep and the antisymmetric part of . So a cell that starts without rotation does not start to rotate.
- Large cell mass. As the step tends to velocity Verlet in a fixed cell.
- Minimum image. If is less than the smallest width of the cell, each pair has at most one image within , the one that the code uses.
- The ensemble. The flow keeps , the enthalpy plus the cell kinetic energy, so if it is ergodic it samples NPH. With a thermostat on all variables at , the stationary density is , with the Lebesgue measure on the entries of .
The measure on is the question for NPT. Since gives the weight , not , the method with a thermostat samples an NPT distribution in which the volume has the extra weight . The configurational integral already has the factor , so this changes volume averages by a relative amount of order . Later constant pressure equations, such as those in the work of Martyna, Tuckerman, Tobias and Klein, are built to give the weight of the standard NPT ensemble.
Proof: The Parrinello-Rahman splitting is a symmetric composition of exact Hamiltonian flows, and it samples NPHfull
The cell is the matrix whose columns are the cell vectors, with volume . Particle has scaled coordinates , position and momentum conjugate to ; is conjugate to , is the cell mass and the external pressure. With , the Hamiltonian is
Since along the flow, is the velocity of particle relative to the moving cell, and is the kinetic energy of Parrinello and Rahman (1981). The potential is a sum of pair terms over minimum images, with and .
Claim 1 (the three flows are exact). Write with , and . The exact flows for a time are:
- : and (lines L3 and L8).
- : and (lines L4 and L6).
- : (line L5).
Proof. depends only on and , so under its flow and are fixed and the momenta move at constant rates and . Now by the chain rule. Inside one minimum image region differs from by a fixed integer vector, so and . Jacobi's formula gives .
depends only on and , so these are fixed, is fixed, , and . With , , so
and .
depends only on , so is fixed and .
Each flow is the exact flow of a Hamiltonian, so it is symplectic. The step is the palindrome , so it is symplectic and has order 2 (see operator splitting), and is kept up to over a fixed time. Line L7 computes the forces at the new and , and they are used again in line L3 of the next step, where and have not changed.
Claim 2 (time reversal). With , .
Proof. is even in , so for each part , and a palindrome of such maps is reversed by .
Claim 3 (the cell equation). Along the exact flow of ,
Proof. , the sum of the rates in Claim 1. Since , , and .
is the internal pressure tensor (kinetic part plus virial), computed in line L9. So the cell accelerates while . If stays bounded, the time average of tends to 0, so the time average of is 0: the internal pressure balances the external one on average. The tests show this for two values of .
Claim 4 (conserved momenta). The exact flow and the step keep and the antisymmetric part of .
Proof. changes only in , by , because the pair forces cancel. For the second, each of , and is invariant under , for a rotation , with and fixed: , depends on distances, and . The generator of this group action is for antisymmetric , which is the component of the antisymmetric part of . By Noether's theorem the exact flow of each part keeps it, so the composition does too.
So a cell started with a nonzero antisymmetric part of turns steadily. The test runs start with a zero cell velocity.
Claim 5 (large cell mass). With , . As with fixed, changes by per step, and the step tends to velocity Verlet in a fixed cell.
Proof. grows by at most a bounded amount per step, so moves by in steps. With fixed, is (since ) and is , which give .
Claim 6 (minimum image). Let be the distances between opposite faces of the cell. If , then for each pair there is at most one image closer than , and it is the one with scaled separation .
Proof. Row of is normal to the face spanned by the other cell vectors, with length . So for , . An image with has for all , and rounding finds this . Two such images would differ by an integer vector with all components less than 1 in size, which is 0. The implementation raises an error when the condition fails.
Claim 7 (the ensemble). The flow keeps and at the fixed pressure , and is the enthalpy plus the cell kinetic energy. So, if it is ergodic, it samples an isoenthalpic-isobaric (NPH) distribution, not the isothermal-isobaric one. Now let a thermostat at act on all of so that the stationary density is . Then the density of with is
with the Lebesgue measure on the entries of .
Proof. and at fixed , so . The integral over is a Gaussian constant.
Integrated over the cell shapes at a fixed volume near a given shape, the measure gives the weight , since with and scales as times a measure on . So with a thermostat the method samples an NPT distribution in which the volume has the weight , not . The configurational integral already carries the factor , so the extra factor changes the volume averages by a relative amount of order .
Complexity
Each step does one force evaluation with the minimum image of each pair, work for the particle flows and work for the cell. With all pairs, steps take time; with neighbor lists, . The extra space is for the scaled coordinates and momenta.
Properties
- Ensemble. NPH if the flow is ergodic. NPT only with a thermostat added, and then with the volume weight of the measure .
- Flexible cell. Both volume and shape change, driven by the full pressure tensor, so stress-driven phase transitions in solids can occur.
- Symplectic and time-reversible with the splitting used here.
- A conserved quantity to monitor. drifts only by integration error.
- Fictitious cell dynamics. The mass is a choice, and the motion of the cell has no physical meaning. Static averages do not depend on , but the volume oscillates with a period set by , and a small disturbs the dynamics of the particles.
- Rotation. The cell can rotate if the antisymmetric part of is not 0 at the start.
Variants and improvements
- Isotropic cells. Andersen (1980) let only the volume change, which suits liquids. The cell is then a scalar.
- Thermostats for NPT. Nose-Hoover chains on the particles and on the cell give a deterministic NPT method, and Martyna, Tuckerman, Tobias and Klein (1996) gave reversible integrators for it. Langevin dynamics or stochastic velocity rescaling on the particles also give NPT when the cell variables are thermostatted too.
- Stochastic barostats. Langevin piston methods and stochastic cell rescaling add friction and noise to the cell, which damps the oscillations of the volume.
- External stress. Parrinello and Rahman (1981) replaced by a general stress term, for simulations under uniaxial load.
- Weak coupling. The Berendsen barostat scales the box toward the target pressure. It equilibrates quickly but does not sample a known ensemble.
When to use it
Use it for crystals and other solids, where the cell must change shape: phase transitions under pressure, elastic constants from the fluctuations of , anisotropic materials and membranes. Combine it with a thermostat for NPT. For liquids an isotropic barostat is simpler. Use a weak coupling method for the first equilibration, since a cell far from equilibrium oscillates strongly with Parrinello-Rahman.
Pitfalls
- Expecting NPT from the barostat alone. Without a thermostat the temperature drifts and the ensemble is NPH.
- Too small a cell mass. The cell then oscillates fast, and the time step must resolve it; check the spread of .
- Starting far from equilibrium. A large pressure difference makes the cell oscillate with a large amplitude, and the system can become unstable. Equilibrate first.
- A cell that becomes too thin. If the cell shears so that exceeds a width, the minimum image is wrong. The implementation raises an error in this case.
- A rotating cell. Start with a symmetric , for example a cell at rest, or restrict to an upper triangular form as many codes do.
- Wrong . The total momentum is conserved, so subtract .
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/parrinello-rahman-barostat/. The authors are listed in prov/A5VK4X.jsonl.
"""The Parrinello-Rahman barostat in two dimensions, with a symmetric splitting.
The periodic cell is the 2 by 2 matrix H whose columns are the cell vectors.
Particle i has scaled coordinates s_i in [0, 1)^2 and the position r_i = H s_i.
With G = H^T H, the momenta pi_i = m_i G ds_i/dt, the cell momentum P_H, the
cell mass W and the external pressure P, the Hamiltonian is
E = sum_i pi_i^T G^-1 pi_i / (2 m_i) + U(H s) + tr(P_H^T P_H) / (2 W) + P det(H).
E is the enthalpy of the particles plus the kinetic energy of the cell. The
flow of E samples the isoenthalpic-isobaric (NPH) ensemble. A thermostat on
the particles and on the cell is needed for the NPT ensemble.
E is split into three parts. Each part has an exact flow:
V: U + P det(H) pi_i += t H^T f_i,
P_H += t (sum_pairs f_ij s_ij^T - P det(H) H^-T)
T: particle kinetic s_i += t H^-1 v_i, P_H += t sum_i m_i v_i (H^-1 v_i)^T,
with v_i = H^-T pi_i / m_i (fixed during the flow)
C: cell kinetic H += t P_H / W
One step of length h is V(h/2) T(h/2) C(h) T(h/2) V(h/2). It is symplectic,
time reversible and second order, and it uses one force evaluation per step.
The pair potential is the Lennard-Jones potential with a force shift at the
cutoff rc, so that the energy and the force are continuous at rc.
Cost per step: one force evaluation, here Theta(N^2) pairs, and Theta(N)
other work.
"""
import math
from typing import Callable
Vec = list[float]
Mat = list[list[float]]
PairPotential = Callable[[float], tuple[float, float]]
def lj_force_shifted(rc: float, eps: float = 1.0, sigma: float = 1.0) -> PairPotential:
"""Lennard-Jones phi(r) - phi(rc) - (r - rc) phi'(rc); returns (energy, -dphi/dr)."""
def raw(r: float) -> tuple[float, float]:
sr6 = (sigma / r) ** 6
return 4.0 * eps * (sr6 * sr6 - sr6), 24.0 * eps * (2.0 * sr6 * sr6 - sr6) / r
ec, fc = raw(rc)
def phi(r: float) -> tuple[float, float]:
e, f = raw(r)
return e - ec + (r - rc) * fc, f - fc
phi.rc = rc
return phi
def det2(a: Mat) -> float:
return a[0][0] * a[1][1] - a[0][1] * a[1][0]
def inv2(a: Mat) -> Mat:
d = det2(a)
return [[a[1][1] / d, -a[0][1] / d], [-a[1][0] / d, a[0][0] / d]]
def mv(a: Mat, x: Vec) -> Vec:
return [a[0][0] * x[0] + a[0][1] * x[1], a[1][0] * x[0] + a[1][1] * x[1]]
def mtv(a: Mat, x: Vec) -> Vec:
"""a^T x."""
return [a[0][0] * x[0] + a[1][0] * x[1], a[0][1] * x[0] + a[1][1] * x[1]]
def min_width(cell: Mat) -> float:
"""The smaller of the two distances between opposite sides of the cell."""
area = abs(det2(cell))
la = math.hypot(cell[0][0], cell[1][0])
lb = math.hypot(cell[0][1], cell[1][1])
return min(area / la, area / lb)
def pair_forces(s: list[Vec], cell: Mat, phi: PairPotential) -> tuple[float, list[Vec], Mat, Mat]:
"""Return U, the Cartesian forces f_i, sum f_ij s_ij^T and the virial sum f_ij r_ij^T.
Each pair uses the image with scaled separation in [-1/2, 1/2]^2. If
2 rc is less than the smallest width w_k of the cell, this image is the
only one closer than rc: a scaled component of a vector r has size at
most |r| / w_k < 1/2. So the function raises ValueError if 2 rc >= the
smallest width.
"""
rc = phi.rc
if 2.0 * rc >= min_width(cell):
raise ValueError("cutoff too large for the cell")
n = len(s)
u = 0.0
f = [[0.0, 0.0] for _ in range(n)]
fs = [[0.0, 0.0], [0.0, 0.0]]
vir = [[0.0, 0.0], [0.0, 0.0]]
rc2 = rc * rc
for i in range(n):
si = s[i]
for j in range(i + 1, n):
d0 = si[0] - s[j][0]
d1 = si[1] - s[j][1]
a0 = d0 - round(d0)
a1 = d1 - round(d1)
r0 = cell[0][0] * a0 + cell[0][1] * a1
r1 = cell[1][0] * a0 + cell[1][1] * a1
r2 = r0 * r0 + r1 * r1
if r2 >= rc2:
continue
r = math.sqrt(r2)
e, mag = phi(r)
u += e
g0 = mag * r0 / r
g1 = mag * r1 / r
f[i][0] += g0
f[i][1] += g1
f[j][0] -= g0
f[j][1] -= g1
fs[0][0] += g0 * a0
fs[0][1] += g0 * a1
fs[1][0] += g1 * a0
fs[1][1] += g1 * a1
vir[0][0] += g0 * r0
vir[0][1] += g0 * r1
vir[1][0] += g1 * r0
vir[1][1] += g1 * r1
return u, f, fs, vir
def _velocities(pi: list[Vec], m: list[float], cell: Mat) -> list[Vec]:
hinv = inv2(cell)
return [[c / mi for c in mtv(hinv, p)] for p, mi in zip(pi, m)]
def _kick(pi, ph, f, fs, cell, pressure, t):
"""The exact flow of U + P det(H) for a time t."""
for i, fi in enumerate(f):
g = mtv(cell, fi)
pi[i][0] += t * g[0]
pi[i][1] += t * g[1]
vol = det2(cell)
hit = inv2(cell)
for a in range(2):
for b in range(2):
ph[a][b] += t * (fs[a][b] - pressure * vol * hit[b][a])
def _drift_particles(s, pi, ph, m, cell, t):
"""The exact flow of the particle kinetic energy for a time t."""
hinv = inv2(cell)
for i, vi in enumerate(_velocities(pi, m, cell)):
sd = mv(hinv, vi)
s[i][0] += t * sd[0]
s[i][1] += t * sd[1]
for a in range(2):
for b in range(2):
ph[a][b] += t * m[i] * vi[a] * sd[b]
def energy(s, pi, ph, m, cell, pressure, w, u) -> float:
"""The conserved quantity E = K + U + tr(P_H^T P_H) / (2 W) + P det(H)."""
k = sum(0.5 * mi * (vi[0] ** 2 + vi[1] ** 2) for vi, mi in zip(_velocities(pi, m, cell), m))
kc = sum(ph[a][b] ** 2 for a in range(2) for b in range(2)) / (2.0 * w)
return k + u + kc + pressure * det2(cell)
def pressure_tensor(v: list[Vec], m: list[float], vir: Mat, cell: Mat) -> Mat:
"""The internal pressure tensor (sum m v v^T + sum f_ij r_ij^T) / det(H)."""
vol = det2(cell)
return [[(sum(mi * vi[a] * vi[b] for vi, mi in zip(v, m)) + vir[a][b]) / vol
for b in range(2)] for a in range(2)]
def parrinello_rahman(
r: list[Vec], v: list[Vec], m: list[float], cell: Mat, cell_velocity: Mat,
phi: PairPotential, h: float, steps: int, pressure: float, w: float,
) -> tuple[list[Vec], list[Vec], Mat, Mat, list[tuple[float, float, Mat]]]:
"""Run steps of the Parrinello-Rahman equations (NPH) in two dimensions.
r and v are Cartesian positions and velocities. cell_velocity is dH/dt.
Returns the final positions (unwrapped), velocities, cell and cell
velocity, and (E, det(H), internal pressure tensor) after each step.
The inputs are not changed.
"""
if h <= 0 or w <= 0:
raise ValueError("need h > 0 and w > 0")
cell = [list(row) for row in cell]
hinv = inv2(cell)
s = [mv(hinv, ri) for ri in r]
pi = [[mi * c for c in mtv(cell, vi)] for vi, mi in zip(v, m)]
ph = [[w * c for c in row] for row in cell_velocity]
u, f, fs, vir = pair_forces(s, cell, phi) # @line L1
out = []
for _ in range(steps): # @line L2
_kick(pi, ph, f, fs, cell, pressure, 0.5 * h) # @line L3
_drift_particles(s, pi, ph, m, cell, 0.5 * h) # @line L4
for a in range(2):
for b in range(2):
cell[a][b] += h * ph[a][b] / w # @line L5
_drift_particles(s, pi, ph, m, cell, 0.5 * h) # @line L6
u, f, fs, vir = pair_forces(s, cell, phi) # @line L7
_kick(pi, ph, f, fs, cell, pressure, 0.5 * h) # @line L8
vel = _velocities(pi, m, cell)
out.append((energy(s, pi, ph, m, cell, pressure, w, u), det2(cell),
pressure_tensor(vel, m, vir, cell))) # @line L9
pos = [mv(cell, si) for si in s]
vel = _velocities(pi, m, cell)
return pos, vel, cell, [[c / w for c in row] for row in ph], out # @line L10
def triangular_lattice(cols: int, rows: int, a: float) -> tuple[list[Vec], Mat]:
"""A triangular lattice of cols by rows sites (rows even) with spacing a, and its cell."""
if rows % 2:
raise ValueError("rows must be even")
dy = a * math.sqrt(3.0) / 2.0
pos = [[(c + 0.5 * (k % 2)) * a, k * dy] for k in range(rows) for c in range(cols)]
return pos, [[cols * a, 0.0], [0.0, rows * dy]]
test_parrinello_rahman_barostat.py 144 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/parrinello-rahman-barostat/. The authors are listed in prov/A5VK4X.jsonl.
import math
import random
import pytest
from parrinello_rahman_barostat import (
det2,
lj_force_shifted,
pair_forces,
parrinello_rahman,
triangular_lattice,
)
PHI = lj_force_shifted(1.8)
ZERO = [[0.0, 0.0], [0.0, 0.0]]
def lattice(seed, spread=0.3):
pos, cell = triangular_lattice(4, 6, 1.12)
rng = random.Random(seed)
vel = [[rng.gauss(0.0, spread), rng.gauss(0.0, spread)] for _ in pos]
cm = [sum(v[a] for v in vel) / len(vel) for a in range(2)]
return pos, [[v[0] - cm[0], v[1] - cm[1]] for v in vel], cell
def test_enthalpy_is_conserved_with_second_order_error():
pos, vel, cell = lattice(3)
m = [1.0] * len(pos)
spreads = []
for h in (0.01, 0.005, 0.0025):
out = parrinello_rahman(pos, vel, m, cell, ZERO, PHI, h, round(0.5 / h), 1.0, 5.0)[4]
es = [o[0] for o in out]
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)
def test_time_reversible():
pos, vel, cell = lattice(4)
m = [1.0] * len(pos)
cv = [[0.01, 0.002], [-0.003, -0.02]]
r, v, c, cd, _ = parrinello_rahman(pos, vel, m, cell, cv, PHI, 0.005, 150, 1.0, 5.0)
neg = [[-x for x in row] for row in v]
r, v, c, cd, _ = parrinello_rahman(r, neg, m, c, [[-x for x in row] for row in cd], PHI, 0.005, 150, 1.0, 5.0)
for a, b in zip(r, pos):
assert a == pytest.approx(b, abs=1e-9)
for a, b in zip(v, vel):
assert [-x for x in a] == pytest.approx(b, abs=1e-9)
for a, b in zip(c, cell):
assert a == pytest.approx(b, abs=1e-9)
def velocity_verlet_fixed_cell(pos, vel, cell, h, steps):
"""Reference: plain velocity Verlet in the fixed rectangular cell."""
lx, ly = cell[0][0], cell[1][1]
r = [list(p) for p in pos]
v = [list(p) for p in vel]
def forces():
f = [[0.0, 0.0] for _ in r]
for i in range(len(r)):
for j in range(i + 1, len(r)):
dx = r[i][0] - r[j][0]
dy = r[i][1] - r[j][1]
dx -= lx * round(dx / lx)
dy -= ly * round(dy / ly)
d = math.hypot(dx, dy)
if d < PHI.rc:
_, mag = PHI(d)
f[i][0] += mag * dx / d
f[i][1] += mag * dy / d
f[j][0] -= mag * dx / d
f[j][1] -= mag * dy / d
return f
f = forces()
for _ in range(steps):
for i in range(len(r)):
for a in range(2):
v[i][a] += 0.5 * h * f[i][a]
r[i][a] += h * v[i][a]
f = forces()
for i in range(len(r)):
for a in range(2):
v[i][a] += 0.5 * h * f[i][a]
return r, v
def test_heavy_cell_reduces_to_constant_volume_dynamics():
pos, vel, cell = lattice(5)
m = [1.0] * len(pos)
r, v, c, _, out = parrinello_rahman(pos, vel, m, cell, ZERO, PHI, 0.01, 100, 1.0, 1e14)
r_ref, v_ref = velocity_verlet_fixed_cell(pos, vel, cell, 0.01, 100)
for a, b in zip(r, r_ref):
assert a == pytest.approx(b, abs=1e-7)
for a, b in zip(v, v_ref):
assert a == pytest.approx(b, abs=1e-7)
assert out[-1][1] == pytest.approx(det2(cell), rel=1e-9)
def test_cell_shrinks_under_high_pressure_and_grows_under_low_pressure():
pos, vel, cell = lattice(6)
m = [1.0] * len(pos)
v0 = det2(cell)
high = parrinello_rahman(pos, vel, m, cell, ZERO, PHI, 0.01, 60, 4.0, 5.0)[4]
low = parrinello_rahman(pos, vel, m, cell, ZERO, PHI, 0.01, 60, -1.0, 5.0)[4]
assert high[-1][1] < v0 < low[-1][1]
def test_internal_pressure_averages_to_the_external_pressure():
# W d^2H/dt^2 = det(H) (Pi - P) H^-T, and dH/dt stays bounded, so the
# time average of the internal pressure tends to P.
pos, vel, cell = lattice(3)
m = [1.0] * len(pos)
for pressure in (0.5, 1.5):
out = parrinello_rahman(pos, vel, m, cell, ZERO, PHI, 0.01, 400, pressure, 2.0)[4]
p = [0.5 * (o[2][0][0] + o[2][1][1]) for o in out]
assert sum(p) / len(p) == pytest.approx(pressure, abs=0.05)
def test_virial_matches_finite_difference_of_energy_under_strain():
# dU/dH = -sum f_ij s_ij^T: compare with a central difference.
pos, _, cell = lattice(7)
rng = random.Random(7)
pos = [[x + rng.uniform(-0.05, 0.05), y + rng.uniform(-0.05, 0.05)] for x, y in pos]
inv = [[1 / cell[0][0], 0.0], [0.0, 1 / cell[1][1]]]
s = [[inv[0][0] * x, inv[1][1] * y] for x, y in pos]
_, _, fs, _ = pair_forces(s, cell, PHI)
eps = 1e-6
for a in range(2):
for b in range(2):
up = [list(row) for row in cell]
dn = [list(row) for row in cell]
up[a][b] += eps
dn[a][b] -= eps
du = (pair_forces(s, up, PHI)[0] - pair_forces(s, dn, PHI)[0]) / (2 * eps)
assert -du == pytest.approx(fs[a][b], abs=1e-5)
def test_cutoff_larger_than_half_the_cell_raises():
pos, _, cell = lattice(1)
with pytest.raises(ValueError):
pair_forces([[0.0, 0.0], [0.5, 0.5]], [[3.0, 0.0], [0.0, 3.0]], PHI)
History
Andersen (1980) proposed a barostat in which the volume is a dynamical variable. In the same year Parrinello and Rahman generalized it to a cell matrix with its own kinetic energy, so that the shape could change, and in 1981 they gave the method in full and used it to study polymorphic transitions in crystals. Later work combined it with thermostats, and Martyna, Tuckerman, Tobias and Klein (1996) gave reversible integrators for constant pressure dynamics with a flexible cell. The method is available in most molecular dynamics codes.
References
- M. Parrinello and A. Rahman, Crystal structure and pair potentials, A molecular-dynamics study, Physical Review Letters 45(14), 1980, 1196-1199, the Lagrangian with the cell matrix as a variable and the first simulation of a structural transition
- M. Parrinello and A. Rahman, Polymorphic transitions in single crystals, A new molecular dynamics method, Journal of Applied Physics 52(12), 1981, 7182-7190, the full equations of motion for the particles and the cell under an external stress, and the conserved quantity
- 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, reversible splitting integrators for constant pressure dynamics with a flexible cell and thermostat chains
- Mark E. Tuckerman, Statistical Mechanics, Theory and Molecular Simulation, Oxford University Press, 2010, Chapter 5, the isobaric ensembles, including anisotropic cell fluctuations
- Daan Frenkel and Berend Smit, Understanding Molecular Simulation, From Algorithms to Applications, second edition, Academic Press, 2002, the chapter on molecular dynamics in various ensembles, constant pressure
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 A5VK4X Edit this page History Report an error Markdown