Algorithm Search⌘K

Algorithmadvanced

Car-Parrinello molecular dynamics

Also called CPMD.

Propagates electronic orbitals as fictitious classical variables together with the nuclei, so ab initio forces need no full electronic minimization each step.

Time
O(T C) worst
Space
O(C) extra
Where
C = the cost of one energy and force evaluation; T = the number of time steps
Properties
deterministicnot iterativenot randomized
Origin
Roberto Car, Michele Parrinello, 1985

Car-Parrinello molecular dynamics (CPMD) is ab initio molecular dynamics in which the electronic orbitals are not solved at each step but move with the nuclei as classical variables. Car and Parrinello (1985) wrote one Lagrangian with the nuclear kinetic energy, a fictitious kinetic energy μ2∣c˙∣2\frac{\mu}{2} |\dot c|^2 of the orbitals with a small fictitious mass μ\mu, the electronic energy E(X,c)E(X, c), and Lagrange multipliers that keep the orbitals orthonormal. Started at the electronic ground state, the orbitals then oscillate fast and with small amplitude around the instantaneous ground state, and the nuclei move almost on the Born-Oppenheimer surface. Each step costs one energy and force evaluation, with no self-consistent field (SCF) loop, but the time step must resolve the fast orbital motion. The method has a conserved energy and no SCF drift, and its error is controlled by μ\mu. Compare Born-Oppenheimer molecular dynamics, which solves the SCF at each step. The code on this page uses the same toy electronic model as the BOMD page, not a real quantum chemistry method.

In plain words

In ordinary ab initio dynamics, the electrons are solved from scratch at every step, which costs many inner iterations.

Car and Parrinello let the electrons move along with the nuclei instead. The electronic state gets a small artificial mass and is pushed by the same energy that holds the nuclei together. Because this mass is small, the electronic state follows the nuclei closely, like a light dog on a short leash that stays near its owner.

Each step is then cheap, but the steps must be short, since the light electronic state moves fast. The answer is slightly off from the exact ground state, by an amount that shrinks with the artificial mass.

The problem

The input is the nuclear positions XX, velocities VV and masses MM, an initial electronic state cc (usually the ground state for XX) with velocity c˙=0\dot c = 0, the fictitious mass μ\mu, and the time step hh. For one orbital with the constraint ∣c∣=1|c| = 1, the Car-Parrinello Lagrangian is

L=∑kMk2x˙k2+μ2∣c˙∣2−E(X,c)+Λ(∣c∣2−1),\mathcal L = \sum_k \frac{M_k}{2} \dot x_k^2 + \frac{\mu}{2} |\dot c|^2 - E(X, c) + \Lambda (|c|^2 - 1),

and its equations of motion are

Mkx¨k=−∂E∂xk,μc¨=−∇cE+2Λc,M_k \ddot x_k = -\frac{\partial E}{\partial x_k}, \qquad \mu \ddot c = -\nabla_c E + 2 \Lambda c,

with Λ\Lambda chosen so that ∣c∣=1|c| = 1 at all times. The conserved energy is Econs=∑kMk2x˙k2+μ2∣c˙∣2+E(X,c)E_{\text{cons}} = \sum_k \frac{M_k}{2} \dot x_k^2 + \frac{\mu}{2} |\dot c|^2 + E(X, c) (Claim 1 of the proof). The toy model is the one of the BOMD page: one orbital per atom on a line, E(X,c)=2cTH0(X)c+U∑ici4+Φ(X)E(X, c) = 2 c^T H_0(X) c + U \sum_i c_i^4 + \Phi(X).

The algorithm

  1. CPMD(X, V, M, c, cdot, mu, h, steps)
  2. 1F_X ← -dE/dX at (X, c); F_c ← -grad_c E at (X, c)
  3. 2for n ← 1 to steps do
  4. 3V ← V + (h / 2) F_X / M; X ← X + h V
  5. 4cdot ← cdot + (h / 2) F_c / mu
  6. 5c ← c + h cdot + lambda c_old, with lambda chosen so |c| = 1; cdot ← cdot + lambda c_old / h ▷ SHAKE
  7. 6F_X ← -dE/dX at (X, c); F_c ← -grad_c E at (X, c)
  8. 7V ← V + (h / 2) F_X / M; cdot ← cdot + (h / 2) F_c / mu
  9. 8cdot ← cdot - (c . cdot) c ▷ RATTLE
  10. 9return the trajectory and E_cons

