Algorithm Search⌘K

Algorithmadvanced

QM/MM method

Also called hybrid quantum mechanics molecular mechanics.

Treats a small reactive region by quantum mechanics and the rest by a molecular mechanics force field, with coupling terms between them.

Time
O(q^3 + N) worst
Space
O(q^2 + N) extra
Where
N = the number of atoms; q = the number of sites in the QM model system
Properties
deterministicnot exactnot iterativenot randomized
Origin
Arieh Warshel, Michael Levitt, 1976

The QM/MM method computes the energy and forces of a large molecular system by treating a small region, where bonds break or electrons move, with quantum mechanics (QM), and everything else with a molecular mechanics force field (MM). Quantum calculations cost at least the cube of the size of the region, while force fields cost about linear time, so the split makes reactions in enzymes, in solution and in materials possible to model. The two regions are coupled by bonded terms across the boundary, by electrostatics and by van der Waals terms, and bonds cut by the boundary are capped with link atoms. With these energies and forces, the system can be optimized or moved by molecular dynamics in the spirit of Born-Oppenheimer molecular dynamics for the QM part.

In plain words

Think of an enzyme with thousands of atoms. Only a few of them take part in the chemical reaction; the rest hold the stage. Computing the electrons of all atoms would take far too long, so you compute the electrons only for the small group at the center, and treat all other atoms as balls on springs.

Where the two parts meet, a chemical bond is cut in two. To keep the small group chemically sensible, you put a stand-in atom, usually hydrogen, on the cut bond. The forces on the stand-in are passed back to the two real atoms of the bond. There are two ways to add up the energies: add the small group and the rest, taking care not to count anything twice, or compute the whole system cheaply and replace the cheap energy of the center by the accurate one.

The problem

The input is the positions of NN atoms, a QM region QQ of atoms, a QM method that gives the energy and the forces of a small molecule, and an MM force field for the whole system. The output is a total energy EE and forces F=−∇EF = -\nabla E on all atoms, so that geometry optimization and molecular dynamics can use them. The model system is the QM region with a link atom LL on each cut bond (a,b)(a, b), a∈Qa \in Q, b∉Qb \notin Q, placed on the bond at

yL=ya+g (yb−ya)y_L = y_a + g\, (y_b - y_a)

with a fixed ratio gg (for a carbon-hydrogen link that replaces a carbon-carbon bond, gg is near the ratio of the two bond lengths). The additive energy is

E=EQM(model)+EMM(outside Q)+EQM-MM,E = E_{QM}(\text{model}) + E_{MM}(\text{outside } Q) + E_{QM\text{-}MM},

where EQM-MME_{QM\text{-}MM} couples the regions. The subtractive energy (IMOMM, ONIOM) is

E=EMM(real)+EQM(model)−EMM(model).E = E_{MM}(\text{real}) + E_{QM}(\text{model}) - E_{MM}(\text{model}).

In mechanical embedding, the coupling is the MM terms between QM and MM atoms. In electrostatic embedding, the MM charges also enter the QM Hamiltonian, so the electrons of the QM region are polarized by the environment.

The algorithm

  1. QMMM-ADDITIVE(positions y, QM region Q, ratio g)
  2. 1build the model system: the atoms of Q, and a link atom at y_L = y_a + g (y_b - y_a) on each cut bond (a, b)
  3. 2(E_Q, F_Q) ← QM energy and forces of the model system
  4. 3for each link atom L on the cut bond (a, b): F_a ← F_a + (1 - g) F_L, F_b ← F_b + g F_L, then drop L
  5. 4(E_M, F_M) ← MM energy and forces of every term with at least one atom outside Q
  6. 5return E = E_Q + E_M and F = F_Q + F_M

The link atom is not a real atom: its position is a function of yay_a and yby_b, so its force must be passed to them by the chain rule, which is line L3. Line L4 takes the coupling terms (bonds, angles and dihedrals across the boundary, and the van der Waals terms between the regions) from the force field, which is mechanical embedding; in electrostatic embedding the MM charges also go into the QM calculation of line L2, and the MM terms of line L4 leave out the electrostatics between the regions, because the QM calculation already contains them.

The implementation is a toy. The QM method is a Hückel tight-binding model of a chain on a line, with hopping t(r)=t0e−β(r−r0)t(r) = t_0 e^{-\beta (r - r_0)}, one electron per site and the energy 2∑occupiedλk+∑iAe−2β(ri−r0)2 \sum_{\text{occupied}} \lambda_k + \sum_i A e^{-2 \beta (r_i - r_0)}. The matrix is diagonalized by the Jacobi eigenvalue algorithm, and the forces follow from the Hellmann-Feynman formula. The MM part is harmonic bonds (k/2)(r−d0)2(k/2)(r - d_0)^2. The parameters t0=1t_0 = 1, β=ln⁡2\beta = \ln 2, A=1A = 1, r0=1r_0 = 1, k=10k = 10, d0=2d_0 = 2 and g=1/2g = 1/2 are choices that make the numbers simple. The code also has the subtractive scheme.

