Algorithm Search⌘K

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
Properties
deterministiciterativesymmetricsymplectic
Origin
Michele Parrinello, Aneesur Rahman, 1980

The Parrinello-Rahman barostat controls the pressure in molecular dynamics with periodic boundary conditions. It makes the matrix HH of the cell vectors a dynamical variable with a mass WW. 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 NN particles in dd dimensions with positions rir_i, velocities viv_i and masses mim_i, a periodic cell with the matrix HH whose columns are the cell vectors (volume V=det⁡HV = \det H), a cell velocity H˙\dot H, a pair potential, a time step hh, a number of steps SS, the external pressure PP and the cell mass W>0W > 0. The particles use scaled coordinates si=H−1ri∈[0,1)ds_i = H^{-1} r_i \in [0, 1)^d. With G=HTHG = H^{\mathsf T} H, the Lagrangian of Parrinello and Rahman gives the Hamiltonian

E=∑iπiTG−1πi2mi+U(Hs)+tr⁡(PHTPH)2W+Pdet⁡H,E = \sum_i \frac{\pi_i^{\mathsf T} G^{-1} \pi_i}{2 m_i} + U(H s) + \frac{\operatorname{tr}(P_H^{\mathsf T} P_H)}{2W} + P \det H,

with the momenta πi=miGs˙i\pi_i = m_i G \dot s_i and PH=WH˙P_H = W \dot H. The first term is the kinetic energy KK of the particles in Cartesian velocities vi=Hs˙iv_i = H \dot s_i. Its equations give the cell equation

WH¨=V (Π−PI) H−T,Π=1V(∑imiviviT+∑i<jfijrijT),W \ddot H = V\,(\Pi - P I)\,H^{-\mathsf T}, \qquad \Pi = \frac{1}{V}\Bigl(\sum_i m_i v_i v_i^{\mathsf T} + \sum_{i < j} f_{ij} r_{ij}^{\mathsf T}\Bigr),

with the internal pressure tensor Π\Pi. The output is the trajectory and, after each step, EE, det⁡H\det H and Π\Pi. The implementation works in d=2d = 2 with a force-shifted Lennard-Jones potential. For the kinetic temperature, Nf=dN−dN_f = dN - d, since the flow keeps ∑iπi\sum_i \pi_i, and with it the total momentum, at 0.

The algorithm

  1. PARRINELLO-RAHMAN(s, pi, H, P_H, m, h, S, P, W)
  2. 1(U, f, F) ← FORCES(s, H) ▷ F = Σ_pairs f_ij s_ij^T, with minimum images
  3. 2for step ← 1 to S do
  4. 3pi_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
  5. 4for 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
  6. 5H ← H + h P_H / W ▷ C: cell drift
  7. 6repeat line L4 with the new H ▷ T
  8. 7(U, f, F) ← FORCES(s, H)
  9. 8repeat line L3 ▷ V
  10. 9record E, det(H) and the pressure tensor Pi
  11. 10return (H s, the velocities, H, P_H / W, the records)

The energy is split into three parts: U+Pdet⁡HU + P\det H, the particle kinetic energy KK, and the cell kinetic energy. Each part has an exact flow. In the KK 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 W→∞W \to \infty the cell stays fixed and the step is velocity Verlet.

Example

The test system. 24 particles with m=1m = 1 on a 4×64 \times 6 triangular lattice with spacing 1.12, in reduced Lennard-Jones units, with the cutoff rc=1.8r_c = 1.8, so the cell is 4.48×5.819694.48 \times 5.81969 and V0=26.0722V_0 = 26.0722. The velocities are normal with standard deviation 0.3 (seed 3), less their mean. Then K=1.886K = 1.886, Nf=46N_f = 46, kBT=2K/Nf=0.0820k_B T = 2K/N_f = 0.0820 and U=−45.704U = -45.704. The internal pressure is Π≈0.865I\Pi \approx 0.865 I, with off-diagonal entries of −0.0074-0.0074.

Second order energy error. With P=1P = 1, W=5W = 5 and the cell at rest, run to t=0.5t = 0.5:

hh 0.01 0.005 0.0025
spread of EE 6.152×10−36.152 \times 10^{-3} 1.579×10−31.579 \times 10^{-3} 3.979×10−43.979 \times 10^{-4}

The spread falls by a factor of 4 when hh is halved. A run of 150 steps forward and 150 back with the velocities flipped recovers the start to 10−910^{-9}. With W=1014W = 10^{14} the positions agree with velocity Verlet in the fixed cell to 10−710^{-7}.

The pressure follows the external pressure. With W=2W = 2, h=0.01h = 0.01 and 400 steps:

PP mean of 12tr⁡Π\frac12 \operatorname{tr} \Pi range of VV
0.5 0.4917 26.07 to 26.78
1.5 1.4987 25.73 to 26.09

At P=0.5P = 0.5, less than the initial internal pressure, the cell grows. At P=1.5P = 1.5 it shrinks. These are measurements. The time average of Π\Pi tends to PP because H˙\dot H stays bounded in the cell equation.

Correctness

The proof in proofs/correctness.md shows:

  1. The three flows are exact, so the step is symplectic.
  2. Time reversal. The step is a palindrome of flows that the flip of all momenta reverses.
  3. The cell equation of the flow is WH¨=V(Π−PI)H−TW\ddot H = V(\Pi - P I)H^{-\mathsf T}.
  4. Conserved momenta. The flow and the step keep ∑iπi\sum_i \pi_i and the antisymmetric part of PHHTP_H H^{\mathsf T}. So a cell that starts without rotation does not start to rotate.
  5. Large cell mass. As W→∞W \to \infty the step tends to velocity Verlet in a fixed cell.
  6. Minimum image. If 2rc2 r_c is less than the smallest width of the cell, each pair has at most one image within rcr_c, the one that the code uses.
  7. The ensemble. The flow keeps EE, the enthalpy K+U+PVK + U + PV plus the cell kinetic energy, so if it is ergodic it samples NPH. With a thermostat on all variables at kBTk_B T, the stationary density is e−β(K+U+PV) dr dp dHe^{-\beta(K + U + PV)}\,dr\,dp\,dH, with the Lebesgue measure on the d2d^2 entries of HH.

The measure on VV is the question for NPT. Since dHdH gives the weight Vd−1 dVV^{d-1}\,dV, not dVdV, the method with a thermostat samples an NPT distribution in which the volume has the extra weight Vd−1V^{d-1}. The configurational integral already has the factor VNV^N, so this changes volume averages by a relative amount of order (d−1)/N(d-1)/N. 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 d×dd \times d matrix HH whose columns are the cell vectors, with volume V=det⁡H>0V = \det H > 0. Particle ii has scaled coordinates sis_i, position ri=Hsir_i = H s_i and momentum πi\pi_i conjugate to sis_i; PHP_H is conjugate to HH, W>0W > 0 is the cell mass and PP the external pressure. With vi=H−Tπi/miv_i = H^{-\mathsf T} \pi_i / m_i, the Hamiltonian is

E=∑i12mi∣vi∣2⏟K+U(Hs)+tr⁡(PHTPH)2W+Pdet⁡H.E = \underbrace{\sum_i \tfrac12 m_i |v_i|^2}_{K} + U(Hs) + \frac{\operatorname{tr}(P_H^{\mathsf T} P_H)}{2W} + P \det H.

Since πi=miHTHs˙i\pi_i = m_i H^{\mathsf T} H \dot s_i along the flow, vi=Hs˙iv_i = H \dot s_i is the velocity of particle ii relative to the moving cell, and K=∑i12mis˙iTHTHs˙iK = \sum_i \frac12 m_i \dot s_i^{\mathsf T} H^{\mathsf T} H \dot s_i is the kinetic energy of Parrinello and Rahman (1981). The potential is a sum of pair terms ϕ(∣rij∣)\phi(|r_{ij}|) over minimum images, with rij=Hsijr_{ij} = H s_{ij} and fij=−ϕ′(∣rij∣) rij/∣rij∣f_{ij} = -\phi'(|r_{ij}|)\, r_{ij}/|r_{ij}|.