This is velocity Verlet for the nuclei and the orbital together, with the constraint ∣c∣=1|c| = 1 kept by SHAKE on the positions and RATTLE on the velocities, as in the RATTLE algorithm. Line L5 solves the quadratic ∣d+λcold∣2=1|d + \lambda c_{\text{old}}|^2 = 1 with d=cold+hc˙d = c_{\text{old}} + h \dot c, whose root of smaller size is λ=−d⋅cold+(d⋅cold)2−∣d∣2+1\lambda = -d \cdot c_{\text{old}} + \sqrt{(d \cdot c_{\text{old}})^2 - |d|^2 + 1}. Line L8 removes the part of c˙\dot c along cc, so that ddt∣c∣2=2c⋅c˙=0\frac{d}{dt}|c|^2 = 2 c \cdot \dot c = 0. For many orbitals the same steps keep the orbitals orthonormal with a matrix of multipliers. The nuclear force in line L6 is the partial derivative at the current cc, which is not exactly the Born-Oppenheimer force, because cc is not exactly the ground state.

Example

Orbital frequency. For the dimer with U=0U = 0 at fixed distance r=1r = 1, the two orbital energies are ∓1\mp 1, a gap Δ=2\Delta = 2. Near the ground state the orbital oscillates with angular frequency ω=2Δ/μ\omega = 2\sqrt{\Delta / \mu} (Claim 3). With h=0.002h = 0.002, the measured ω\omega was 28.268 against 22/0.01=28.2842\sqrt{2/0.01} = 28.284 for μ=0.01\mu = 0.01, and 14.134 against 14.142 for μ=0.04\mu = 0.04.

The chain. Four atoms with U=1U = 1, X=(0,1.1,2.0,3.2)X = (0, 1.1, 2.0, 3.2), V=(0.3,−0.2,0.1,−0.2)V = (0.3, -0.2, 0.1, -0.2) and unit masses, started at the self-consistent ground state with c˙=0\dot c = 0, run for a time of 10 and compared with BOMD with a tight SCF at the same time step:

μ\mu hh spread of EconsE_{\text{cons}} largest fictitious kinetic energy largest ∣xCP−xBO∣\lvert x_{\text{CP}} - x_{\text{BO}} \rvert largest EE above the BO surface
0.002 0.002 6.1×10−76.1 \times 10^{-7} 5.4×10−55.4 \times 10^{-5} 8.6×10−48.6 \times 10^{-4} 1.2×10−51.2 \times 10^{-5}
0.01 0.004 2.4×10−62.4 \times 10^{-6} 2.5×10−42.5 \times 10^{-4} 4.3×10−34.3 \times 10^{-3} 5.6×10−55.6 \times 10^{-5}
0.05 0.01 1.5×10−51.5 \times 10^{-5} 1.2×10−31.2 \times 10^{-3} 0.022 2.3×10−42.3 \times 10^{-4}
0.2 0.01 1.4×10−51.4 \times 10^{-5} 3.9×10−33.9 \times 10^{-3} 0.099 2.0×10−32.0 \times 10^{-3}

The mean nuclear kinetic energy was about 0.212, so the fictitious kinetic energy stays a small fraction of it, which is the adiabatic regime. The deviation of the trajectory from BOMD grows about linearly in μ\mu. The norm ∣c∣|c| stayed 1 to 10−1510^{-15}. The self-consistent orbital energies of the chain at the start are −1.641,0.086,0.923,1.632-1.641, 0.086, 0.923, 1.632, a gap of 1.73, so the slowest orbital frequency for μ=0.2\mu = 0.2 is about 21.73/0.2≈5.92\sqrt{1.73/0.2} \approx 5.9, not far above the nuclear frequencies: this is where the error becomes large.

Correctness

The proof in proofs/correctness.md shows:

  1. The conserved energy. The exact Car-Parrinello equations with the constraint conserve EconsE_{\text{cons}}.
  2. The constraint steps. The SHAKE step of line L5 has a real root exactly when h∣c˙⊥∣≤1h |\dot c_\perp| \le 1, where c˙⊥\dot c_\perp is the part of c˙\dot c orthogonal to coldc_{\text{old}}, and then ∣c∣=1|c| = 1 after the step; the RATTLE step of line L8 makes c⋅c˙=0c \cdot \dot c = 0 with the smallest change of c˙\dot c.
  3. The orbital frequency. For U=0U = 0 and fixed nuclei, the motion of cc stays in the plane of the ground state and any other eigenvector, and small oscillations about the ground state have angular frequency 2Δ/μ2\sqrt{\Delta / \mu}, where Δ\Delta is the eigenvalue gap.