Example

By hand. Three atoms sit at y=(0,2.2,4.2)y = (0, 2.2, 4.2) and atom 00 is the QM region. The cut bond is (0,1)(0, 1), so line L1 puts the link atom at 0+0.5⋅2.2=1.10 + 0.5 \cdot 2.2 = 1.1, and the model system is a dimer of length 1.11.1. Its hopping is t=2−0.1=0.933033t = 2^{-0.1} = 0.933033 and its repulsion is Ae−2β⋅0.1=2−0.2=0.870551A e^{-2\beta \cdot 0.1} = 2^{-0.2} = 0.870551. The dimer has one bonding orbital with eigenvalue −t-t and two electrons, so line L2 gives EQ=−2t+2−0.2=−0.995515E_Q = -2t + 2^{-0.2} = -0.995515, and

dEQdr=2βt−2β⋅2−0.2=2ln⁡2⋅(0.933033−0.870551)=0.086619.\frac{dE_Q}{dr} = 2 \beta t - 2 \beta \cdot 2^{-0.2} = 2 \ln 2 \cdot (0.933033 - 0.870551) = 0.086619 .

So the force on atom 00 is +0.086619+0.086619 and the force on the link atom is −0.086619-0.086619. Line L3 gives half of the link force to atom 00 and half to atom 11: the QM forces on the real atoms are (0.043310,−0.043310,0)(0.043310, -0.043310, 0). Line L4 adds the cut bond, stretched by 0.20.2, with energy 5⋅0.04=0.25 \cdot 0.04 = 0.2 and forces (2,−2)(2, -2) on atoms 00 and 11; bond (1,2)(1, 2) is at rest. The total is E=−0.795515E = -0.795515 with F=(2.043310,−2.043310,0)F = (2.043310, -2.043310, 0).

Subtractive. For the same atoms, ONIOM gives E=0.2−0.995515−0.2=−0.995515E = 0.2 - 0.995515 - 0.2 = -0.995515: the MM energy of the real system is the cut bond, 0.20.2, and in the model system the link bond gets the MM parameters (k/g2,gd0)=(40,1)(k / g^2, g d_0) = (40, 1), so its MM energy is 20⋅0.12=0.220 \cdot 0.1^2 = 0.2 as well. The two schemes differ by the MM energy of the cut bonds, a fact that the proofs file proves for any chain with this choice of link parameters.

Dynamics. On a chain of 8 atoms with the QM region of atoms 22 to 55 (two link atoms, a model system of 6 sites), velocity Verlet over 5 time units keeps the total energy to within 2.65⋅10−42.65 \cdot 10^{-4} at h=0.02h = 0.02 and 6.69⋅10−56.69 \cdot 10^{-5} at h=0.01h = 0.01 for the additive scheme, and 3.57⋅10−43.57 \cdot 10^{-4} and 9.24⋅10−59.24 \cdot 10^{-5} for ONIOM. The ratio is close to 44, the second order of the integrator, which shows that the forces are the gradient of the energy (measurement).

Correctness

The proofs file shows, for the toy, that the forces are the exact negative gradient of the energy. The model system of an even number of sites on a chain always has a gap between the occupied and the empty orbitals, because the spectrum is symmetric about 00 and 00 is not an eigenvalue; with the gap, the derivative of the sum of the occupied eigenvalues is the Hellmann-Feynman expression 2∑kckT(∂H/∂r)ck2 \sum_k c_k^T (\partial H / \partial r) c_k. The link atom position is linear in the positions of aa and bb, so line L3 is the chain rule. The proof also shows that the forces sum to zero, that both schemes give the pure QM energy when QQ contains all atoms, and that the additive minus the subtractive energy is the MM energy of the cut bonds.

For a real QM method, the same argument needs a converged self-consistent field: the Hellmann-Feynman forces are the gradient only at the variational minimum, and with a basis of atom-centered functions they need the Pulay terms as well. The quality of the result, how close EE is to the energy of a full QM calculation, is not a theorem: it depends on the size of the QM region, the boundary and the embedding, and is checked by tests that enlarge the region.

Proof: The toy QM/MM forces are the exact gradient of the QM/MM energy, and the energy has the right limitsfull

Setup. Atoms 0,…,n−10, \dots, n - 1 sit at y0<y1<⋯<yn−1y_0 < y_1 < \dots < y_{n-1} on a line. The QM region is the block Q={q0,…,q1−1}Q = \{q_0, \dots, q_1 - 1\}. Each cut bond (a,b)(a, b), with a∈Qa \in Q and b∉Qb \notin Q a neighbor of aa, gets a link atom at yL=(1−g)ya+gyby_L = (1 - g) y_a + g y_b with a fixed 0<g<10 < g < 1. The model system is the ordered list of sites: the left link atom if there is one, the atoms of QQ, and the right link atom if there is one. Each site position is sm=∑atom cWmc ycs_m = \sum_{\text{atom } c} W_{m c}\, y_c with fixed weights WW (line L1). For sites s0<⋯<sM−1s_0 < \dots < s_{M-1} with bond lengths ri=si+1−sir_i = s_{i+1} - s_i and t(r)=t0e−β(r−r0)t(r) = t_0 e^{-\beta (r - r_0)}, the tight-binding matrix HH has Hi,i+1=Hi+1,i=−t(ri)H_{i, i+1} = H_{i+1, i} = -t(r_i) and zeros elsewhere, and

