Algorithm Search⌘K

Algorithmadvanced

Born-Oppenheimer molecular dynamics

Also called ab initio molecular dynamics.

Moves the nuclei classically on forces from an electronic structure calculation solved to self-consistency at every step.

Time
O(T I C) worst
Space
O(C) extra
Where
C = the cost of one SCF iteration; I = the number of SCF iterations per step; T = the number of time steps
Properties
deterministiciterativenot randomized
Origin
Claude Leforestier, 1978

Born-Oppenheimer molecular dynamics (BOMD) moves the nuclei of a molecule or a solid by Newton's laws on forces computed from quantum mechanics. At each time step the electronic structure problem, usually Kohn-Sham density functional theory or Hartree-Fock, is solved by a self-consistent field (SCF) iteration for the current nuclear positions; the forces then follow from the Hellmann-Feynman theorem, and the nuclei move by velocity Verlet. The name comes from the Born-Oppenheimer approximation: the electrons are light and fast, so they stay in their ground state for the current nuclei, and the nuclei move on the ground-state energy surface. Compared with molecular dynamics on an interatomic potential, BOMD needs no fitted force field and can break and form bonds, at a cost thousands of times higher per step. Car-Parrinello molecular dynamics avoids the SCF at each step by moving the orbitals too. The code on this page uses a toy electronic model with one orbital per atom, not a real quantum chemistry method.

In plain words

In a molecule, the electrons are much lighter than the nuclei and move much faster. For every arrangement of the nuclei, they settle almost at once into their lowest energy state.

BOMD uses this. At each small time step it holds the nuclei still, solves for the electrons, and computes the forces that the electrons and the other nuclei put on each nucleus. Then it moves the nuclei a little according to those forces, and repeats.

The electrons are solved by a repeated guess-and-correct loop. If that loop is stopped too early, the forces are slightly wrong, and the total energy slowly drifts.

The problem

The input is the nuclear positions XX, velocities VV and masses MM, a time step hh, and an electronic structure method: for given XX, an energy E(X,c)E(X, c) of the electronic state cc (orbitals or density). The Born-Oppenheimer energy is

EBO(X)=min⁡cE(X,c)E_{\text{BO}}(X) = \min_c E(X, c)

under the constraints on cc, such as orthonormal orbitals. The task is to integrate

MkX¨k=−∂EBO∂Xk.M_k \ddot X_k = -\frac{\partial E_{\text{BO}}}{\partial X_k}.

In this page's toy model, NN atoms sit on a line with one orbital each, the hopping t(r)=−t0e−a(r−d0)t(r) = -t_0 e^{-a(r - d_0)} forms the matrix H0(X)H_0(X), two electrons fill the lowest orbital cc with ∣c∣=1|c| = 1, and

E(X,c)=2cTH0(X)c+U∑ici4+∑i<jAe−b(rij−d0).E(X, c) = 2 c^T H_0(X) c + U \sum_i c_i^4 + \sum_{i < j} A e^{-b(r_{ij} - d_0)}.

The quartic term is a mean-field on-site repulsion, which makes the problem self-consistent: cc is the lowest eigenvector of H(c)=H0+U diag(ci2)H(c) = H_0 + U\,\mathrm{diag}(c_i^2) (Claim 1 of the proof).

The algorithm

  1. BOMD(X, V, M, h, steps)
  2. 1c ← SCF(X) ▷ electronic ground state at the start
  3. 2F ← -dE/dX at fixed c ▷ Hellmann-Feynman forces
  4. 3for n ← 1 to steps do
  5. 4V ← V + (h / 2) F / M
  6. 5X ← X + h V
  7. 6c ← SCF(X), started from the previous density
  8. 7F ← -dE/dX at fixed c
  9. 8V ← V + (h / 2) F / M
  10. 9return the trajectory and the total energies E_BO(X) + (1/2) V^T M V

Line L6 is the costly part. The SCF loop builds HH from the current density, takes its lowest eigenvector (here by the Jacobi eigenvalue algorithm), mixes the new density with the old one, and repeats until the density changes by less than a tolerance. Starting from the previous step's density saves iterations. Line L7 uses the Hellmann-Feynman theorem: at a self-consistent cc, the derivative of EBOE_{\text{BO}} is the partial derivative of EE at fixed cc, so no derivative of the orbitals is needed. Lines L4, L5 and L8 are velocity Verlet.