The claim that the nuclei follow the BO surface with an error that vanishes as μ→0\mu \to 0 is the adiabatic argument of Car and Parrinello and of Pastore, Smargiassi and Buda (1991). It is not proved here; the table above measures it.

Proof: The conserved energy, the constraint steps and the orbital frequency of Car-Parrinello dynamicsfull

Let E(X,c)E(X, c) be continuously differentiable in the nuclear positions X=(x1,…,xN)X = (x_1, \dots, x_N) and the orbital c∈Rnc \in \mathbb R^n, and let S={c:∣c∣=1}S = \{c : |c| = 1\}. The Car-Parrinello equations with one orbital are

Mkx¨k=−∂E∂xk,μc¨=−∇cE+2Λc,∣c∣=1,M_k \ddot x_k = -\frac{\partial E}{\partial x_k}, \qquad \mu \ddot c = -\nabla_c E + 2 \Lambda c, \qquad |c| = 1,

where Λ(t)\Lambda(t) is the multiplier that keeps cc on SS.

Claim 1 (the conserved energy). Along any solution, Econs=∑kMk2x˙k2+μ2∣c˙∣2+E(X,c)E_{\text{cons}} = \sum_k \frac{M_k}{2} \dot x_k^2 + \frac{\mu}{2} |\dot c|^2 + E(X, c) is constant.

Proof.

dEconsdt=∑kx˙k(Mkx¨k+∂E∂xk)+c˙⋅(μc¨+∇cE)=2Λ c⋅c˙=Λddt∣c∣2=0,\frac{d E_{\text{cons}}}{dt} = \sum_k \dot x_k \Bigl(M_k \ddot x_k + \frac{\partial E}{\partial x_k}\Bigr) + \dot c \cdot (\mu \ddot c + \nabla_c E) = 2 \Lambda\, c \cdot \dot c = \Lambda \frac{d}{dt} |c|^2 = 0,

because the first bracket is 0 by the nuclear equation, the second is 2Λc2\Lambda c by the orbital equation, and ∣c∣2=1|c|^2 = 1 for all tt. □\square

EconsE_{\text{cons}} is not the physical energy: it contains the fictitious kinetic energy μ2∣c˙∣2\frac{\mu}{2}|\dot c|^2, and E(X,c)≥EBO(X)E(X, c) \ge E_{\text{BO}}(X) when EBO(X)=min⁡c∈SE(X,c)E_{\text{BO}}(X) = \min_{c \in S} E(X, c). The physical energy ∑kMk2x˙k2+EBO(X)\sum_k \frac{M_k}{2} \dot x_k^2 + E_{\text{BO}}(X) is conserved only up to these two terms, which is why the page reports the fictitious kinetic energy and the energy above the BO surface.

Claim 2 (the constraint steps). Let cc be the old orbital with ∣c∣=1|c| = 1, let c˙\dot c be the orbital velocity after line L4, and write c˙⊥=c˙−(c⋅c˙) c\dot c_\perp = \dot c - (c \cdot \dot c)\, c. Let d=c+hc˙d = c + h \dot c.

(a) The equation ∣d+λc∣2=1|d + \lambda c|^2 = 1 has a real root if and only if h∣c˙⊥∣≤1h |\dot c_\perp| \le 1. Its roots are λ±=−d⋅c±1−h2∣c˙⊥∣2\lambda_\pm = -d \cdot c \pm \sqrt{1 - h^2 |\dot c_\perp|^2}, and line L5 takes λ+\lambda_+. If also h∣c˙∣<1h |\dot c| < 1, then ∣λ+∣<∣λ−∣|\lambda_+| < |\lambda_-|, and λ+=−h (c⋅c˙)+O(h2∣c˙⊥∣2)\lambda_+ = -h\,(c \cdot \dot c) + O(h^2 |\dot c_\perp|^2). After line L5, ∣cnew∣=1|c_{\text{new}}| = 1 and cnew=c+hc˙newc_{\text{new}} = c + h \dot c_{\text{new}}.

(b) Line L8 replaces c˙\dot c by c˙−(c⋅c˙) c\dot c - (c \cdot \dot c)\, c, which is the vector closest to c˙\dot c among those uu with c⋅u=0c \cdot u = 0.