EQM(s)=2∑k=1M/2λk(H)+∑iAe−2β(ri−r0),E_{QM}(s) = 2 \sum_{k = 1}^{M/2} \lambda_k(H) + \sum_i A e^{-2 \beta (r_i - r_0)},

with the eigenvalues λ1≤⋯≤λM\lambda_1 \le \dots \le \lambda_M and MM even. The additive energy is E=EQM(Wy)+EMM(y)E = E_{QM}(W y) + E_{MM}(y), where EMME_{MM} sums (k/2)(yi+1−yi−d0)2(k / 2)(y_{i+1} - y_i - d_0)^2 over all bonds with at least one atom outside QQ. We assume exact arithmetic and an exact eigensolver.

Lemma 1 (a gap at half filling). If MM is even and every t(ri)>0t(r_i) > 0, then λM/2<0<λM/2+1\lambda_{M/2} < 0 < \lambda_{M/2 + 1}.

Proof. HH has a zero diagonal and the sites form a path, so the matrix D=diag⁡(1,−1,1,… )D = \operatorname{diag}(1, -1, 1, \dots) satisfies DHD=−HD H D = -H, and the spectrum is symmetric about 00. Expanding the determinant of a tridiagonal matrix with zero diagonal along the first row gives det⁡HM=−t12det⁡HM−2\det H_M = -t_1^2 \det H_{M-2}, so det⁡H=(−1)M/2∏i oddt(ri)2≠0\det H = (-1)^{M/2} \prod_{i \text{ odd}} t(r_i)^2 \ne 0, and 00 is not an eigenvalue. A symmetric spectrum without 00 has exactly M/2M/2 negative eigenvalues. □\square

Lemma 2 (Hellmann-Feynman for the occupied sum). Let c1,…,cM/2c_1, \dots, c_{M/2} be orthonormal eigenvectors of the occupied eigenvalues. Under the gap of Lemma 1,

∂∂ri 2∑k≤M/2λk=2∑k≤M/2ckT∂H∂rick=2Pi β t(ri),Pi=2∑k≤M/2ck,i ck,i+1.\frac{\partial}{\partial r_i} \, 2 \sum_{k \le M/2} \lambda_k = 2 \sum_{k \le M/2} c_k^T \frac{\partial H}{\partial r_i} c_k = 2 P_i\, \beta\, t(r_i), \qquad P_i = 2 \sum_{k \le M/2} c_{k, i}\, c_{k, i+1}.

Proof. Let Π=∑k≤M/2ckckT\Pi = \sum_{k \le M/2} c_k c_k^T, the projector onto the occupied space, so ∑k≤M/2λk=tr⁡(ΠH)\sum_{k \le M/2} \lambda_k = \operatorname{tr}(\Pi H). Because of the gap, Π\Pi is a smooth function of HH (it is the Riesz projector, a contour integral of the resolvent around the negative eigenvalues). Differentiate: dtr⁡(ΠH)=tr⁡(Π dH)+tr⁡(H dΠ)d \operatorname{tr}(\Pi H) = \operatorname{tr}(\Pi\, dH) + \operatorname{tr}(H\, d\Pi). From Π2=Π\Pi^2 = \Pi we get dΠ=Π dΠ+dΠ Πd\Pi = \Pi\, d\Pi + d\Pi\, \Pi, so Π dΠ Π=0\Pi\, d\Pi\, \Pi = 0 and (I−Π) dΠ (I−Π)=0(I - \Pi)\, d\Pi\, (I - \Pi) = 0. Hence dΠ=Π dΠ (I−Π)+(I−Π) dΠ Πd\Pi = \Pi\, d\Pi\, (I - \Pi) + (I - \Pi)\, d\Pi\, \Pi. Since HH commutes with Π\Pi, tr⁡(HΠ dΠ (I−Π))=tr⁡((I−Π)HΠ dΠ)=0\operatorname{tr}(H \Pi\, d\Pi\, (I - \Pi)) = \operatorname{tr}((I - \Pi) H \Pi\, d\Pi) = 0, and the same holds for the other term. So dtr⁡(ΠH)=tr⁡(Π dH)=∑kckTdH ckd \operatorname{tr}(\Pi H) = \operatorname{tr}(\Pi\, dH) = \sum_k c_k^T dH\, c_k. Only Hi,i+1=Hi+1,i=−t(ri)H_{i, i+1} = H_{i+1, i} = -t(r_i) depend on rir_i, with derivative βt(ri)\beta t(r_i), so ckT(∂H/∂ri)ck=2βt(ri)ck,ick,i+1c_k^T (\partial H / \partial r_i) c_k = 2 \beta t(r_i) c_{k,i} c_{k,i+1}. Summing over kk and multiplying by 22 gives the formula. □\square