Example

A dimer with U=0U = 0. With t0=a=d0=A=1t_0 = a = d_0 = A = 1 and b=2b = 2, the lowest orbital of two atoms has energy −∣t(r)∣-|t(r)|, so EBO(r)=−2e−(r−1)+e−2(r−1)E_{\text{BO}}(r) = -2e^{-(r - 1)} + e^{-2(r - 1)}, a Morse curve with minimum −1-1 at r=1r = 1 and curvature E′′=2E'' = 2. The SCF reproduces this to rounding.

A chain of four atoms with U=1U = 1. At X=(0,1.1,2.0,3.2)X = (0, 1.1, 2.0, 3.2) the SCF converges in 25 iterations with mixing 0.5 to EBO=−0.589106E_{\text{BO}} = -0.589106. The Hellmann-Feynman forces agree with centred finite differences of EBOE_{\text{BO}} to 2×10−102 \times 10^{-10}. After one SCF iteration only, the density residual is 0.11 and the forces are visibly wrong.

Energy conservation. Start with V=(0.3,−0.2,0.1,−0.2)V = (0.3, -0.2, 0.1, -0.2), unit masses, h=0.05h = 0.05, 1000 steps:

SCF total energy drift note
tolerance 10−1010^{-10} 2.35×10−62.35 \times 10^{-6} the energy oscillates with spread 5.6×10−45.6 \times 10^{-4}
tolerance 10−310^{-3} 3.0×10−33.0 \times 10^{-3}
one iteration per step 0.035

With the tight SCF the energy oscillates but does not drift, as expected of a symplectic integrator on an exact potential. The spread over a time of 50 was 1.38×10−31.38 \times 10^{-3} at h=0.1h = 0.1, 5.65×10−45.65 \times 10^{-4} at h=0.05h = 0.05 and 1.39×10−41.39 \times 10^{-4} at h=0.025h = 0.025: it falls by about 4 when hh halves, so it is second order. With a loose SCF the forces are not the gradient of any energy, and the energy drifts.

Correctness

The proof in proofs/correctness.md shows, for the toy model:

  1. SCF fixed points are stationary points. On the sphere ∣c∣=1|c| = 1, EE is stationary in cc exactly when cc is an eigenvector of H(c)=H0+U diag(ci2)H(c) = H_0 + U\,\mathrm{diag}(c_i^2).
  2. Hellmann-Feynman forces. If c(X)c(X) is a stationary point that depends smoothly on XX, then dEBO/dXk=∂E/∂XkdE_{\text{BO}}/dX_k = \partial E / \partial X_k at fixed cc, which is the formula of the code.
  3. Energy errors are second order, force errors first order. If cc is off the stationary point by δ\delta, the energy is off by O(∣δ∣2)O(|\delta|^2) but the force by O(∣δ∣)O(|\delta|).
  4. The dynamics. With exact forces, EBO+12VTMVE_{\text{BO}} + \frac12 V^T M V is conserved by the exact flow, and velocity Verlet is a symplectic, time-reversible, second-order method for it.
  5. The dimer. For U=0U = 0 and two atoms, EBO(r)=−2t0e−a(r−d0)+Ae−b(r−d0)E_{\text{BO}}(r) = -2 t_0 e^{-a(r - d_0)} + A e^{-b(r - d_0)}.
Proof: Self-consistency, the Hellmann-Feynman forces and energy conservation for the toy modelfull

The toy model has NN atoms at positions x1,…,xNx_1, \dots, x_N on a line, distances rij=∣xi−xj∣>0r_{ij} = |x_i - x_j| > 0, the symmetric matrix H0(X)H_0(X) with (H0)ii=0(H_0)_{ii} = 0 and (H0)ij=t(rij)=−t0e−a(rij−d0)(H_0)_{ij} = t(r_{ij}) = -t_0 e^{-a(r_{ij} - d_0)}, and the energy

E(X,c)=2cTH0(X)c+U∑ici4+Φ(X),Φ(X)=∑i<jAe−b(rij−d0),E(X, c) = 2 c^T H_0(X) c + U \sum_i c_i^4 + \Phi(X), \qquad \Phi(X) = \sum_{i < j} A e^{-b(r_{ij} - d_0)},