Proof. (a) ∣d+λc∣2=λ2+2λ d⋅c+∣d∣2|d + \lambda c|^2 = \lambda^2 + 2 \lambda\, d \cdot c + |d|^2, so the roots are −d⋅c±(d⋅c)2−∣d∣2+1-d \cdot c \pm \sqrt{(d \cdot c)^2 - |d|^2 + 1}. With d⋅c=1+h c⋅c˙d \cdot c = 1 + h\, c \cdot \dot c and ∣d∣2=1+2h c⋅c˙+h2∣c˙∣2|d|^2 = 1 + 2h\, c \cdot \dot c + h^2 |\dot c|^2, the discriminant is 1+h2(c⋅c˙)2−h2∣c˙∣2=1−h2∣c˙⊥∣21 + h^2 (c \cdot \dot c)^2 - h^2 |\dot c|^2 = 1 - h^2 |\dot c_\perp|^2. If h∣c˙∣<1h|\dot c| < 1 then d⋅c≥1−h∣c˙∣>0d \cdot c \ge 1 - h |\dot c| > 0, so λ+\lambda_+ is the root of smaller size. Expanding the square root, λ+=−1−h c⋅c˙+1−12h2∣c˙⊥∣2+O(h4∣c˙⊥∣4)\lambda_+ = -1 - h\, c \cdot \dot c + 1 - \frac12 h^2 |\dot c_\perp|^2 + O(h^4 |\dot c_\perp|^4). The code sets c˙new=c˙+λc/h\dot c_{\text{new}} = \dot c + \lambda c / h and cnew=d+λc=c+hc˙newc_{\text{new}} = d + \lambda c = c + h \dot c_{\text{new}}, which has norm 1 by the choice of λ\lambda. (b) The set {u:c⋅u=0}\{u : c \cdot u = 0\} is a subspace, and the closest point of a subspace is the orthogonal projection, which for the complement of the unit vector cc is u=c˙−(c⋅c˙) cu = \dot c - (c \cdot \dot c)\, c. □\square

Thus each step keeps ∣c∣=1|c| = 1 to rounding, as measured on the page (10−1510^{-15}), and the velocity is tangent to SS at the end of each step, which is the hidden constraint ddt∣c∣2=0\frac{d}{dt} |c|^2 = 0. With these two projections, velocity Verlet becomes the RATTLE method, which is symplectic and time reversible on the constrained phase space (see the RATTLE algorithm); this note does not repeat that proof.

Claim 3 (the orbital frequency). Let E(X,c)=2cTHc+constE(X, c) = 2 c^T H c + \text{const} with XX fixed and HH symmetric, with orthonormal eigenvectors e0,eje_0, e_j and eigenvalues ϵ0<ϵj\epsilon_0 < \epsilon_j, and let Δ=ϵj−ϵ0\Delta = \epsilon_j - \epsilon_0. If c(0)c(0) and c˙(0)\dot c(0) lie in the plane PP spanned by e0e_0 and eje_j, then c(t)=cos⁡θ(t) e0+sin⁡θ(t) ejc(t) = \cos\theta(t)\, e_0 + \sin\theta(t)\, e_j for all tt, with

μθ¨=−2Δsin⁡2θ.\mu \ddot \theta = -2 \Delta \sin 2\theta.

Small oscillations about the ground state θ=0\theta = 0 have angular frequency ω=2Δ/μ\omega = 2 \sqrt{\Delta / \mu}.

Proof. Let θ(t)\theta(t) solve the scalar equation with the initial data of cc, and put c(t)=cos⁡θ e0+sin⁡θ ejc(t) = \cos\theta\, e_0 + \sin\theta\, e_j and c⊥=−sin⁡θ e0+cos⁡θ ejc_\perp = -\sin\theta\, e_0 + \cos\theta\, e_j. Then ∣c∣=1|c| = 1 and c¨=−θ˙2c+θ¨ c⊥\ddot c = -\dot\theta^2 c + \ddot\theta\, c_\perp. Also Hc=ϵ0cos⁡θ e0+ϵjsin⁡θ ejH c = \epsilon_0 \cos\theta\, e_0 + \epsilon_j \sin\theta\, e_j, so c⊥⋅(−4Hc)=4sin⁡θcos⁡θ (ϵ0−ϵj)=−2Δsin⁡2θc_\perp \cdot (-4 H c) = 4 \sin\theta \cos\theta\, (\epsilon_0 - \epsilon_j) = -2\Delta \sin 2\theta, and −4Hc-4Hc lies in PP. Choose 2Λ=−μθ˙2+c⋅4Hc2\Lambda = -\mu \dot\theta^2 + c \cdot 4 H c. Then the component of μc¨+4Hc−2Λc\mu \ddot c + 4 H c - 2 \Lambda c along cc is −μθ˙2+c⋅4Hc−2Λ=0-\mu \dot\theta^2 + c \cdot 4Hc - 2\Lambda = 0, the component along c⊥c_\perp is μθ¨+2Δsin⁡2θ=0\mu \ddot \theta + 2\Delta \sin 2\theta = 0, and there is no component outside PP. So this cc solves the constrained equations, and by uniqueness of solutions of the constrained system it is the solution. For small θ\theta, sin⁡2θ=2θ+O(θ3)\sin 2\theta = 2\theta + O(\theta^3), which gives θ¨=−(4Δ/μ)θ\ddot\theta = -(4\Delta / \mu)\theta and the frequency. □\square