Lemma 3 (the QM site forces). Function qm_chain returns fm=−∂EQM/∂smf_m = -\partial E_{QM} / \partial s_m.

Proof. By Lemma 2 and ddrAe−2β(r−r0)=−2βAe−2β(r−r0)\frac{d}{dr} A e^{-2\beta (r - r_0)} = -2 \beta A e^{-2\beta (r - r_0)}, the code computes ∂EQM/∂ri\partial E_{QM} / \partial r_i as de_dr. Since ri=si+1−sir_i = s_{i+1} - s_i, bond ii contributes −∂EQM/∂ri-\partial E_{QM} / \partial r_i to ∂EQM/∂si\partial E_{QM} / \partial s_i and +∂EQM/∂ri+\partial E_{QM} / \partial r_i to ∂EQM/∂si+1\partial E_{QM} / \partial s_{i+1}. The code adds the negatives of these: de_dr to fif_i and minus de_dr to fi+1f_{i+1}. □\square

Lemma 4 (the link atom forces). Line L3 returns −∂EQM(Wy)/∂yc=∑mWmcfm-\partial E_{QM}(W y) / \partial y_c = \sum_m W_{mc} f_m for each atom cc.

Proof. s=Wys = W y is linear, so ∂EQM(Wy)/∂yc=∑m(∂EQM/∂sm)Wmc\partial E_{QM}(W y) / \partial y_c = \sum_m (\partial E_{QM} / \partial s_m) W_{mc}. Function _spread adds WmcfmW_{mc} f_m for every site mm and every atom cc in it. For a link atom of the cut bond (a,b)(a, b) this gives (1−g)fL(1 - g) f_L to aa and gfLg f_L to bb. □\square

Theorem (correctness). (i) Lines L1 to L5 return EE and F=−∇yEF = -\nabla_y E exactly. (ii) ∑cFc=0\sum_c F_c = 0. (iii) If QQ contains all atoms, the additive and the subtractive energies both equal EQM(y)E_{QM}(y). (iv) If a bond to a link atom gets the MM parameters (k/g2,gd0)(k / g^2, g d_0) in the model system, then Eadditive−EONIOME_{\text{additive}} - E_{\text{ONIOM}} is the MM energy of the cut bonds.

Proof. (i) Lemmas 3 and 4 for the QM part; for the MM part, ∂∂yjk2(yj−yi−d0)2=k(yj−yi−d0)\frac{\partial}{\partial y_j} \frac{k}{2} (y_j - y_i - d_0)^2 = k (y_j - y_i - d_0) and the code adds k⋅stretchk \cdot \text{stretch} to FiF_i and subtracts it from FjF_j. (ii) EE depends on the positions only through differences, because the rows of WW sum to 11, so E(y+ϵ1)=E(y)E(y + \epsilon \mathbf{1}) = E(y) and ∑c∂E/∂yc=0\sum_c \partial E / \partial y_c = 0. (iii) With QQ equal to all atoms there are no cut bonds, W=IW = I and every bond has both atoms in QQ, so EMM=0E_{MM} = 0 and E=EQM(y)E = E_{QM}(y). In ONIOM, the model system is the real system and has the same MM bonds, so EMM(real)−EMM(model)=0E_{MM}(\text{real}) - E_{MM}(\text{model}) = 0. (iv) For a cut bond (a,b)(a, b), the link bond has length ∣yL−ya∣=g∣yb−ya∣|y_L - y_a| = g |y_b - y_a|, so its MM energy in the model is k2g2(grab−gd0)2=k2(rab−d0)2\frac{k}{2 g^2} (g r_{ab} - g d_0)^2 = \frac{k}{2} (r_{ab} - d_0)^2, the MM energy of the cut bond. So EMM(model)E_{MM}(\text{model}) is the MM energy of the bonds inside QQ plus that of the cut bonds, and EONIOM=EMM(real)−EMM(model)+EQME_{\text{ONIOM}} = E_{MM}(\text{real}) - E_{MM}(\text{model}) + E_{QM} is EQME_{QM} plus the MM energy of the bonds with both atoms outside QQ. The additive energy is EQME_{QM} plus the MM energy of all bonds with at least one atom outside QQ, which also counts the cut bonds. □\square

Remark. Statement (i) is what makes molecular dynamics with these forces conserve the total energy up to the error of the integrator, which the tests measure. In real QM/MM programs, the QM energy comes from a self-consistent method, and the Hellmann-Feynman step of Lemma 2 needs the self-consistent solution to be converged; a partly converged solution gives forces that are not the exact gradient. ■\blacksquare

Complexity

In the real RAM model, the toy costs O(q3)O(q^3) per sweep of the Jacobi method on the qq by qq matrix of the model system, with a capped number of sweeps, and O(N)O(N) for the bonds of the MM part, so an energy and force evaluation is O(q3+N)O(q^3 + N) with O(q2+N)O(q^2 + N) memory. In real programs, the QM part dominates: Hartree-Fock and density functional methods cost between the cube and the fourth power of the number of basis functions, and correlated methods more, while the MM part costs O(Nlog⁡N)O(N \log N) with particle mesh Ewald electrostatics. Electrostatic embedding adds the NN MM charges to the QM Hamiltonian, at a cost linear in NN per QM matrix element of the external potential.