Claim 1 (the three flows are exact). Write E=EV+ET+ECE = E_V + E_T + E_C with EV=U+Pdet⁡HE_V = U + P\det H, ET=KE_T = K and EC=tr⁡(PHTPH)/(2W)E_C = \operatorname{tr}(P_H^{\mathsf T} P_H)/(2W). The exact flows for a time tt are:

  • EVE_V: πi+=t HTfi\pi_i \mathrel{+}= t\,H^{\mathsf T} f_i and PH+=t(∑i<jfijsijT−PVH−T)P_H \mathrel{+}= t\bigl(\sum_{i<j} f_{ij} s_{ij}^{\mathsf T} - P V H^{-\mathsf T}\bigr) (lines L3 and L8).
  • ETE_T: si+=t H−1vis_i \mathrel{+}= t\,H^{-1} v_i and PH+=t∑imivi(H−1vi)TP_H \mathrel{+}= t \sum_i m_i v_i (H^{-1} v_i)^{\mathsf T} (lines L4 and L6).
  • ECE_C: H+=tPH/WH \mathrel{+}= t P_H / W (line L5).

Proof. EVE_V depends only on ss and HH, so under its flow ss and HH are fixed and the momenta move at constant rates −∂EV/∂si-\partial E_V/\partial s_i and −∂EV/∂H-\partial E_V/\partial H. Now −∂U/∂si=HTfi-\partial U/\partial s_i = H^{\mathsf T} f_i by the chain rule. Inside one minimum image region sijs_{ij} differs from si−sjs_i - s_j by a fixed integer vector, so ∂∣Hsij∣/∂Hab=(rij)a(sij)b/∣rij∣\partial |H s_{ij}| / \partial H_{ab} = (r_{ij})_a (s_{ij})_b / |r_{ij}| and −∂U/∂H=∑i<jfijsijT-\partial U/\partial H = \sum_{i<j} f_{ij} s_{ij}^{\mathsf T}. Jacobi's formula gives ∂det⁡H/∂H=VH−T\partial \det H/\partial H = V H^{-\mathsf T}.

ETE_T depends only on π\pi and HH, so these are fixed, viv_i is fixed, s˙i=∂K/∂πi=H−1H−Tπi/mi=H−1vi\dot s_i = \partial K / \partial \pi_i = H^{-1}H^{-\mathsf T}\pi_i/m_i = H^{-1} v_i, and P˙H=−∂K/∂H\dot P_H = -\partial K/\partial H. With yi=H−Tπi=miviy_i = H^{-\mathsf T}\pi_i = m_i v_i, dyi=−H−T dHT yidy_i = -H^{-\mathsf T}\,dH^{\mathsf T}\,y_i, so

dK=∑iyiTdyimi=−∑imi(H−1vi)TdHTvi=−∑imi viT dH (H−1vi),dK = \sum_i \frac{y_i^{\mathsf T} dy_i}{m_i} = -\sum_i m_i (H^{-1} v_i)^{\mathsf T} dH^{\mathsf T} v_i = -\sum_i m_i\, v_i^{\mathsf T}\, dH\, (H^{-1} v_i),

and −∂K/∂H=∑imivi(H−1vi)T-\partial K/\partial H = \sum_i m_i v_i (H^{-1} v_i)^{\mathsf T}.

ECE_C depends only on PHP_H, so PHP_H is fixed and H˙=PH/W\dot H = P_H/W. □\square

Each flow is the exact flow of a Hamiltonian, so it is symplectic. The step is the palindrome Ψh=ϕh/2V∘ϕh/2T∘ϕhC∘ϕh/2T∘ϕh/2V\Psi_h = \phi^V_{h/2} \circ \phi^T_{h/2} \circ \phi^C_h \circ \phi^T_{h/2} \circ \phi^V_{h/2}, so it is symplectic and has order 2 (see operator splitting), and EE is kept up to O(h2)O(h^2) over a fixed time. Line L7 computes the forces at the new ss and HH, and they are used again in line L3 of the next step, where ss and HH have not changed.