For the dimer of the page with U=0U = 0 at r=1r = 1, H=H0H = H_0 is 2×22 \times 2 with eigenvalues ∓1\mp 1, so every motion lies in PP, Δ=2\Delta = 2 and ω=22/μ\omega = 2\sqrt{2 / \mu}. With ϕ=2θ\phi = 2\theta the equation is that of a pendulum, ϕ¨=−(4Δ/μ)sin⁡ϕ\ddot \phi = -(4\Delta/\mu) \sin\phi, whose frequency at amplitude ϕ0\phi_0 is lower by the factor 1−ϕ02/16+O(ϕ04)1 - \phi_0^2 / 16 + O(\phi_0^4). The start at θ0=0.05\theta_0 = 0.05 has ϕ0=0.1\phi_0 = 0.1, a relative shift of 6×10−46 \times 10^{-4}, which accounts for the measured 28.26828.268 against 28.28428.284.

Remark (adiabaticity). Claim 3 shows that the orbital oscillates about the ground state at a frequency that grows like μ−1/2\mu^{-1/2}. When this frequency is far above the frequencies of the nuclei, little energy flows between the two, and the orbital stays close to the instantaneous ground state. This adiabatic argument (Car and Parrinello 1985; Pastore, Smargiassi and Buda 1991) explains why the error of CPMD shrinks with μ\mu. It is not a theorem proved here; the deviations on the page, which grow about linearly in μ\mu, are measurements.

Complexity

Each step costs one evaluation of EE, ∇cE\nabla_c E and ∂E/∂X\partial E / \partial X, of cost CC, plus the orthonormality constraint. For plane-wave DFT with many orbitals, the orthonormalization costs O(N3)O(N^3) per step, the same order as one SCF iteration. Over TT steps the time is O(TC)O(T C), with no SCF loop. The time step must resolve the fastest orbital frequency ωmax⁡∼Ecut/μ\omega_{\max} \sim \sqrt{E_{\text{cut}} / \mu} for a plane-wave cutoff EcutE_{\text{cut}}, so it is typically 5 to 10 times smaller than for BOMD. Whether CPMD or BOMD is faster depends on the system: CPMD saves the SCF iterations but needs more steps.

Properties

  • No SCF at each step, and so no SCF tolerance and no drift from an incomplete SCF.
  • A conserved energy, EconsE_{\text{cons}}, for the extended system; velocity Verlet with RATTLE is symplectic and time reversible for it.
  • Close to the BO surface, not on it. The orbitals lag the ground state and add an error that grows with μ\mu; the nuclei also feel a drag, as if their mass were larger.
  • Needs a gap. The adiabatic separation needs the lowest orbital frequency 2Δ/μ2\sqrt{\Delta / \mu} to stay well above the nuclear frequencies; in metals, with no gap, the orbitals heat up.
  • Small time steps, set by μ\mu and the plane-wave cutoff.

Variants and improvements

  • Thermostats on the orbitals. A Nosé-Hoover thermostat on the orbital degrees of freedom keeps the fictitious kinetic energy low, which is needed for metals and small gaps.
  • Mass preconditioning. Different fictitious masses for different plane waves reduce the highest frequency and allow larger steps.
  • Extended Lagrangian BOMD (Niklasson 2008) borrows the idea of an auxiliary electronic variable but uses it as the initial guess of an SCF.
  • Car-Parrinello QM/MM. Only a small region is treated by CPMD; see the QM/MM method.

When to use it

Use CPMD for insulators and semiconductors with a clear gap, large systems where one SCF solve per step is expensive, and simulations where strict energy conservation matters. For metals, for systems with small gaps, or when large time steps are wanted, BOMD with a good initial guess is usually simpler. Check adiabaticity by monitoring the fictitious kinetic energy: it should stay small and not grow.