for cc on the unit sphere S={c∈RN:∣c∣=1}S = \{c \in \mathbb R^N : |c| = 1\}. Let H(c)=H0+U diag(c12,…,cN2)H(c) = H_0 + U\,\mathrm{diag}(c_1^2, \dots, c_N^2).

Claim 1 (SCF fixed points are stationary points). For fixed XX, c∈Sc \in S is a stationary point of E(X,⋅)E(X, \cdot) on SS if and only if H(c) c=ϵ cH(c)\, c = \epsilon\, c for some ϵ\epsilon. In particular, a fixed point of the SCF map (take an eigenvector of H(c)H(c)) is a stationary point.

Proof. ∇cE=4H0c+4U(c13,…,cN3)T=4H(c) c\nabla_c E = 4 H_0 c + 4 U (c_1^3, \dots, c_N^3)^T = 4 H(c)\, c. By the Lagrange multiplier rule, cc is stationary on SS if and only if ∇cE=2μc\nabla_c E = 2\mu c for some μ\mu, that is H(c) c=(μ/2) cH(c)\, c = (\mu / 2)\, c. □\square

E(X,⋅)E(X, \cdot) is continuous on the compact set SS, so it has a minimizer, which is a stationary point by Claim 1. The code takes the lowest eigenvector of HH at each SCF iteration; when the iteration converges, its limit is a stationary point. This note does not prove that it is the global minimizer or that the iteration converges; the iteration counts on the page are measurements.

Claim 2 (Hellmann-Feynman forces). Suppose that near XX there is a continuously differentiable map X↦c(X)∈SX \mapsto c(X) \in S of stationary points (for example, by the implicit function theorem, when the stationary point is nondegenerate on SS). Then for EBO(X)=E(X,c(X))E_{\text{BO}}(X) = E(X, c(X)),

∂EBO∂xk=∂E∂xk(X,c)=2cT∂H0∂xkc+∂Φ∂xk.\frac{\partial E_{\text{BO}}}{\partial x_k} = \frac{\partial E}{\partial x_k}(X, c) = 2 c^T \frac{\partial H_0}{\partial x_k} c + \frac{\partial \Phi}{\partial x_k}.

For the toy model this is

∂EBO∂xk=∑j≠ksgn(xk−xj)(4ckcj at0e−a(rkj−d0)−bAe−b(rkj−d0)),\frac{\partial E_{\text{BO}}}{\partial x_k} = \sum_{j \ne k} \mathrm{sgn}(x_k - x_j) \bigl(4 c_k c_j\, a t_0 e^{-a(r_{kj} - d_0)} - b A e^{-b(r_{kj} - d_0)}\bigr),

which is minus the force computed by the code.

Proof. By the chain rule, ∂xkEBO=∂xkE+∇cE⋅∂xkc\partial_{x_k} E_{\text{BO}} = \partial_{x_k} E + \nabla_c E \cdot \partial_{x_k} c. By Claim 1, ∇cE=2μc\nabla_c E = 2 \mu c. Since ∣c(X)∣2=1|c(X)|^2 = 1 for all XX, differentiating gives c⋅∂xkc=0c \cdot \partial_{x_k} c = 0. So the second term is 0. The UU term does not depend on XX. In 2cTH0c=2∑i≠jcicjt(rij)2 c^T H_0 c = 2 \sum_{i \ne j} c_i c_j t(r_{ij}), each pair {i,j}\{i, j\} appears twice, so it contributes 4cicjt(rij)4 c_i c_j t(r_{ij}). With t′(r)=at0e−a(r−d0)t'(r) = a t_0 e^{-a(r - d_0)}, ∂rkj/∂xk=sgn(xk−xj)\partial r_{kj} / \partial x_k = \mathrm{sgn}(x_k - x_j) and ddrAe−b(r−d0)=−bAe−b(r−d0)\frac{d}{dr} A e^{-b(r - d_0)} = -b A e^{-b(r - d_0)}, the formula follows. □\square

The sign of cc is not fixed by the eigensolver, but EE and the force depend only on products cicjc_i c_j, which do not change under c→−cc \to -c.