Properties

  • Consistent forces. With a converged QM calculation and the chain rule for link atoms, the forces are the gradient of a single energy, so dynamics conserve energy and optimizations converge (theorem for the toy, Lemma 2 and Lemma 4 of the proofs file).
  • Correct limits. If the QM region is the whole system, both schemes give the QM energy (theorem). If the QM method is replaced by the MM method, the subtractive scheme gives the MM energy of the real system exactly (theorem, from the form of the formula).
  • Additive versus subtractive. The subtractive scheme needs no special coupling terms and works with any pair of methods, but needs MM parameters for the model system, including the QM region. The additive scheme needs no MM parameters inside the QM region, which matters when bonds change.
  • Approximate. The result depends on the choice of the QM region, the link atoms and the embedding, and must be checked by enlarging the QM region (heuristic).
  • Translation invariance. The energy depends only on the relative positions, so the forces sum to zero (theorem).

Variants and improvements

  • Electrostatic embedding. The MM point charges enter the QM Hamiltonian, which polarizes the QM region. This is the common choice for reactions in proteins and solution. Charges next to the link atom are often removed, shifted or smeared, to avoid an overpolarization of the boundary.
  • Polarizable embedding. The MM region has induced dipoles or fluctuating charges, which respond to the QM region in turn.
  • Other boundary treatments. Instead of link atoms, the cut bond can be capped by frozen localized orbitals or by a boundary atom with special parameters (pseudopotentials).
  • Several layers. ONIOM uses three or more layers, each with its own method, by repeating the subtraction.
  • Adaptive QM/MM. Atoms enter and leave the QM region as they move, for example water molecules near a solute, with a smooth switching to keep the energy continuous.
  • Machine learning potentials. A Behler-Parrinello or other learned potential can replace the QM method, or the MM region, at a much lower cost.

When to use it

Use QM/MM when a chemical event (a bond that breaks, a change of charge, an excited state) takes place in a small part of a large system, and the rest acts through its shape and its electrostatics. Use a plain molecular mechanics force field when no bonds change. Use a full QM method, as in Born-Oppenheimer or Car-Parrinello molecular dynamics, when the system is small enough or when the chemistry is spread out, for example in a metal. Use the quasicontinuum method for the analogous split between atoms and a continuum in solids.

Pitfalls

  • The link force is dropped. Leaving out line L3, or giving all of FLF_L to atom aa, gives forces that are not the gradient of the energy, and molecular dynamics drifts in energy. Write line L3 with the chain rule weights 1−g1 - g for aa and gg for bb.
  • Terms counted twice. In the additive scheme, line L4 must leave out the MM terms with all atoms in QQ, because EQE_Q already contains them; in the subtractive scheme, EMM(model)E_{MM}(\text{model}) must use the same terms as EMM(real)E_{MM}(\text{real}) for the model atoms. Write line L4 over the terms with at least one atom outside QQ.
  • Odd electron counts. A link atom adds one electron per cut bond. The toy raises an error when the model system has an odd number of electrons; a real calculation must set the charge and spin of the model system on purpose.
  • Overpolarization at the boundary. In electrostatic embedding, an MM charge on atom bb sits very close to the link atom and pulls the QM electrons too strongly. Remove, shift or smear the charges next to the boundary.
  • Cuts through polar or conjugated bonds. A link atom on a polar bond, or on a bond of a conjugated system, changes the electronic structure of the QM region. Cut nonpolar single bonds, two or three bonds away from the reacting atoms.
  • A QM region too small. Results can change much with the size of the QM region. Check convergence by enlarging the region.
  • Unconverged QM forces. A loose convergence of the self-consistent field gives forces that are not the gradient of the energy. Tighten the convergence for dynamics.

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.

qm_mm_method.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/qm-mm-method/. The authors are listed in prov/CDM80T.jsonl.
"""A toy QM/MM calculation on a chain of atoms in one dimension.

This is a toy. The "QM" part is a Hueckel tight-binding model, not a real
electronic structure method, and the "MM" part is a chain of harmonic
bonds. The code shows the parts that every QM/MM program has: the split
into a QM region and an MM region, the link atoms that cap the cut bonds,
the transfer of the link atom forces onto the real atoms, and the two ways
to add the energies (additive and subtractive, also called ONIOM).

Atoms 0 .. n-1 sit at positions y[0] < y[1] < ... on a line, with a bond
between each pair of neighbors. The QM region is the block of atoms
q0 .. q1-1. Each bond (a, b) with a in the QM region and b outside it is
cut and gets a link atom at y_a + g (y_b - y_a).

QM model (for a chain of sites s_0 < s_1 < ... with bond lengths r_i):
    H_{i,i+1} = -t(r_i), t(r) = t0 exp(-beta (r - r0)), one orbital per site,
    one electron per site, each occupied orbital holds two electrons,
    E_QM = 2 (sum of the occupied eigenvalues) + sum_i A exp(-2 beta (r_i - r0)).
MM model: E_MM = sum over bonds of (k / 2) (r - d0)^2.
"""