Pitfalls

  • Fictitious mass too large. The orbitals lag the nuclei, the forces are wrong, and energy flows from the nuclei into the orbitals; the nuclear temperature drops.
  • Not starting at the ground state. The orbitals must be minimized before the run, or they carry a large fictitious kinetic energy from the start.
  • Small gaps and metals. The orbital and nuclear frequencies overlap and adiabaticity is lost.
  • Time step too large for the orbital frequency; the run becomes unstable.
  • Mass renormalization. The nuclei behave as if slightly heavier, which changes vibrational frequencies by an amount that grows with μ\mu.
  • Toy model. The code here is a toy with one orbital; it shows the structure of CPMD, not real chemistry.

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.

car_parrinello_molecular_dynamics.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/car-parrinello-molecular-dynamics/. The authors are listed in prov/PQJARX.jsonl.
"""Car-Parrinello molecular dynamics on a toy electronic model.

This is a toy, not a quantum chemistry code. It keeps the structure of CPMD:
the orbital coefficients c are dynamic variables with a fictitious mass mu,
and nuclei and orbital move together under the extended Lagrangian

    L = sum_k M_k v_k^2 / 2 + (mu / 2) |dc/dt|^2 - E(x, c) + Lambda (|c|^2 - 1).

There is no self-consistent solve during the run. The constraint |c| = 1 is
kept by a SHAKE step on the positions and a RATTLE step on the velocities,
and the conserved quantity is

    E_cons = sum_k M_k v_k^2 / 2 + (mu / 2) |dc/dt|^2 + E(x, c).

The model is the one of the BOMD page: N atoms on a line, one orbital per
atom, two electrons in the orbital c,

    E(x, c) = 2 c^T H0(x) c + U sum_i c_i^4 + Phi(x),
    H0_ij = -t0 exp(-a (r_ij - d0)) (i != j),  Phi = sum_{i<j} A exp(-b (r_ij - d0)).
"""

import math
from typing import Sequence