Claim 3 (energy errors are second order, force errors first order). Let c∗c^* be a stationary point and c∈Sc \in S with ∣c−c∗∣=δ|c - c^*| = \delta. Then E(X,c)−E(X,c∗)=O(δ2)E(X, c) - E(X, c^*) = O(\delta^2) and ∂xkE(X,c)−∂xkE(X,c∗)=O(δ)\partial_{x_k} E(X, c) - \partial_{x_k} E(X, c^*) = O(\delta), with constants that depend on XX only.

Proof. Let L(c)=E(X,c)−μ(∣c∣2−1)\mathcal L(c) = E(X, c) - \mu (|c|^2 - 1) with the multiplier μ\mu of c∗c^*. Then ∇L(c∗)=0\nabla \mathcal L(c^*) = 0 and L\mathcal L is a polynomial, so Taylor's theorem gives L(c)−L(c∗)=O(δ2)\mathcal L(c) - \mathcal L(c^*) = O(\delta^2). On SS, L=E\mathcal L = E. The partial derivative ∂xkE(X,c)\partial_{x_k} E(X, c) is a quadratic polynomial in cc, hence Lipschitz on SS, which gives the second bound. □\square

This is why an incomplete SCF gives a good energy but forces that are not its gradient: the force error is first order in the SCF error, and in general it does not vanish to that order. Such forces do not come from any potential, so the total energy is no longer conserved, which is the drift measured on the page.

Claim 4 (the dynamics). Let X(t)X(t) solve Mkx¨k=−∂EBO/∂xkM_k \ddot x_k = -\partial E_{\text{BO}} / \partial x_k with EBOE_{\text{BO}} continuously differentiable. Then H=12∑kMkx˙k2+EBO(X)\mathcal H = \frac12 \sum_k M_k \dot x_k^2 + E_{\text{BO}}(X) is constant in time.

Proof. dH/dt=∑kMkx˙kx¨k+∑k∂xkEBO x˙k=∑kx˙k(Mkx¨k+∂xkEBO)=0d\mathcal H / dt = \sum_k M_k \dot x_k \ddot x_k + \sum_k \partial_{x_k} E_{\text{BO}}\, \dot x_k = \sum_k \dot x_k (M_k \ddot x_k + \partial_{x_k} E_{\text{BO}}) = 0. □\square

Lines L4, L5 and L8 are velocity Verlet for this system, which is symplectic, time reversible and second order (see Verlet integration and symplectic integrators). For a smooth potential and a small enough step, its energy error stays bounded and of order h2h^2 over long times, through the shadow Hamiltonian. This matches the measured spread on the page, which falls by about 4 when hh halves. The guarantee needs exact forces of one fixed potential. With the SCF started from the previous step and stopped at a tolerance, the force map depends on the history, the method is no longer exactly symplectic or reversible, and the energy can drift.

Claim 5 (the dimer). For N=2N = 2 and U=0U = 0, EBO(r)=−2t0e−a(r−d0)+Ae−b(r−d0)E_{\text{BO}}(r) = -2 t_0 e^{-a(r - d_0)} + A e^{-b(r - d_0)}. With t0=a=d0=A=1t_0 = a = d_0 = A = 1 and b=2b = 2, the minimum is EBO(1)=−1E_{\text{BO}}(1) = -1 and EBO′′(1)=2E_{\text{BO}}''(1) = 2.

Proof. H=H0=(0tt0)H = H_0 = \begin{pmatrix} 0 & t \\ t & 0 \end{pmatrix} has eigenvalues ±t\pm t, and the minimum of 2cTH0c2 c^T H_0 c on SS is twice the lowest eigenvalue, −2∣t(r)∣=−2t0e−a(r−d0)-2|t(r)| = -2 t_0 e^{-a(r - d_0)}. Add Φ\Phi. With the given constants, E(r)=−2e−(r−1)+e−2(r−1)E(r) = -2 e^{-(r - 1)} + e^{-2(r - 1)}, E′(r)=2e−(r−1)−2e−2(r−1)E'(r) = 2 e^{-(r - 1)} - 2 e^{-2(r - 1)} vanishes at r=1r = 1, and E′′(1)=−2+4=2E''(1) = -2 + 4 = 2. □\square

Complexity