import math
from dataclasses import dataclass
from typing import Sequence


@dataclass(frozen=True)
class Params:
    t0: float = 1.0                 # hopping at r = r0
    beta: float = math.log(2.0)     # decay rate of the hopping
    rep: float = 1.0                # repulsion A; with A = t0 the QM dimer has its minimum at r0
    r0: float = 1.0
    k: float = 10.0                 # MM bond stiffness
    d0: float = 2.0                 # MM bond rest length
    g: float = 0.5                  # link atom placed at the fraction g of the cut bond


def jacobi_eigen(a: Sequence[Sequence[float]], tol: float = 1e-14,
                 max_sweeps: int = 60) -> tuple[list[float], list[list[float]]]:
    """Cyclic Jacobi method for a symmetric matrix.

    Returns the eigenvalues in increasing order and the eigenvectors as rows
    (vecs[k] belongs to vals[k]).
    """
    n = len(a)
    m = [list(map(float, row)) for row in a]
    v = [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
    scale = sum(m[i][j] ** 2 for i in range(n) for j in range(n)) or 1.0
    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 * scale:
            break
        for p in range(n - 1):
            for q in range(p + 1, n):
                if m[p][q] == 0.0:
                    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 r in range(n):          # columns p and q
                    mrp, mrq = m[r][p], m[r][q]
                    m[r][p] = c * mrp - s * mrq
                    m[r][q] = s * mrp + c * mrq
                for r in range(n):          # rows p and q
                    mpr, mqr = m[p][r], m[q][r]
                    m[p][r] = c * mpr - s * mqr
                    m[q][r] = s * mpr + c * mqr
                for r in range(n):
                    vrp, vrq = v[r][p], v[r][q]
                    v[r][p] = c * vrp - s * vrq
                    v[r][q] = s * vrp + c * vrq
    else:
        raise ArithmeticError("Jacobi method did not converge")
    order = sorted(range(n), key=lambda i: m[i][i])
    return [m[i][i] for i in order], [[v[r][i] for r in range(n)] for i in order]


def qm_chain(s: Sequence[float], p: Params) -> tuple[float, list[float]]:
    """Energy and forces of the tight-binding chain with sites at s (sorted)."""
    n = len(s)
    if n % 2 != 0:
        raise ValueError("the model system needs an even number of sites (closed shell)")
    r = [s[i + 1] - s[i] for i in range(n - 1)]
    t = [p.t0 * math.exp(-p.beta * (ri - p.r0)) for ri in r]
    h = [[0.0] * n for _ in range(n)]
    for i in range(n - 1):
        h[i][i + 1] = h[i + 1][i] = -t[i]
    vals, vecs = jacobi_eigen(h)
    occ = vecs[:n // 2]
    energy = 2.0 * sum(vals[:n // 2])
    f = [0.0] * n
    for i in range(n - 1):
        bond_order = 2.0 * sum(c[i] * c[i + 1] for c in occ)
        phi = p.rep * math.exp(-2.0 * p.beta * (r[i] - p.r0))
        energy += phi
        # Hellmann-Feynman: dE_el/dr = 2 P dH/dr = 2 P beta t; dphi/dr = -2 beta phi
        de_dr = 2.0 * bond_order * p.beta * t[i] - 2.0 * p.beta * phi
        f[i] += de_dr
        f[i + 1] -= de_dr
    return energy, f


def mm_bonds(y: Sequence[float], bonds: Sequence[tuple[int, int, float, float]],
             n: int) -> tuple[float, list[float]]:
    """Harmonic bonds (i, j, k, d0) with energy (k / 2) (y_j - y_i - d0)^2."""
    energy = 0.0
    f = [0.0] * n
    for i, j, k, d0 in bonds:
        stretch = (y[j] - y[i]) - d0
        energy += 0.5 * k * stretch * stretch
        f[i] += k * stretch
        f[j] -= k * stretch
    return energy, f


def model_sites(n: int, q0: int, q1: int, g: float) -> list[list[tuple[int, float]]]:
    """Each site of the model system as a list of (atom, weight); a link atom has two."""
    if not 0 <= q0 < q1 <= n:
        raise ValueError("the QM region must be a nonempty block of atoms")
    sites = []
    if q0 > 0:
        sites.append([(q0, 1.0 - g), (q0 - 1, g)])      # cut bond (q0 - 1, q0)
    sites.extend([[(i, 1.0)] for i in range(q0, q1)])
    if q1 < n:
        sites.append([(q1 - 1, 1.0 - g), (q1, g)])      # cut bond (q1 - 1, q1)
    return sites


def _spread(site_forces: Sequence[float], sites: Sequence[Sequence[tuple[int, float]]],
            n: int) -> list[float]:
    """Chain rule: a site at sum_w w y_atom passes the force w F_site to each atom."""
    f = [0.0] * n
    for fs, site in zip(site_forces, sites):
        for atom, w in site:
            f[atom] += w * fs
    return f


def additive(y: Sequence[float], q0: int, q1: int, p: Params = Params()) -> tuple[float, list[float]]:
    """Additive QM/MM with link atoms and mechanical embedding."""
    n = len(y)
    sites = model_sites(n, q0, q1, p.g)                                         # @line L1
    s = [sum(w * y[a] for a, w in site) for site in sites]
    e_qm, f_sites = qm_chain(s, p)                                              # @line L2
    f = _spread(f_sites, sites, n)                                              # @line L3
    mm = [(i, i + 1, p.k, p.d0) for i in range(n - 1) if not (q0 <= i and i + 1 < q1)]
    e_mm, f_mm = mm_bonds(y, mm, n)                                             # @line L4
    return e_qm + e_mm, [a + b for a, b in zip(f, f_mm)]                        # @line L5


def oniom(y: Sequence[float], q0: int, q1: int, p: Params = Params()) -> tuple[float, list[float]]:
    """Subtractive QM/MM (ONIOM): E_MM(real) + E_QM(model) - E_MM(model).

    In the model system, a bond to a link atom gets the MM parameters
    (k / g^2, g d0), so that its MM energy equals that of the cut bond.
    """
    n = len(y)
    sites = model_sites(n, q0, q1, p.g)
    s = [sum(w * y[a] for a, w in site) for site in sites]
    e_real, f_real = mm_bonds(y, [(i, i + 1, p.k, p.d0) for i in range(n - 1)], n)
    e_qm, f_qm = qm_chain(s, p)
    model_bonds = []
    for i in range(len(sites) - 1):
        link = len(sites[i]) == 2 or len(sites[i + 1]) == 2
        k, d0 = (p.k / p.g ** 2, p.g * p.d0) if link else (p.k, p.d0)
        model_bonds.append((i, i + 1, k, d0))
    e_low, f_low = mm_bonds(s, model_bonds, len(sites))
    f_model = _spread([a - b for a, b in zip(f_qm, f_low)], sites, n)
    return e_real + e_qm - e_low, [a + b for a, b in zip(f_real, f_model)]


def velocity_verlet(y: list[float], v: list[float], h: float, steps: int, q0: int, q1: int,
                    scheme=additive, p: Params = Params()) -> list[float]:
    """NVE run with unit masses; returns the total energy after each step."""
    e, f = scheme(y, q0, q1, p)
    energies = []
    for _ in range(steps):
        for i in range(len(y)):
            v[i] += 0.5 * h * f[i]
            y[i] += h * v[i]
        e, f = scheme(y, q0, q1, p)
        for i in range(len(y)):
            v[i] += 0.5 * h * f[i]
        energies.append(e + 0.5 * sum(vi * vi for vi in v))
    return energies
test_qm_mm_method.py 99 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/qm-mm-method/. The authors are listed in prov/CDM80T.jsonl.
import math
import random

import pytest

from qm_mm_method import Params, additive, jacobi_eigen, model_sites, oniom, qm_chain, velocity_verlet


def chain(n, seed, jitter=0.1):
    rng = random.Random(seed)
    return [2.0 * i + rng.uniform(-jitter, jitter) for i in range(n)]


def test_jacobi_matches_the_eigenvalues_of_a_uniform_chain():
    n = 6
    h = [[-1.0 if abs(i - j) == 1 else 0.0 for j in range(n)] for i in range(n)]
    vals, vecs = jacobi_eigen(h)
    exact = sorted(-2.0 * math.cos(k * math.pi / (n + 1)) for k in range(1, n + 1))
    assert vals == pytest.approx(exact, abs=1e-12)
    for lam, c in zip(vals, vecs):
        hc = [sum(h[i][j] * c[j] for j in range(n)) for i in range(n)]
        assert hc == pytest.approx([lam * ci for ci in c], abs=1e-12)


def test_dimer_by_hand():
    # Two sites at the distance r0: t = 1, E = -2 t + A = -1 and no force.
    e, f = qm_chain([0.0, 1.0], Params())
    assert e == pytest.approx(-1.0, abs=1e-14)
    assert f == pytest.approx([0.0, 0.0], abs=1e-14)


def test_three_atom_example_by_hand():
    # Atom 0 is QM; the link atom sits at 0 + 0.5 * 2.2 = 1.1.
    y = [0.0, 2.2, 4.2]
    t, phi = 2.0 ** -0.1, 2.0 ** -0.2
    e_qm = -2.0 * t + phi
    de_dr = 2.0 * math.log(2.0) * (t - phi)
    e, f = additive(y, 0, 1)
    assert e == pytest.approx(e_qm + 0.5 * 10.0 * 0.2 ** 2, abs=1e-12)
    assert f == pytest.approx([2.0 + de_dr / 2, -2.0 - de_dr / 2, 0.0], abs=1e-12)
    e2, f2 = oniom(y, 0, 1)
    assert e2 == pytest.approx(e_qm, abs=1e-12)
    assert f2 == pytest.approx([de_dr / 2, -de_dr / 2, 0.0], abs=1e-12)


@pytest.mark.parametrize("scheme", [additive, oniom])
@pytest.mark.parametrize("region", [(0, 3), (2, 6), (5, 8), (0, 8)])
def test_forces_are_minus_the_gradient(scheme, region):
    y = chain(8, 1)
    _, f = scheme(y, *region)
    eps = 1e-6
    for i in range(len(y)):
        up, down = list(y), list(y)
        up[i] += eps
        down[i] -= eps
        fd = -(scheme(up, *region)[0] - scheme(down, *region)[0]) / (2 * eps)
        assert fd == pytest.approx(f[i], abs=1e-7)
    assert abs(sum(f)) < 1e-12


def test_whole_system_in_the_qm_region_gives_the_qm_energy():
    y = chain(6, 3)
    e_qm, _ = qm_chain(y, Params())
    assert additive(y, 0, 6)[0] == pytest.approx(e_qm, abs=1e-12)
    assert oniom(y, 0, 6)[0] == pytest.approx(e_qm, abs=1e-12)


def test_additive_minus_subtractive_is_the_mm_energy_of_the_cut_bonds():
    p = Params()
    y = chain(8, 4, jitter=0.3)
    cut = [(1, 2), (5, 6)]
    e_cut = sum(0.5 * p.k * (y[j] - y[i] - p.d0) ** 2 for i, j in cut)
    assert additive(y, 2, 6)[0] - oniom(y, 2, 6)[0] == pytest.approx(e_cut, abs=1e-12)


def test_link_atoms_and_odd_model_systems():
    assert model_sites(5, 1, 3, 0.5) == [[(1, 0.5), (0, 0.5)], [(1, 1.0)], [(2, 1.0)], [(2, 0.5), (3, 0.5)]]
    with pytest.raises(ValueError):
        additive(chain(5, 0), 1, 2)  # one QM atom and two link atoms: three electrons
    with pytest.raises(ValueError):
        additive(chain(5, 0), 3, 3)


@pytest.mark.parametrize("scheme", [additive, oniom])
def test_energy_is_conserved_to_second_order(scheme):
    def drift(h):
        rng = random.Random(2)
        y = chain(8, 2)
        v = [rng.gauss(0.0, 0.3) for _ in y]
        mean = sum(v) / len(v)
        v = [x - mean for x in v]
        energies = velocity_verlet(y, v, h, round(5.0 / h), 2, 6, scheme)
        return max(abs(e - energies[0]) for e in energies)

    coarse, fine = drift(0.02), drift(0.01)
    assert coarse < 1e-3
    assert 3.0 < coarse / fine < 5.0

History

Warshel and Levitt built the first QM/MM model in 1976, for the reaction of the enzyme lysozyme, with a semiempirical quantum treatment of the reacting atoms inside a classical model of the protein and its dielectric. Field, Bash and Karplus gave in 1990 a general QM/MM potential with link atoms and electrostatic coupling, built into a molecular dynamics program. Maseras and Morokuma introduced the subtractive IMOMM scheme in 1995, and Svensson, Morokuma and coworkers generalized it to the multilayer ONIOM method in 1996. Karplus, Levitt and Warshel received the Nobel Prize in Chemistry in 2013 for multiscale models of complex chemical systems. Senn and Thiel reviewed the methods for biomolecular systems in 2009.

References

  1. A. Warshel and M. Levitt, Theoretical studies of enzymic reactions: dielectric, electrostatic and steric stabilization of the carbonium ion in the reaction of lysozyme, Journal of Molecular Biology 103(2), 1976, 227-249, the first combined model, with a quantum region inside a classical protein
  2. Martin J. Field, Paul A. Bash and Martin Karplus, A combined quantum mechanical and molecular mechanical potential for molecular dynamics simulations, Journal of Computational Chemistry 11(6), 1990, 700-733, the additive QM/MM Hamiltonian with link atoms and electrostatic coupling, used for molecular dynamics
  3. Feliu Maseras and Keiji Morokuma, IMOMM: A new integrated ab initio + molecular mechanics geometry optimization scheme of equilibrium structures and transition states, Journal of Computational Chemistry 16(9), 1995, 1170-1179, the subtractive combination of an ab initio model system with molecular mechanics for the whole system
  4. Mats Svensson, Stephane Humbel, Robert D. J. Froese, Toshiaki Matsubara, Stefan Sieber and Keiji Morokuma, ONIOM: A multilayered integrated MO + MM method for geometry optimizations and single point energy predictions, The Journal of Physical Chemistry 100(50), 1996, 19357-19363, the ONIOM extrapolation with several layers
  5. Hans Martin Senn and Walter Thiel, QM/MM methods for biomolecular systems, Angewandte Chemie International Edition 48(7), 2009, 1198-1229, a review of additive and subtractive schemes, mechanical and electrostatic embedding, and the treatment of the boundary

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