def jacobi_eigen(a: Sequence[Sequence[float]], tol: float = 1e-14,
                 max_sweeps: int = 100) -> tuple[list[float], list[list[float]]]:
    """Eigenvalues (ascending) and eigenvectors (as columns) of a symmetric matrix."""
    n = len(a)
    m = [list(row) for row in a]
    v = [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
    for _ in range(max_sweeps):
        if sum(m[i][j] ** 2 for i in range(n) for j in range(n) if i != j) < tol * tol:
            break
        for p in range(n - 1):
            for q in range(p + 1, n):
                if abs(m[p][q]) < 1e-300:
                    continue
                theta = (m[q][q] - m[p][p]) / (2.0 * m[p][q])
                t = math.copysign(1.0, theta) / (abs(theta) + math.sqrt(theta * theta + 1.0))
                c = 1.0 / math.sqrt(t * t + 1.0)
                s = t * c
                for k in range(n):
                    m[k][p], m[k][q] = c * m[k][p] - s * m[k][q], s * m[k][p] + c * m[k][q]
                for k in range(n):
                    m[p][k], m[q][k] = c * m[p][k] - s * m[q][k], s * m[p][k] + c * m[q][k]
                for k in range(n):
                    v[k][p], v[k][q] = c * v[k][p] - s * v[k][q], s * v[k][p] + c * v[k][q]
    order = sorted(range(n), key=lambda i: m[i][i])
    return [m[i][i] for i in order], [[v[k][i] for i in order] for k in range(n)]


class ToyModel:
    def __init__(self, t0=1.0, a=1.0, d0=1.0, big_a=1.0, b=2.0, u=1.0):
        self.t0, self.a, self.d0, self.big_a, self.b, self.u = t0, a, d0, big_a, b, u

    def hopping(self, x):
        n = len(x)
        h = [[0.0] * n for _ in range(n)]
        for i in range(n):
            for j in range(i + 1, n):
                h[i][j] = h[j][i] = -self.t0 * math.exp(-self.a * (abs(x[i] - x[j]) - self.d0))
        return h

    def energy(self, x, c) -> float:
        n = len(x)
        h0 = self.hopping(x)
        e = 2.0 * sum(c[i] * h0[i][j] * c[j] for i in range(n) for j in range(n))
        e += self.u * sum(ci ** 4 for ci in c)
        return e + sum(self.big_a * math.exp(-self.b * (abs(x[i] - x[j]) - self.d0))
                       for i in range(n) for j in range(i + 1, n))

    def orbital_force(self, x, c) -> list[float]:
        """-dE/dc = -4 (H0 + U diag(c^2)) c."""
        h0 = self.hopping(x)
        n = len(c)
        return [-4.0 * (sum(h0[i][j] * c[j] for j in range(n)) + self.u * c[i] ** 3) for i in range(n)]

    def nuclear_force(self, x, c) -> list[float]:
        """-dE/dx_k at fixed c."""
        n = len(x)
        f = [0.0] * n
        for i in range(n):
            for j in range(i + 1, n):
                r = abs(x[i] - x[j])
                sgn = 1.0 if x[i] > x[j] else -1.0
                dt = self.a * self.t0 * math.exp(-self.a * (r - self.d0))
                dphi = -self.b * self.big_a * math.exp(-self.b * (r - self.d0))
                de_dr = 4.0 * c[i] * c[j] * dt + dphi
                f[i] -= de_dr * sgn
                f[j] += de_dr * sgn
        return f

    def ground_state(self, x, dens=None, tol=1e-12, max_iter=500, mix=0.5):
        """Self-consistent lowest orbital, used only for the start and for comparison."""
        n = len(x)
        h0 = self.hopping(x)
        if dens is None:
            dens = [1.0 / n] * n
        for _ in range(max_iter):
            h = [[h0[i][j] + (self.u * dens[i] if i == j else 0.0) for j in range(n)] for i in range(n)]
            _, vecs = jacobi_eigen(h)
            c = [vecs[k][0] for k in range(n)]
            new = [ci * ci for ci in c]
            res = max(abs(p - q) for p, q in zip(new, dens))
            dens = [(1 - mix) * p + mix * q for p, q in zip(dens, new)]
            if res < tol:
                break
        return c


def cpmd(model: ToyModel, x: list[float], v: list[float], m: Sequence[float], c: list[float],
         cdot: list[float], mu: float, h: float, steps: int, fixed_nuclei: bool = False):
    """Velocity Verlet for nuclei and orbital, with SHAKE and RATTLE for |c| = 1.

    Returns a list of (x, c, nuclear KE, fictitious KE, E_cons) after each step,
    starting with the initial state.
    """
    def record():
        kn = 0.0 if fixed_nuclei else 0.5 * sum(mi * vi * vi for mi, vi in zip(m, v))
        ke = 0.5 * mu * sum(d * d for d in cdot)
        return list(x), list(c), kn, ke, kn + ke + model.energy(x, c)

    fx, fc = model.nuclear_force(x, c), model.orbital_force(x, c)           # @line L1
    out = [record()]
    for _ in range(steps):                                                  # @line L2
        if not fixed_nuclei:
            v = [vi + 0.5 * h * fi / mi for vi, fi, mi in zip(v, fx, m)]    # @line L3
            x = [xi + h * vi for xi, vi in zip(x, v)]                       # @line L3
        cdot = [d + 0.5 * h * f / mu for d, f in zip(cdot, fc)]             # @line L4
        d = [ci + h * di for ci, di in zip(c, cdot)]                        # @line L5
        dc = sum(p * q for p, q in zip(d, c))                               # SHAKE: |d + lam c| = 1
        lam = -dc + math.sqrt(dc * dc - sum(p * p for p in d) + 1.0)        # @line L5
        cdot = [di + lam * ci / h for di, ci in zip(cdot, c)]
        c = [p + lam * q for p, q in zip(d, c)]                             # @line L5
        fx, fc = model.nuclear_force(x, c), model.orbital_force(x, c)       # @line L6
        if not fixed_nuclei:
            v = [vi + 0.5 * h * fi / mi for vi, fi, mi in zip(v, fx, m)]    # @line L7
        cdot = [di + 0.5 * h * f / mu for di, f in zip(cdot, fc)]           # @line L7
        proj = sum(p * q for p, q in zip(c, cdot))                          # RATTLE: c . cdot = 0
        cdot = [di - proj * ci for di, ci in zip(cdot, c)]                  # @line L8
        out.append(record())
    return out                                                              # @line L9
test_car_parrinello_molecular_dynamics.py 81 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/car-parrinello-molecular-dynamics/. The authors are listed in prov/PQJARX.jsonl.
import math

import pytest

from car_parrinello_molecular_dynamics import ToyModel, cpmd

X0 = [0.0, 1.1, 2.0, 3.2]
V0 = [0.3, -0.2, 0.1, -0.2]
MASSES = [1.0] * 4


def bo_reference(model, h, steps):
    """Born-Oppenheimer positions with a tight SCF at every step, same integrator for the nuclei."""
    x, v = list(X0), list(V0)
    c = model.ground_state(x)
    f = model.nuclear_force(x, c)
    traj = [list(x)]
    for _ in range(steps):
        v = [vi + 0.5 * h * fi for vi, fi in zip(v, f)]
        x = [xi + h * vi for xi, vi in zip(x, v)]
        c = model.ground_state(x, [q * q for q in c])
        f = model.nuclear_force(x, c)
        v = [vi + 0.5 * h * fi for vi, fi in zip(v, f)]
        traj.append(list(x))
    return traj


def run(mu, h, steps):
    model = ToyModel(u=1.0)
    c = model.ground_state(X0)
    return model, cpmd(model, list(X0), list(V0), MASSES, c, [0.0] * 4, mu, h, steps)


def test_constraint_is_kept_to_rounding():
    _, out = run(0.01, 0.004, 500)
    assert max(abs(sum(q * q for q in o[1]) - 1.0) for o in out) < 1e-12


def test_ground_state_with_fixed_nuclei_does_not_move():
    model = ToyModel(u=1.0)
    c = model.ground_state(X0)
    out = cpmd(model, list(X0), [0.0] * 4, MASSES, list(c), [0.0] * 4, 0.01, 0.004, 200, fixed_nuclei=True)
    assert max(abs(p - q) for p, q in zip(out[-1][1], c)) < 1e-9
    assert out[-1][3] < 1e-15


def test_orbital_frequency_of_two_level_dimer():
    # U = 0 dimer at r = 1: gap 2, so omega_e = 2 sqrt(gap / mu).
    model = ToyModel(u=0.0)
    s = 1 / math.sqrt(2)
    th = 0.05
    c = [s * (math.cos(th) + math.sin(th)), s * (math.cos(th) - math.sin(th))]
    mu, h = 0.01, 0.002
    out = cpmd(model, [0.0, 1.0], [0.0, 0.0], [1.0, 1.0], c, [0.0, 0.0], mu, h, 3000, fixed_nuclei=True)
    proj = [s * (o[1][0] - o[1][1]) for o in out]
    down = [i for i in range(1, len(proj)) if proj[i - 1] > 0 >= proj[i]]
    period = (down[-1] - down[0]) * h / (len(down) - 1)
    assert 2 * math.pi / period == pytest.approx(2 * math.sqrt(2 / mu), rel=0.01)


def test_extended_energy_is_conserved():
    _, out = run(0.01, 0.004, 1250)
    e = [o[4] for o in out]
    assert max(e) - min(e) < 1e-5


def test_small_mass_tracks_born_oppenheimer_and_large_mass_does_not():
    h, steps = 0.004, 1250  # time 5
    model, small = run(0.01, h, steps)
    _, large = run(0.2, h, steps)
    ref = bo_reference(model, h, steps)
    dev_small = max(max(abs(a - b) for a, b in zip(r, o[0])) for r, o in zip(ref, small))
    dev_large = max(max(abs(a - b) for a, b in zip(r, o[0])) for r, o in zip(ref, large))
    assert dev_small < 0.01
    assert dev_large > 5 * dev_small
    # The fictitious kinetic energy stays a small part of the nuclear kinetic energy.
    k_fict = max(o[3] for o in small)
    k_nuc = sum(o[2] for o in small) / len(small)
    assert k_fict < 0.01 * k_nuc

History

Car and Parrinello (1985) introduced the method, which made ab initio molecular dynamics with density functional theory practical for condensed matter and started a large field. Pastore, Smargiassi and Buda (1991) analysed why the fictitious electron dynamics stays close to the ground state, in terms of the gap and the fictitious mass. Later, better SCF methods made Born-Oppenheimer dynamics competitive again, and Marx and Hutter (2009) treat both methods in one book.

References

  1. Roberto Car and Michele Parrinello, Unified approach for molecular dynamics and density-functional theory, Physical Review Letters 55, 2471-2474, 1985, the extended Lagrangian with fictitious orbital dynamics and the orthonormality constraints
  2. Giorgio Pastore, Enrico Smargiassi and Francesco Buda, Theory of ab initio molecular-dynamics calculations, Physical Review A 44(10), 1991, 6334-6347, the analysis of adiabatic separation between the fictitious electron dynamics and the nuclei, and the role of the gap and the fictitious mass
  3. Dominik Marx and Jürg Hutter, Ab Initio Molecular Dynamics, Basic Theory and Advanced Methods, Cambridge University Press, 2009, the chapter on the theory of ab initio molecular dynamics, the sections on Car-Parrinello molecular dynamics, the fictitious mass and adiabaticity

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