Each step costs II SCF iterations of cost CC each plus the forces. For the toy model one iteration is a dense eigenproblem, C=O(N3)C = O(N^3). For Kohn-Sham DFT with plane waves, CC is dominated by fast Fourier transforms and by orthogonalization, which grows like O(N3)O(N^3) in the number of electrons for large systems. The total is O(TIC)O(T I C), and good initial guesses reduce II to about 5 to 15 per step in practice. The extra space is that of one electronic structure calculation.

Properties

  • Exact on the BO surface in the limit of a converged SCF: no force field and no fitting.
  • Bonds can break and form, since the energy comes from the electrons.
  • Symplectic in the nuclei when the SCF is fully converged; then there is no long-time drift.
  • Not exactly time reversible in practice: the SCF starts from the previous step's density, which breaks the symmetry between forward and backward steps and causes drift for loose tolerances (Niklasson 2008).
  • Large time steps. The time step is set by the nuclear motion, about 0.5 to 1 fs, not by the electrons.
  • Ground state only. It cannot describe processes where several electronic states mix.

Variants and improvements

  • Extended Lagrangian BOMD (Niklasson 2008). An auxiliary density moves with a time-reversible integrator and serves as the SCF initial guess, which removes the drift even with few SCF iterations.
  • Extrapolation of the initial guess from several previous steps.
  • Car-Parrinello molecular dynamics. The orbitals move as fictitious classical variables, and no SCF is solved at each step.
  • QM/MM. Only a small region is treated by BOMD and the rest by a force field; see the QM/MM method.
  • Machine-learned potentials. BOMD data are used to fit potentials such as the Behler-Parrinello potential, which then run much faster.

When to use it

Use BOMD when the chemistry matters: bond breaking, proton transfer, reactions at surfaces, liquids where polarization and charge transfer are important, or any system with no reliable force field. It is the standard method for ab initio molecular dynamics with modern codes. For long or large simulations, use it to generate training data for a machine-learned potential, or restrict it to a QM region.

Pitfalls

  • Loose SCF. Forces are not the gradient of the energy and the energy drifts; tighten the tolerance or use extended Lagrangian BOMD.
  • Pulay forces. With basis functions that move with the atoms, as with Gaussian orbitals, the force has extra terms beyond Hellmann-Feynman; plane waves do not have them.
  • SCF failure. Near level crossings or for metals, the SCF can converge slowly or to the wrong state; use smearing or better mixing.
  • Small systems and short times. The cost limits BOMD to hundreds of atoms and tens of picoseconds; statistics are poor.
  • Toy model. The code here is a toy with one orbital per atom; it shows the structure of BOMD, 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.