Claim 2 (time reversal). With R(s,π,H,PH)=(s,−π,H,−PH)R(s, \pi, H, P_H) = (s, -\pi, H, -P_H), Ψh∘R∘Ψh=R\Psi_h \circ R \circ \Psi_h = R.

Proof. EE is even in (π,PH)(\pi, P_H), so for each part R∘ϕt∘R=ϕ−tR \circ \phi_t \circ R = \phi_{-t}, and a palindrome of such maps is reversed by RR. □\square

Claim 3 (the cell equation). Along the exact flow of EE,

WH¨=V (Π−PI) H−T,Π=1V(∑imiviviT+∑i<jfijrijT).W \ddot H = V\,(\Pi - P I)\,H^{-\mathsf T}, \qquad \Pi = \frac{1}{V}\Bigl( \sum_i m_i v_i v_i^{\mathsf T} + \sum_{i<j} f_{ij} r_{ij}^{\mathsf T} \Bigr).

Proof. WH¨=P˙HW\ddot H = \dot P_H, the sum of the rates in Claim 1. Since (H−1vi)T=viTH−T(H^{-1} v_i)^{\mathsf T} = v_i^{\mathsf T} H^{-\mathsf T}, vi(H−1vi)T=viviTH−Tv_i (H^{-1}v_i)^{\mathsf T} = v_i v_i^{\mathsf T} H^{-\mathsf T}, and sijT=rijTH−Ts_{ij}^{\mathsf T} = r_{ij}^{\mathsf T} H^{-\mathsf T}. □\square

Π\Pi is the internal pressure tensor (kinetic part plus virial), computed in line L9. So the cell accelerates while Π≠PI\Pi \ne P I. If PHP_H stays bounded, the time average of P˙H\dot P_H tends to 0, so the time average of V(Π−PI)H−TV(\Pi - P I)H^{-\mathsf T} is 0: the internal pressure balances the external one on average. The tests show this for two values of PP.

Claim 4 (conserved momenta). The exact flow and the step Ψh\Psi_h keep ∑iπi\sum_i \pi_i and the antisymmetric part of PHHTP_H H^{\mathsf T}.

Proof. π\pi changes only in ϕV\phi^V, by tHT∑ifi=0t H^{\mathsf T}\sum_i f_i = 0, because the pair forces cancel. For the second, each of EVE_V, ETE_T and ECE_C is invariant under H↦QHH \mapsto QH, PH↦QPHP_H \mapsto QP_H for a rotation QQ, with ss and π\pi fixed: ∣(QH)−Tπi∣=∣H−Tπi∣|(QH)^{-\mathsf T}\pi_i| = |H^{-\mathsf T}\pi_i|, UU depends on distances, det⁡QH=det⁡H\det QH = \det H and ∣QPH∣=∣PH∣|QP_H| = |P_H|. The generator of this group action is tr⁡((AH)TPH)\operatorname{tr}\bigl((AH)^{\mathsf T}P_H\bigr) for antisymmetric AA, which is the AA component of the antisymmetric part of PHHTP_H H^{\mathsf T}. By Noether's theorem the exact flow of each part keeps it, so the composition does too. □\square

So a cell started with a nonzero antisymmetric part of PHHTP_H H^{\mathsf T} turns steadily. The test runs start with a zero cell velocity.

Claim 5 (large cell mass). With H˙(0)=0\dot H(0) = 0, PH(0)=0P_H(0) = 0. As W→∞W \to \infty with hh fixed, ϕhC\phi^C_h changes HH by O(h2/W)O(h^2/W) per step, and the step tends to velocity Verlet in a fixed cell.

Proof. PHP_H grows by at most a bounded amount per step, so HH moves by O(nh2/W)O(n h^2/W) in nn steps. With HH fixed, ϕtV\phi^V_{t} is vi+=tfi/miv_i \mathrel{+}= t f_i/m_i (since vi=H−Tπi/miv_i = H^{-\mathsf T}\pi_i/m_i) and ϕtT\phi^T_t is ri+=tvir_i \mathrel{+}= t v_i, which give Vh/2AhVh/2V_{h/2}A_hV_{h/2}. □\square