born_oppenheimer_molecular_dynamics.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/born-oppenheimer-molecular-dynamics/. The authors are listed in prov/KR4Y5Q.jsonl.
"""Born-Oppenheimer molecular dynamics on a toy electronic model.

This is a toy, not a quantum chemistry code. It keeps the structure of BOMD:
at every time step the electrons are solved self-consistently for the
current nuclear positions, the forces come from the Hellmann-Feynman
theorem, and the nuclei move by velocity Verlet.

The model: N atoms on a line, one orbital per atom, two electrons (one spin
pair) in the lowest orbital c, with |c| = 1.

    H0_ij = t(r_ij) = -t0 exp(-a (r_ij - d0))   for i != j, H0_ii = 0,
    E_el(c) = 2 c^T H0 c + U sum_i c_i^4,       (a mean-field on-site repulsion)
    Phi = sum_{i<j} A exp(-b (r_ij - d0)),       (repulsion of the cores)
    E = E_el(c) + Phi.

E_el is stationary on |c| = 1 when c is the lowest eigenvector of the
self-consistent matrix H(c) = H0 + U diag(c_i^2). At that point
dE/dx_k = 2 c^T (dH0/dx_k) c + dPhi/dx_k, with no term from dc/dx_k.
"""

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):
        off = sum(m[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
        if off < 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):
                    mkp, mkq = m[k][p], m[k][q]
                    m[k][p], m[k][q] = c * mkp - s * mkq, s * mkp + c * mkq
                for k in range(n):
                    mpk, mqk = m[p][k], m[q][k]
                    m[p][k], m[q][k] = c * mpk - s * mqk, s * mpk + c * mqk
                for k in range(n):
                    vkp, vkq = v[k][p], v[k][q]
                    v[k][p], v[k][q] = c * vkp - s * vkq, s * vkp + c * vkq
    order = sorted(range(n), key=lambda i: m[i][i])
    vals = [m[i][i] for i in order]
    vecs = [[v[k][i] for i in order] for k in range(n)]
    return vals, vecs


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: Sequence[float]) -> list[list[float]]:
        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 repulsion(self, x: Sequence[float]) -> float:
        n = len(x)
        return 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 electronic_energy(self, h0, c) -> float:
        n = len(c)
        e = 2.0 * sum(c[i] * h0[i][j] * c[j] for i in range(n) for j in range(n))
        return e + self.u * sum(ci ** 4 for ci in c)

    def scf(self, x, dens=None, tol=1e-10, max_iter=200, mix=0.5):
        """Self-consistent lowest orbital. Returns (c, E, residual, iterations)."""
        h0 = self.hopping(x)
        n = len(x)
        if dens is None:
            dens = [1.0 / n] * n
        for it in range(1, max_iter + 1):
            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, self.electronic_energy(h0, c) + self.repulsion(x), res, it

    def forces(self, x, c) -> list[float]:
        """Hellmann-Feynman forces -dE/dx_k for the orbital 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))        # dt/dr
                dphi = -self.b * self.big_a * math.exp(-self.b * (r - self.d0))  # dPhi/dr
                de_dr = 2.0 * 2.0 * c[i] * c[j] * dt + dphi                     # both (i,j) and (j,i)
                f[i] -= de_dr * sgn
                f[j] += de_dr * sgn
        return f


def bomd(model: ToyModel, x: list[float], v: list[float], m: Sequence[float], h: float,
         steps: int, tol: float = 1e-10, max_iter: int = 200) -> list[float]:
    """Velocity Verlet with an SCF solve at every step. Returns the total energy at each step."""
    c, e, _, _ = model.scf(x, tol=tol, max_iter=200)                      # @line L1
    dens = [ci * ci for ci in c]
    f = model.forces(x, c)                                                # @line L2
    energies = [e + 0.5 * sum(mi * vi * vi for mi, vi in zip(m, v))]
    for _ in range(steps):                                                # @line L3
        v = [vi + 0.5 * h * fi / mi for vi, fi, mi in zip(v, f, m)]       # @line L4
        x = [xi + h * vi for xi, vi in zip(x, v)]                         # @line L5
        c, e, _, _ = model.scf(x, dens, tol, max_iter)                    # @line L6
        dens = [ci * ci for ci in c]
        f = model.forces(x, c)                                            # @line L7
        v = [vi + 0.5 * h * fi / mi for vi, fi, mi in zip(v, f, m)]       # @line L8
        energies.append(e + 0.5 * sum(mi * vi * vi for mi, vi in zip(m, v)))
    return energies                                                       # @line L9
test_born_oppenheimer_molecular_dynamics.py 89 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/born-oppenheimer-molecular-dynamics/. The authors are listed in prov/KR4Y5Q.jsonl.
import math
import random

import pytest

from born_oppenheimer_molecular_dynamics import ToyModel, bomd, jacobi_eigen

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


def test_jacobi_on_two_by_two():
    vals, _ = jacobi_eigen([[2.0, 1.0], [1.0, 3.0]])
    assert vals == pytest.approx([(5 - math.sqrt(5)) / 2, (5 + math.sqrt(5)) / 2], abs=1e-14)


def test_jacobi_on_random_symmetric_matrix():
    rng = random.Random(1)
    n = 5
    a = [[0.0] * n for _ in range(n)]
    for i in range(n):
        for j in range(i, n):
            a[i][j] = a[j][i] = rng.uniform(-1, 1)
    vals, vecs = jacobi_eigen(a)
    assert vals == sorted(vals)
    for k in range(n):
        col = [vecs[i][k] for i in range(n)]
        av = [sum(a[i][j] * col[j] for j in range(n)) for i in range(n)]
        assert max(abs(p - vals[k] * q) for p, q in zip(av, col)) < 1e-12
        for l in range(n):
            dot = sum(vecs[i][k] * vecs[i][l] for i in range(n))
            assert dot == pytest.approx(1.0 if k == l else 0.0, abs=1e-12)


def test_dimer_without_repulsion_term_matches_closed_form():
    # E(r) = -2 t0 e^{-(r - 1)} + e^{-2 (r - 1)}: minimum E = -1 at r = 1, E'' = 2.
    model = ToyModel(u=0.0)
    for r in (0.8, 1.0, 1.3):
        assert model.scf([0.0, r])[1] == pytest.approx(-2 * math.exp(-(r - 1)) + math.exp(-2 * (r - 1)), abs=1e-12)
    e = [model.scf([0.0, r])[1] for r in (0.99, 1.0, 1.01)]
    assert e[1] == pytest.approx(-1.0, abs=1e-12)
    assert (e[0] - 2 * e[1] + e[2]) / 1e-4 == pytest.approx(2.0, abs=1e-3)


def test_scf_gives_lowest_eigenvector_of_its_own_matrix():
    model = ToyModel(u=1.0)
    c, _, res, _ = model.scf(X0)
    assert res < 1e-10
    h0 = model.hopping(X0)
    h = [[h0[i][j] + (c[i] ** 2 if i == j else 0.0) for j in range(4)] for i in range(4)]
    vals, vecs = jacobi_eigen(h)
    assert abs(sum(c[i] * vecs[i][0] for i in range(4))) == pytest.approx(1.0, abs=1e-9)


def test_hellmann_feynman_force_matches_finite_differences_only_at_scf():
    model = ToyModel(u=1.0)
    c, _, _, _ = model.scf(X0)
    f = model.forces(X0, c)
    for k in range(4):
        xp, xm = list(X0), list(X0)
        xp[k] += 1e-5
        xm[k] -= 1e-5
        fd = -(model.scf(xp)[1] - model.scf(xm)[1]) / 2e-5
        assert f[k] == pytest.approx(fd, abs=1e-7)
    # One SCF iteration from a flat density leaves an orbital that is not stationary.
    c1, _, res, _ = model.scf(X0, max_iter=1)
    assert res > 0.05
    assert max(abs(p - q) for p, q in zip(model.forces(X0, c1), f)) > 0.02
    assert sum(f) == pytest.approx(0.0, abs=1e-12)


def test_tight_scf_conserves_energy_with_second_order_fluctuations():
    model = ToyModel(u=1.0)
    e1 = bomd(model, list(X0), list(V0), MASSES, 0.05, 500)
    e2 = bomd(model, list(X0), list(V0), MASSES, 0.025, 1000)
    s1, s2 = max(e1) - min(e1), max(e2) - min(e2)
    assert s1 < 1e-3
    assert math.log2(s1 / s2) == pytest.approx(2.0, abs=0.4)


def test_loose_scf_drifts():
    model = ToyModel(u=1.0)
    tight = bomd(model, list(X0), list(V0), MASSES, 0.05, 1000)
    loose = bomd(model, list(X0), list(V0), MASSES, 0.05, 1000, max_iter=1)
    assert abs(loose[-1] - loose[0]) > 100 * abs(tight[-1] - tight[0])
    assert abs(loose[-1] - loose[0]) > 0.01

History

Early ab initio trajectory studies, such as that of Leforestier (1978) on a small reaction, evaluated the quantum chemical energy and gradient at every step of a classical trajectory. Car and Parrinello (1985) showed how to avoid the full electronic minimization at each step, and for some years their method dominated condensed-matter work. With better SCF methods and initial guesses, Born-Oppenheimer dynamics with density functional theory became the more common approach. Niklasson (2008) explained the energy drift of BOMD by the broken time reversibility of the SCF initial guess and removed it with an extended Lagrangian. Marx and Hutter (2009) treat both methods in one book.

References

  1. 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 Born-Oppenheimer molecular dynamics and on the Hellmann-Feynman forces
  2. Anders M. N. Niklasson, Extended Born-Oppenheimer molecular dynamics, Physical Review Letters 100, 123004, 2008, the loss of time reversibility and the energy drift caused by the SCF initial guess, and the extended Lagrangian that restores reversibility
  3. Roberto Car and Michele Parrinello, Unified approach for molecular dynamics and density-functional theory, Physical Review Letters 55, 2471-2474, 1985, the alternative to solving the electrons at every step, used for comparison

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

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