Claim 6 (minimum image). Let w1,…,wdw_1, \ldots, w_d be the distances between opposite faces of the cell. If 2rc<min⁡kwk2r_c < \min_k w_k, then for each pair there is at most one image closer than rcr_c, and it is the one with scaled separation a=sij−round⁡(sij)a = s_{ij} - \operatorname{round}(s_{ij}).

Proof. Row kk of H−1H^{-1} is normal to the face spanned by the other cell vectors, with length 1/wk1/w_k. So for r=Har = Ha, ∣ak∣≤∣r∣/wk|a_k| \le |r|/w_k. An image with ∣r∣<rc|r| < r_c has ∣ak∣<rc/wk<1/2|a_k| < r_c/w_k < 1/2 for all kk, and rounding finds this aa. 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. □\square

Claim 7 (the ensemble). The flow keeps EE and NN at the fixed pressure PP, and EE is the enthalpy K+U+PVK + U + PV 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 kBTk_B T act on all of (s,π,H,PH)(s, \pi, H, P_H) so that the stationary density is e−βE ds dπ dH dPHe^{-\beta E}\,ds\,d\pi\,dH\,dP_H. Then the density of (r,p,H)(r, p, H) with pi=mivip_i = m_i v_i is

e−β(K+U+PV) dr dp dH,e^{-\beta (K + U + PV)}\,dr\,dp\,dH,

with the Lebesgue measure on the d2d^2 entries of HH.

Proof. ri=Hsir_i = H s_i and πi=HTpi\pi_i = H^{\mathsf T} p_i at fixed HH, so dsi dπi=(det⁡H)−1dri (det⁡H) dpi=dri dpids_i\,d\pi_i = (\det H)^{-1} dr_i\,(\det H)\,dp_i = dr_i\,dp_i. The integral over PHP_H is a Gaussian constant. □\square

Integrated over the cell shapes at a fixed volume near a given shape, the measure dHdH gives the weight Vd−1 dVV^{d-1}\,dV, since H=V1/dH0H = V^{1/d} H_0 with det⁡H0=1\det H_0 = 1 and dHdH scales as Vd−1dVV^{d - 1} dV times a measure on H0H_0. So with a thermostat the method samples an NPT distribution in which the volume has the weight Vd−1 dVV^{d-1}\,dV, not dVdV. The configurational integral already carries the factor VNV^N, so the extra factor changes the volume averages by a relative amount of order (d−1)/N(d-1)/N.

Complexity

Each step does one force evaluation with the minimum image of each pair, O(N)O(N) work for the particle flows and O(d3)O(d^3) work for the cell. With all pairs, SS steps take O(SN2)O(S N^2) time; with neighbor lists, O(SN)O(S N). The extra space is O(N)O(N) 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 Vd−1V^{d-1} of the measure dHdH.
  • 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. EE drifts only by integration error.
  • Fictitious cell dynamics. The mass WW is a choice, and the motion of the cell has no physical meaning. Static averages do not depend on WW, but the volume oscillates with a period set by WW, and a small WW disturbs the dynamics of the particles.
  • Rotation. The cell can rotate if the antisymmetric part of PHHTP_H H^{\mathsf T} 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 Pdet⁡HP\det H 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 HH, 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 EE.
  • 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 2rc2 r_c exceeds a width, the minimum image is wrong. The implementation raises an error in this case.
  • A rotating cell. Start with a symmetric PHHTP_H H^{\mathsf T}, for example a cell at rest, or restrict HH to an upper triangular form as many codes do.
  • Wrong NfN_f. The total momentum is conserved, so subtract dd.

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.

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

  1. 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
  2. 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
  3. 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
  4. Mark E. Tuckerman, Statistical Mechanics, Theory and Molecular Simulation, Oxford University Press, 2010, Chapter 5, the isobaric ensembles, including anisotropic cell fluctuations
  5. 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.

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