Algorithm Search⌘K

Algorithmadvanced

Quasicontinuum method

Also called QC method.

Keeps full atomistic detail near defects and a Cauchy-Born continuum elsewhere, with the positions of all atoms interpolated from a few representative atoms.

Time
O(I (N + n^3)) worst
Space
O(N + n^2) extra
Where
I = the number of Newton iterations; N = the number of atoms; n = the number of representative atoms
Properties
deterministicnot exactiterativenot randomized
Origin
Ellad B. Tadmor, Michael Ortiz, Rob Phillips, 1996

The quasicontinuum (QC) method computes the equilibrium of a crystal with a defect, such as a crack tip, a dislocation core or a weak bond, at a fraction of the cost of full atomistics. It keeps every atom near the defect, where the strain changes from atom to atom. Far from the defect, where the strain is smooth, it keeps only a few representative atoms (repatoms) and interpolates the positions of all other atoms on a finite element mesh. The energy of the far region comes from the Cauchy-Born rule: each element deforms uniformly, so its energy is the number of atoms in it times the energy per atom of the uniformly deformed lattice. The unknowns are the repatom positions, and the method minimizes the approximate energy (energy-based QC) or sets the approximate forces to zero (force-based QC). The difficulty is the interface between the two regions, where the energy-based form makes spurious ghost forces.

In plain words

Think of a long chain of beads joined by springs, with one weak spring in the middle. Near the weak spring the beads move in a complex way, so you follow each bead. Far from it the beads only spread out evenly, so you follow one bead in four or one in ten and place the others evenly between them. For the far part you do not add the springs one by one. You take the energy of one bead in an evenly stretched chain and multiply by the number of beads.

The two descriptions meet at a border. If you only add up energies, the beads at the border feel small false forces, because the near part and the far part count the long springs across the border in different ways. These forces are the ghost forces. One fix is to balance the forces directly instead of the energy.

The problem

The input is a crystal of NN atoms with reference sites XiX_i and a potential energy E(y)E(y) of the positions yy (here a pair potential φ\varphi with a cutoff), boundary conditions, and a defect. The output is an approximation of the local minimizer y∗y^* of EE, with about the same accuracy near the defect, but with only n≪Nn \ll N unknowns. The page uses a chain: atoms 0,…,N−10, \dots, N - 1 at Xi=iaX_i = i a, nearest neighbor bonds (i,i+1)(i, i+1) and second neighbor bonds (i,i+2)(i, i+2), with energy

E(y)=∑isi,i+1 φ(yi+1−yi)+∑iφ(yi+2−yi),E(y) = \sum_{i} s_{i,i+1}\, \varphi(y_{i+1} - y_i) + \sum_i \varphi(y_{i+2} - y_i),

where sbs_b is a scale factor of the bond (sb=1s_b = 1 except at the defect). The two atoms at each end are fixed at yi=Fˉaiy_i = \bar F a i, which applies a mean stretch Fˉ\bar F.

The QC method chooses a sorted set RR of repatoms with positions zz, and a subset A⊂RA \subset R of nonlocal repatoms. The positions of all atoms follow by linear interpolation, y=Tzy = T z: an atom ii between neighboring repatoms p<i<qp < i < q gets yi=((q−i)zp+(i−p)zq)/(q−p)y_i = ((q - i) z_p + (i - p) z_q) / (q - p). Each pair of neighboring repatoms forms an element e=(p,q)e = (p, q) with ne=q−pn_e = q - p lattice spacings and the deformation gradient Fe=(zq−zp)/(nea)F_e = (z_q - z_p) / (n_e a). The Cauchy-Born energy per atom is W(F)=φ(Fa)+φ(2Fa)W(F) = \varphi(F a) + \varphi(2 F a) for the chain with second neighbors.

The energy-based approximation is the sum of the energies of the atoms: half of each bond for a nonlocal atom, W(Fe)W(F_e) for a local atom inside an element, and the mean of WW over the two elements for a local repatom. Collected bond by bond and element by element, this is

EQCE(z)=∑bcb sb φ(yj−yi)+∑ewe W(Fe),cb=12 #(b∩A),we=ne−12 #(e∩A),E_{\mathrm{QCE}}(z) = \sum_b c_b\, s_b\, \varphi(y_j - y_i) + \sum_e w_e\, W(F_e), \quad c_b = \tfrac12\, \#(b \cap A), \quad w_e = n_e - \tfrac12\, \#(e \cap A),

where #(b∩A)\#(b \cap A) is the number of ends of bond bb in AA. Bonds with cb=0c_b = 0 drop out, and elements inside the atomistic region have ne=1n_e = 1 and we=0w_e = 0.

The algorithm

  1. QUASICONTINUUM(φ, R, A, z, fixed, tol)
  2. 1build T with y = T z: an atom between repatoms p < i < q gets y_i = ((q - i) z_p + (i - p) z_q) / (q - p)
  3. 2c_b ← (number of ends of bond b in A) / 2, w_e ← n_e - (number of ends of element e in A) / 2
  4. 3repeat
  5. 4y ← T z
  6. 5g ← T^T ∇_y Σ_b c_b s_b φ(y_j - y_i) + ∇_z Σ_e w_e W(F_e) ▷ F_e = (z_q - z_p) / (n_e a)
  7. 6K ← the Hessian of the same energy, restricted to the free repatoms
  8. 7solve K δ = -g on the free repatoms
  9. 8z_free ← z_free + δ
  10. 9until max |g_free| < tol
  11. 10return z, y

Line L1 builds the interpolation, which is the finite element interpolation with linear elements in one dimension. Line L2 fixes the weights once. Lines L4 to L8 are a Newton iteration on EQCEE_{\mathrm{QCE}}. The gradient of line L5 has two parts: the bond forces of the atomistic part, pulled back to the repatoms by TTT^{\mathsf T} (an interpolated atom passes its force to its two repatoms in the ratio of the weights), and the element forces ±weW′(Fe)/(nea)\pm w_e W'(F_e) / (n_e a) with W′(F)=aφ′(Fa)+2aφ′(2Fa)W'(F) = a \varphi'(F a) + 2 a \varphi'(2 F a). The Hessian of line L6 adds cbsbφ′′c_b s_b \varphi'' for each bond, pulled back by TT on both sides, and weW′′(Fe)/(nea)2w_e W''(F_e) / (n_e a)^2 for each element. The fixed repatoms carry the boundary conditions.

The force-based form (QCF) changes lines L5 and L6. For a nonlocal repatom, the residual is minus the exact atomistic force −∂E/∂yi-\partial E / \partial y_i at y=Tzy = T z, with all bonds of atom ii. For a local repatom, it is the gradient of the pure local energy ∑eneW(Fe)\sum_e n_e W(F_e). These forces are not the gradient of any energy, so KK is the Jacobian of the residual and is not symmetric.

Example

Ghost forces by hand. Take a long chain at the uniform state yi=iay_i = i a, with all atoms as repatoms, the atoms i≤0i \le 0 nonlocal and the atoms i≥1i \ge 1 local. Collect the terms of EQCEE_{\mathrm{QCE}} by the function they contain. The nearest neighbor bond (i,i+1)(i, i+1) appears with weight cb+wec_b + w_e, which is 11 for every ii: (1,0)(1, 0) for i≤−1i \le -1, (12,12)(\frac12, \frac12) for i=0i = 0 and (0,1)(0, 1) for i≥1i \ge 1. So with nearest neighbors only, EQCE=EE_{\mathrm{QCE}} = E and there are no ghost forces. The second neighbor terms do not match. The true bonds φ(yi+2−yi)\varphi(y_{i+2} - y_i) have the weights ci=1c_i = 1 for i≤−2i \le -2, 12\frac12 for i=−1i = -1 and 00, and 00 for i≥1i \ge 1, while the elements add wiφ(2(yi+1−yi))w_i \varphi(2 (y_{i+1} - y_i)) with wi=0w_i = 0 for i≤−1i \le -1, 12\frac12 for i=0i = 0 and 11 for i≥1i \ge 1. At the uniform state the derivative of each term is ±φ′(2a)\pm \varphi'(2a), so the force on atom kk is

fk=−∂EQCE∂yk=φ′(2a) (ck−ck−2+2wk−2wk−1).f_k = -\frac{\partial E_{\mathrm{QCE}}}{\partial y_k} = \varphi'(2a)\, \bigl(c_k - c_{k-2} + 2 w_k - 2 w_{k-1}\bigr).

This gives f−1=−12φ′(2a)f_{-1} = -\frac12 \varphi'(2a), f0=12φ′(2a)f_0 = \frac12 \varphi'(2a), f1=12φ′(2a)f_1 = \frac12 \varphi'(2a), f2=−12φ′(2a)f_2 = -\frac12 \varphi'(2a), and fk=0f_k = 0 for all other kk. For the Lennard-Jones potential φ(r)=4ϵ((σ/r)12−(σ/r)6)\varphi(r) = 4\epsilon ((\sigma / r)^{12} - (\sigma / r)^6) in reduced units, the chain with second neighbors has its equilibrium spacing at φ′(a)+2φ′(2a)=0\varphi'(a) + 2 \varphi'(2a) = 0, which is a=(2(1+2−12)/(1+2−6))1/6σ=1.11961 σa = (2 (1 + 2^{-12}) / (1 + 2^{-6}))^{1/6} \sigma = 1.11961\, \sigma. There φ′(2a)=0.083673 ϵ/σ\varphi'(2a) = 0.083673\, \epsilon / \sigma, so the ghost forces are ±0.041837 ϵ/σ\pm 0.041837\, \epsilon / \sigma on the four atoms next to the interface, while the exact forces are zero. The force-based residual is zero at this state.

A weak bond. Take N=81N = 81 Lennard-Jones atoms with a=1.11961 σa = 1.11961\, \sigma, the bond (40,41)(40, 41) scaled by s=0.5s = 0.5, and the two end atoms on each side fixed at a mean stretch Fˉ=1.02\bar F = 1.02. The full atomistic minimizer, by Newton's method on all 77 free atoms, has the energy −80.947593 ϵ-80.947593\, \epsilon and opens the weak bond to 1.174750 σ1.174750\, \sigma, against a mean spacing of 1.142003 σ1.142003\, \sigma. For QC, the atoms 0 to 3, 32 to 49 and 77 to 80 are nonlocal, and the local region has a repatom at every fourth atom, which gives n=40n = 40 repatoms in place of 81 atoms. From the uniformly stretched start, the free gradient of EQCEE_{\mathrm{QCE}} falls in the Newton steps as

step 0 1 2 3 4 5
max⁡∣g∣\max \lvert g \rvert (ϵ/σ\epsilon / \sigma) 4.66×10−14.66 \times 10^{-1} 9.76×10−29.76 \times 10^{-2} 8.54×10−38.54 \times 10^{-3} 8.67×10−58.67 \times 10^{-5} 9.23×10−99.23 \times 10^{-9} 6.5×10−136.5 \times 10^{-13}

which is quadratic convergence. The QCE energy is −80.947681 ϵ-80.947681\, \epsilon. The largest error in the atom positions is 9.5×10−4 σ9.5 \times 10^{-4}\, \sigma for QCE, at atom 4, next to the interface near the fixed end, where the ghost forces act. QCF reaches the same residuals in the same number of steps, and its largest error is 2.2×10−10 σ2.2 \times 10^{-10}\, \sigma. With a nonlocal region of only two atoms on each side of the weak bond (32 repatoms), the QCF error grows to 2.6×10−8 σ2.6 \times 10^{-8}\, \sigma, because the strain field of the defect then reaches the local region. These numbers are measurements on this chain.

Correctness

The proof in the proofs file has four parts. First, EQCEE_{\mathrm{QCE}} with the weights of line L2 is exactly the sum of the atom energies defined above, by a count of the bonds and elements that each atom touches. Second, if every atom is a nonlocal repatom, cb=1c_b = 1 for every bond and we=0w_e = 0 for every element, so QC is full atomistics. Third, the patch test: at a uniform state y=FXy = F X, the force-based residual is zero at every free repatom whose neighbors exist, because the atomistic forces cancel by symmetry and each local repatom gets ±W′(F)/a\pm W'(F) / a from its two elements. The energy-based form fails the patch test when the potential reaches beyond nearest neighbors, with the ghost forces of the example. Fourth, Newton's method converges to the minimizer of EQCEE_{\mathrm{QCE}} (or to the zero of the QCF residual) quadratically from a start close enough, when KK is nonsingular there, which is the standard result for Newton's method. The proof does not bound the error of QC against full atomistics. Such bounds are theorems of the numerical analysis literature (see Luskin and Ortner 2013) under stability hypotheses.

Proof: The energy of the quasicontinuum chain, its exact limit, the patch test and the Newton iterationfull

We use the chain of the page. Atoms 0,…,N−10, \dots, N - 1 have reference sites Xi=iaX_i = i a. The bonds are (i,i+1)(i, i+1) and (i,i+2)(i, i+2), with a pair potential φ\varphi that is twice continuously differentiable on (0,∞)(0, \infty) and a scale factor sbs_b per bond. The repatoms R={r0<r1<⋯<rn−1}R = \{r_0 < r_1 < \dots < r_{n-1}\} contain 00 and N−1N - 1, the nonlocal set A⊂RA \subset R contains 00 and N−1N - 1, and every bond with sb≠1s_b \ne 1 has both ends in AA. The interpolation is y=Tzy = T z (line L1), the elements are ek=(rk,rk+1)e_k = (r_k, r_{k+1}) with nk=rk+1−rkn_k = r_{k+1} - r_k and Fk=(zk+1−zk)/(nka)F_k = (z_{k+1} - z_k) / (n_k a), and W(F)=φ(Fa)+φ(2Fa)W(F) = \varphi(F a) + \varphi(2 F a). We assume exact arithmetic.

Definition (atom energies). For a nonlocal atom ii, εi=12∑b∋isbφ(ℓb)\varepsilon_i = \frac12 \sum_{b \ni i} s_b \varphi(\ell_b), where ℓb=yj−yi\ell_b = y_j - y_i is the length of the bond b=(i,j)b = (i, j) at y=Tzy = T z. For a local atom ii strictly inside the element eke_k, εi=W(Fk)\varepsilon_i = W(F_k). For a local repatom rkr_k, εi=12(W(Fk−1)+W(Fk))\varepsilon_i = \frac12 (W(F_{k-1}) + W(F_k)); it has two elements because the ends are nonlocal.

Lemma 1 (the weights). With cbc_b and wkw_k of line L2, ∑iεi=∑bcbsbφ(ℓb)+∑kwkW(Fk)=EQCE(z)\sum_i \varepsilon_i = \sum_b c_b s_b \varphi(\ell_b) + \sum_k w_k W(F_k) = E_{\mathrm{QCE}}(z).

Proof. Split the sum over atoms into nonlocal and local atoms. The nonlocal part is ∑i∈A12∑b∋isbφ(ℓb)\sum_{i \in A} \frac12 \sum_{b \ni i} s_b \varphi(\ell_b). Exchange the two sums: the bond bb appears once for each of its ends in AA, with the factor 12\frac12, so its weight is 12#(b∩A)=cb\frac12 \#(b \cap A) = c_b. In the local part, the term W(Fk)W(F_k) comes from the nk−1n_k - 1 atoms strictly inside eke_k, each with weight 11, and from each end of eke_k that is a local repatom, with weight 12\frac12. Each end of eke_k is in AA or is a local repatom, so the weight is nk−1+12(2−#(ek∩A))=nk−12#(ek∩A)=wkn_k - 1 + \frac12 (2 - \#(e_k \cap A)) = n_k - \frac12 \#(e_k \cap A) = w_k. □\square

Lemma 2 (the exact limit). If R=A={0,…,N−1}R = A = \{0, \dots, N - 1\}, then T=IT = I and EQCE(z)=E(z)E_{\mathrm{QCE}}(z) = E(z) for all zz.

Proof. Every atom is a repatom, so line L1 gives yi=ziy_i = z_i. Both ends of every bond are in AA, so cb=1c_b = 1. Every element has nk=1n_k = 1 and two ends in AA, so wk=1−1=0w_k = 1 - 1 = 0. Then EQCE(z)=∑bsbφ(zj−zi)=E(z)E_{\mathrm{QCE}}(z) = \sum_b s_b \varphi(z_j - z_i) = E(z). □\square

So the iteration of lines L3 to L9 is Newton's method on the full energy in this case, and QC can be refined to full atomistics.

Lemma 3 (the patch test for the force-based form). Let sb=1s_b = 1 for all bonds and let zk=Farkz_k = F a r_k for some F>0F > 0, so that y=FXy = F X. Then the QCF residual is zero at every repatom rkr_k with 2≤rk≤N−32 \le r_k \le N - 3.

Proof. For a nonlocal repatom ii with 2≤i≤N−32 \le i \le N - 3, the atoms i±1i \pm 1 and i±2i \pm 2 exist. At y=FXy = F X the bonds to i+1i + 1 and i−1i - 1 have the same length FaF a, and their forces on ii are φ′(Fa)\varphi'(F a) and −φ′(Fa)-\varphi'(F a); the same holds for i±2i \pm 2 with φ′(2Fa)\varphi'(2 F a). So the atomistic force on ii is zero. For a local repatom rkr_k, the local energy ∑mnmW(Fm)\sum_m n_m W(F_m) has the derivative −nkW′(Fk)/(nka)+nk−1W′(Fk−1)/(nk−1a)=(W′(Fk−1)−W′(Fk))/a-n_k W'(F_k) / (n_k a) + n_{k-1} W'(F_{k-1}) / (n_{k-1} a) = (W'(F_{k-1}) - W'(F_k)) / a with respect to zkz_k, and Fk−1=Fk=FF_{k-1} = F_k = F, so it is zero. □\square

Lemma 4 (ghost forces of the energy-based form). Let all atoms be repatoms, let the nonlocal atoms be i≤pi \le p and the local atoms p+1≤i≤qp + 1 \le i \le q inside a long chain, with sb=1s_b = 1 and y=FXy = F X. Then the force fk=−∂EQCE/∂ykf_k = -\partial E_{\mathrm{QCE}} / \partial y_k is −12φ′(2Fa)-\frac12 \varphi'(2 F a) at k=p−1k = p - 1, 12φ′(2Fa)\frac12 \varphi'(2 F a) at k=pk = p and k=p+1k = p + 1, −12φ′(2Fa)-\frac12 \varphi'(2 F a) at k=p+2k = p + 2, and zero at other atoms at a distance of more than two from both interfaces.

Proof. Shift the indices so that p=0p = 0. With nk=1n_k = 1, the element (i,i+1)(i, i + 1) contributes wi(φ(ℓ)+φ(2ℓ))w_i (\varphi(\ell) + \varphi(2 \ell)) with ℓ=yi+1−yi\ell = y_{i+1} - y_i. The coefficient of φ(yi+1−yi)\varphi(y_{i+1} - y_i) is c(i,i+1)+wic_{(i,i+1)} + w_i, which is 1+01 + 0 for i≤−1i \le -1, 12+12\frac12 + \frac12 for i=0i = 0, and 0+10 + 1 for i≥1i \ge 1. So the nearest neighbor terms are those of EE, and their forces cancel at y=FXy = F X as in Lemma 3. The other terms are ∑iciφ(yi+2−yi)\sum_i c_i \varphi(y_{i+2} - y_i) with ci=c(i,i+2)c_i = c_{(i, i+2)} equal to 11 for i≤−2i \le -2, 12\frac12 for i∈{−1,0}i \in \{-1, 0\} and 00 for i≥1i \ge 1, and ∑iwiφ(2(yi+1−yi))\sum_i w_i \varphi(2 (y_{i+1} - y_i)). At y=FXy = F X each argument is 2Fa2 F a. The derivative of the first sum with respect to yky_k is (ck−2−ck)φ′(2Fa)(c_{k-2} - c_k) \varphi'(2 F a), and that of the second is 2(wk−1−wk)φ′(2Fa)2 (w_{k-1} - w_k) \varphi'(2 F a). So fk=φ′(2Fa)(ck−ck−2+2wk−2wk−1)f_k = \varphi'(2 F a) (c_k - c_{k-2} + 2 w_k - 2 w_{k-1}). Insert the values: k=−1k = -1 gives 12−1+0−0=−12\frac12 - 1 + 0 - 0 = -\frac12; k=0k = 0 gives 12−1+1−0=12\frac12 - 1 + 1 - 0 = \frac12; k=1k = 1 gives 0−12+2−1=120 - \frac12 + 2 - 1 = \frac12; k=2k = 2 gives 0−12+2−2=−120 - \frac12 + 2 - 2 = -\frac12; k≤−2k \le -2 gives 1−1+0−0=01 - 1 + 0 - 0 = 0; k≥3k \ge 3 gives 0−0+2−2=00 - 0 + 2 - 2 = 0. □\square

Lemma 4 shows that QCE fails the patch test whenever φ′(2Fa)≠0\varphi'(2 F a) \ne 0, and with nearest neighbors only the second neighbor terms are absent, so the forces are zero.

Lemma 5 (the Newton iteration). Let G(z)G(z) be the gradient of EQCEE_{\mathrm{QCE}} (or the QCF residual) restricted to the free repatoms, with the fixed repatoms held at their values. Lines L5 and L6 compute GG and its Jacobian KK exactly. If G(z∗)=0G(z^*) = 0, K(z∗)K(z^*) is nonsingular and KK is Lipschitz near z∗z^*, then for a start close enough to z∗z^* the iterates of lines L4 to L8 converge to z∗z^* quadratically, and a returned zz satisfies max⁡∣G(z)∣<tol\max |G(z)| < \mathrm{tol}.

Proof. The energy is a sum of terms φ(ℓ)\varphi(\ell) with ℓ\ell linear in zz (through TT), and of terms W(Fk)W(F_k) with FkF_k linear in zz. By the chain rule, the gradient of c φ(ℓ)c\, \varphi(\ell) is c φ′(ℓ) ∇zℓc\, \varphi'(\ell)\, \nabla_z \ell, and its Hessian is c φ′′(ℓ) ∇zℓ ∇zℓTc\, \varphi''(\ell)\, \nabla_z \ell\, \nabla_z \ell^{\mathsf T}, because ℓ\ell is linear in zz. For a bond (i,j)(i, j), ∇zℓ=TT(ej−ei)\nabla_z \ell = T^{\mathsf T}(e_j - e_i), which is what line L5 adds for the bonds and line L6 for their Hessians; the elements are the same with ∇zFk=(ek+1−ek)/(nka)\nabla_z F_k = (e_{k+1} - e_k) / (n_k a). For QCF the residual rows are the same expressions restricted to the rows of the nonlocal or local repatoms, so KK is again the exact Jacobian. Lines L7 and L8 are then the Newton step z←z−K−1Gz \leftarrow z - K^{-1} G on the free variables, and the local quadratic convergence is the standard theorem for Newton's method under the stated hypotheses. The loop returns only when the test of line L9 holds. □\square

Theorem. The procedure returns a stationary point of EQCEE_{\mathrm{QCE}} (or a zero of the QCF residual) on the free repatoms whenever its Newton iteration converges. That point is the exact atomistic equilibrium when every atom is a nonlocal repatom. For uniform deformations, QCF reproduces the exact zero forces, and QCE has the ghost forces of Lemma 4 when second neighbor bonds are present.

Proof. Lemma 5 gives the first claim, Lemma 2 the second, and Lemmas 3 and 4 the third. ■\blacksquare

Complexity

In the real RAM model, one iteration computes y=Tzy = T z in O(N)O(N), the atomistic part in O(∣A∣)O(|A|) (a bounded number of bonds per nonlocal atom), the element part in O(n)O(n), and the Newton step. The implementation solves with dense Gaussian elimination, O(n3)O(n^3), so the cost is O(I(N+n3))O(I (N + n^3)) for II Newton steps. The Hessian couples only repatoms within the cutoff of each other, so in one dimension it is banded and a banded solve takes O(n)O(n); in two and three dimensions sparse solvers apply as for finite elements. A production code never forms yy for all atoms: it needs only the positions of the atoms near the nonlocal repatoms, so the cost of an iteration scales with nn and not with NN. The memory is O(N+n2)O(N + n^2) here and O(n)O(n) with sparse storage.

Properties

  • Exact limit. With every atom a nonlocal repatom, QC is full atomistics (Correctness, part two).
  • Ghost forces (theorem, for this chain). QCE has nonzero forces at the uniform state when the potential reaches beyond nearest neighbors. With nearest neighbors only, there are none.
  • Energy or forces. QCE has an energy, a symmetric Hessian and a variational structure. QCF has no ghost forces but no energy, so a minimizer, a line search or an energy barrier is not defined for it, and its Jacobian is not symmetric.
  • Local errors. In the example, the QCE error sits at the interface, not at the defect. The QCF error depends on the size of the nonlocal region around the defect.
  • Uniform elements. Each element has one deformation gradient. The Cauchy-Born rule assumes a simple lattice; complex lattices need the inner shifts of the Cauchy-Born page.

Variants and improvements

  • Ghost force correction. Shenoy and coauthors (1999) compute the ghost forces at the reference state and add their negative as a fixed load. This removes the ghost forces at the reference state, but not at other states.
  • Force-based QC. QCF zeroes the forces without an energy; Dobson and Luskin (2008) analyze it. It passes the patch test, as in the example.
  • Consistent energies. Several energy-based couplings change the energy of the atoms near the interface so that the uniform state has no ghost forces. Miller and Tadmor (2009) compare fourteen coupling methods, energy-based and force-based, in one framework on one benchmark.
  • Adaptive meshes. The mesh is refined to full atomistic resolution where the strain changes fast, for example ahead of a moving dislocation, and coarsened elsewhere.
  • Finite temperature and dynamics. Extensions use free energies in place of the energy in the local region, or couple to molecular dynamics; see the chapters on dynamics in Tadmor and Miller (2011).

When to use it

Use QC for a static or slowly loaded problem in a crystal with a few localized defects in a large region of smooth deformation: nanoindentation, a crack tip, the core of a dislocation, a grain boundary. Use full molecular dynamics when the defects move fast or fill the volume, or when temperature matters. Use the heterogeneous multiscale method or the FE2 method when the continuum constitutive law itself is the unknown everywhere, not near one defect. Use peridynamics when many cracks grow and the fine scale is not a lattice.

Pitfalls

  • Full weights on interface bonds. If line L2 gives weight 11 to every bond that touches AA and we=new_e = n_e to every element, the bonds across the interface are counted twice. The right weights are cb=12#(b∩A)c_b = \frac12 \#(b \cap A) and we=ne−12#(e∩A)w_e = n_e - \frac12 \#(e \cap A), which give the sum of the atom energies.
  • A symmetric solver for QCF. The QCF Jacobian is not symmetric, so Cholesky or conjugate gradients in line L7 can fail. Use an LU solve (Gaussian elimination with pivoting) or GMRES for QCF.
  • A nonlocal region that is too small. The strain must be close to uniform in each local element. With two nonlocal atoms on each side of the weak bond, the QCF error in the example is a hundred times larger than with eight. Refine where the strain changes.
  • Error checks only at the defect. The QCE error in the example is largest at an interface far from the defect. Compare with full atomistics over the whole chain on a small problem.
  • An interpolated atom in a nonlocal bond. Bonds of nonlocal atoms that reach into a coarse element use interpolated positions. Refine the mesh to full resolution within one cutoff of the nonlocal region.
  • Large strains. The local energy W(F)W(F) loses convexity where the lattice becomes unstable, and the Cauchy-Born rule then fails; see the Cauchy-Born rule.

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.

quasicontinuum_method.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/quasicontinuum-method/. The authors are listed in prov/7F8PW8.jsonl.
"""The quasicontinuum method on a one-dimensional chain of atoms.

The chain has atoms 0, 1, ..., N - 1 at the reference sites X_i = i a,
with a pair potential on the nearest neighbor bonds (i, i + 1) and, if
nnn is true, on the second neighbor bonds (i, i + 2). A bond can carry a
scale factor (a weak bond is a simple defect).

The repatoms are a sorted list R of atom indices. The positions of all
atoms follow from the repatom positions z by linear interpolation,
y = T z. A subset A of the repatoms is nonlocal (atomistic). The other
atoms are local: their energy is the Cauchy-Born energy per atom
W(F) = phi(F a) + phi(2 F a) of the element that holds them.

Energy-based QC (QCE, Tadmor, Ortiz and Phillips 1996, with the local and
nonlocal repatoms of Shenoy et al. 1999):

    E_QCE(z) = sum over bonds b of c_b phi_b(y_j - y_i)
             + sum over elements e of w_e W(F_e),

    c_b = (number of ends of b in A) / 2,
    w_e = n_e - (number of ends of e in A) / 2,

where n_e is the number of lattice spacings in the element and F_e is its
deformation gradient. This is the sum of the atom energies: half of each
bond for a nonlocal atom, W(F) for a local atom inside an element, and
the mean of W over the two elements for a local repatom.

Force-based QC (QCF): the force on a nonlocal repatom is the exact
atomistic force at y = T z, and the force on a local repatom is the force
of the pure local energy sum n_e W(F_e). QCF has no energy, so its
Newton matrix is not symmetric.

A pair potential is a function r -> (phi(r), phi'(r), phi''(r)).
The two end atoms must be nonlocal repatoms, and the caller lists the
fixed repatoms (the boundary conditions).
"""

from typing import Callable, Sequence

import scimat

Pair = Callable[[float], tuple[float, float, float]]


def lennard_jones(r: float, epsilon: float = 1.0, sigma: float = 1.0) -> tuple[float, float, float]:
    """phi(r) = 4 epsilon ((sigma/r)^12 - (sigma/r)^6) and its first two derivatives."""
    s6 = (sigma / r) ** 6
    s12 = s6 * s6
    return (4.0 * epsilon * (s12 - s6),
            4.0 * epsilon * (-12.0 * s12 + 6.0 * s6) / r,
            4.0 * epsilon * (156.0 * s12 - 42.0 * s6) / (r * r))


class Chain:
    """A chain of n atoms with spacing a, a pair potential, and optional weak bonds."""

    def __init__(self, n: int, a: float, pair: Pair, nnn: bool = True,
                 scale: dict | None = None) -> None:
        self.n = n
        self.a = a
        self.pair = pair
        self.nnn = nnn
        self.scale = dict(scale or {})

    def bonds(self) -> list[tuple[int, int, float]]:
        """All bonds (i, j, s) with i < j and scale factor s."""
        out = []
        reach = 2 if self.nnn else 1
        for i in range(self.n):
            for j in range(i + 1, min(i + reach, self.n - 1) + 1):
                out.append((i, j, self.scale.get((i, j), 1.0)))
        return out

    def cauchy_born(self, f: float) -> tuple[float, float, float]:
        """W(F) per atom for the uniform state y = F X, and W'(F), W''(F)."""
        a = self.a
        v1, d1, s1 = self.pair(f * a)
        w, dw, d2w = v1, a * d1, a * a * s1
        if self.nnn:
            v2, d2, s2 = self.pair(2.0 * f * a)
            w, dw, d2w = w + v2, dw + 2.0 * a * d2, d2w + 4.0 * a * a * s2
        return w, dw, d2w


def interpolation(n: int, rep: Sequence[int]) -> list[list[tuple[int, float]]]:
    """Row i of T as a list of (repatom index k, weight): y_i = sum w z_k."""
    rows: list[list[tuple[int, float]]] = []
    k = 0
    for i in range(n):
        while k + 1 < len(rep) and rep[k + 1] <= i:
            k += 1
        p = rep[k]
        if p == i:
            rows.append([(k, 1.0)])
        else:
            q = rep[k + 1]
            w = (i - p) / (q - p)
            rows.append([(k, 1.0 - w), (k + 1, w)])
    return rows


def _check(chain: Chain, rep: Sequence[int], nonlocal_set: set) -> None:
    if list(rep) != sorted(set(rep)) or rep[0] != 0 or rep[-1] != chain.n - 1:
        raise ValueError("repatoms must be sorted, distinct, and contain both ends")
    if not nonlocal_set <= set(rep) or 0 not in nonlocal_set or chain.n - 1 not in nonlocal_set:
        raise ValueError("nonlocal atoms must be repatoms and contain both ends")
    for (i, j), s in chain.scale.items():
        if s != 1.0 and not (i in nonlocal_set and j in nonlocal_set):
            raise ValueError("a scaled bond must join two nonlocal atoms")


def positions(t_rows, z: Sequence[float]) -> list[float]:
    """y = T z."""
    return [sum(w * z[k] for k, w in row) for row in t_rows]


def qce_weights(chain: Chain, rep: Sequence[int], nonlocal_set: set):
    """The bond weights c_b (bonds with c_b > 0 only) and the element weights w_e."""
    cb = []
    for i, j, s in chain.bonds():
        c = 0.5 * ((i in nonlocal_set) + (j in nonlocal_set))
        if c > 0.0:
            cb.append((i, j, c * s))
    we = []
    for k in range(len(rep) - 1):
        p, q = rep[k], rep[k + 1]
        we.append((q - p) - 0.5 * ((p in nonlocal_set) + (q in nonlocal_set)))
    return cb, we


def _add_bond(t_rows, g, kmat, i, j, dv, d2v):
    """Add the gradient and Hessian of one bond energy, pulled back by T."""
    for a_idx, sa in ((i, -1.0), (j, 1.0)):
        for k, w in t_rows[a_idx]:
            g[k] += sa * w * dv
            if kmat is not None:
                for b_idx, sb in ((i, -1.0), (j, 1.0)):
                    for m, u in t_rows[b_idx]:
                        kmat[k][m] += sa * sb * w * u * d2v


def qce_energy(chain: Chain, rep, nonlocal_set, z) -> float:
    """E_QCE(z)."""
    t_rows = interpolation(chain.n, rep)
    y = positions(t_rows, z)
    cb, we = qce_weights(chain, rep, nonlocal_set)
    e = sum(c * chain.pair(y[j] - y[i])[0] for i, j, c in cb)
    for k, w in enumerate(we):
        if w != 0.0:
            ne = rep[k + 1] - rep[k]
            e += w * chain.cauchy_born((z[k + 1] - z[k]) / (ne * chain.a))[0]
    return e


def qce_gradient_hessian(chain: Chain, rep, nonlocal_set, z, hessian: bool = True):
    """The gradient of E_QCE with respect to z and, if asked, its Hessian."""
    m = len(rep)
    t_rows = interpolation(chain.n, rep)
    y = positions(t_rows, z)
    cb, we = qce_weights(chain, rep, nonlocal_set)
    g = [0.0] * m
    kmat = [[0.0] * m for _ in range(m)] if hessian else None
    for i, j, c in cb:
        _, dv, d2v = chain.pair(y[j] - y[i])
        _add_bond(t_rows, g, kmat, i, j, c * dv, c * d2v)
    for k, w in enumerate(we):
        if w == 0.0:
            continue
        h = (rep[k + 1] - rep[k]) * chain.a
        _, dw, d2w = chain.cauchy_born((z[k + 1] - z[k]) / h)
        g[k] -= w * dw / h
        g[k + 1] += w * dw / h
        if kmat is not None:
            s = w * d2w / (h * h)
            kmat[k][k] += s
            kmat[k + 1][k + 1] += s
            kmat[k][k + 1] -= s
            kmat[k + 1][k] -= s
    return g, kmat


def qcf_residual_jacobian(chain: Chain, rep, nonlocal_set, z):
    """QCF: minus the forces on the repatoms, and the Jacobian of that residual."""
    m = len(rep)
    t_rows = interpolation(chain.n, rep)
    y = positions(t_rows, z)
    index = {p: k for k, p in enumerate(rep)}
    r = [0.0] * m
    jac = [[0.0] * m for _ in range(m)]
    for i, j, s in chain.bonds():
        for atom, sa in ((i, -1.0), (j, 1.0)):
            if atom not in nonlocal_set:
                continue
            k = index[atom]
            _, dv, d2v = chain.pair(y[j] - y[i])
            r[k] += sa * s * dv
            for b_idx, sb in ((i, -1.0), (j, 1.0)):
                for mm, u in t_rows[b_idx]:
                    jac[k][mm] += sa * sb * u * s * d2v
    for k in range(m - 1):
        h = (rep[k + 1] - rep[k]) * chain.a
        _, dw, d2w = chain.cauchy_born((z[k + 1] - z[k]) / h)
        ne = rep[k + 1] - rep[k]
        for kk, sk in ((k, -1.0), (k + 1, 1.0)):
            if rep[kk] in nonlocal_set:
                continue
            r[kk] += sk * ne * dw / h
            jac[kk][k] -= sk * ne * d2w / (h * h)
            jac[kk][k + 1] += sk * ne * d2w / (h * h)
    return r, jac


def quasicontinuum(chain: Chain, rep: Sequence[int], nonlocal_set, z0: Sequence[float],
                   fixed: Sequence[int], method: str = "qce", tol: float = 1e-10,
                   max_iter: int = 50) -> tuple[list[float], list[float]]:
    """Solve for the repatom positions z by Newton's method.

    rep: sorted repatom indices; nonlocal_set: the nonlocal repatoms;
    z0: start positions of the repatoms (the fixed ones keep their value);
    fixed: indices into rep of the fixed repatoms; method: "qce" (minimize
    E_QCE) or "qcf" (zero the QCF forces). Return (z, y) with y = T z.
    """
    nonlocal_set = set(nonlocal_set)
    _check(chain, rep, nonlocal_set)
    t_rows = interpolation(chain.n, rep)                                 # @line L1
    if method == "qce":
        qce_weights(chain, rep, nonlocal_set)                            # @line L2
    z = [float(v) for v in z0]
    free = [k for k in range(len(rep)) if k not in set(fixed)]
    for _ in range(max_iter):                                            # @line L3
        y = positions(t_rows, z)                                         # @line L4
        if method == "qce":
            g, kmat = qce_gradient_hessian(chain, rep, nonlocal_set, z)  # @line L5
        else:
            g, kmat = qcf_residual_jacobian(chain, rep, nonlocal_set, z)
        gf = [g[k] for k in free]
        if max(abs(v) for v in gf) < tol:                                # @line L9
            return z, y                                                  # @line L10
        kff = [[kmat[k][m] for m in free] for k in free]                 # @line L6
        delta = scimat.solve(kff, [-v for v in gf])                      # @line L7
        for k, d in zip(free, delta):                                    # @line L8
            z[k] += d
    raise RuntimeError("Newton iteration did not converge")


def full_atomistic(chain: Chain, y0: Sequence[float], fixed: Sequence[int],
                   tol: float = 1e-10) -> list[float]:
    """The exact atomistic equilibrium: QC with every atom a nonlocal repatom."""
    rep = list(range(chain.n))
    z, _ = quasicontinuum(chain, rep, set(rep), y0, fixed, "qce", tol)
    return z
scimat.py 227 lines
# SPDX-License-Identifier: MIT
# Shared helper of the scientific-computing pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small dense linear algebra and error norms for the scientific-computing pages.

A matrix is a list of rows and a vector is a list. Entries may be int,
float or fractions.Fraction. The routines that do not take a square root
(solve, inv, det and the arithmetic) keep Fraction entries exact.
cholesky, cholesky_solve and norm2 take square roots and return floats.

API (fixed; other pages copy this file byte for byte):
    zeros(m, n=None)        m by n zero matrix (n = m if not given)
    eye(n)                  n by n identity
    add(A, B), sub(A, B)    entrywise sum and difference (vectors or matrices)
    scale(c, A)             c times A (vector or matrix)
    matmul(A, B)            matrix product
    matvec(A, x)            matrix times vector
    transpose(A)            transpose
    dot(x, y)               inner product of two vectors
    norm2(x)                Euclidean norm of a vector, as a float
    outer(x, y)             outer product x y^T
    solve(A, b)             Gaussian elimination with partial pivoting;
                            b is a vector or a matrix of right sides
    inv(A)                  inverse of A
    det(A)                  determinant of A
    cholesky(A)             lower triangular L with A = L L^T (floats)
    cholesky_solve(L, b)    solve L L^T x = b for a vector b
    err_l1(e, dx=1)         sum |e_j| dx
    err_l2(e, dx=1)         sqrt(sum e_j^2 dx), as a float
    err_linf(e, dx=1)       max |e_j| (dx is not used)
    observed_order(errors)  [log2(E_i / E_(i+1)) for successive errors]
"""

import math


def zeros(m, n=None):
    """Return an m by n matrix of zeros (n = m if n is None)."""
    if n is None:
        n = m
    return [[0] * n for _ in range(m)]


def eye(n):
    """Return the n by n identity matrix."""
    out = zeros(n, n)
    for i in range(n):
        out[i][i] = 1
    return out


def _is_matrix(a):
    return len(a) > 0 and isinstance(a[0], list)


def add(a, b):
    """Return a + b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x + y for x, y in zip(a, b)]


def sub(a, b):
    """Return a - b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x - y for x, y in zip(a, b)]


def scale(c, a):
    """Return c times a, for a vector or a matrix a."""
    if _is_matrix(a):
        return [[c * x for x in row] for row in a]
    return [c * x for x in a]


def transpose(a):
    """Return the transpose of the matrix a."""
    return [list(col) for col in zip(*a)]


def matmul(a, b):
    """Return the matrix product a b."""
    bt = transpose(b)
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def matvec(a, x):
    """Return the product of the matrix a and the vector x."""
    return [sum(aij * xj for aij, xj in zip(row, x)) for row in a]


def dot(x, y):
    """Return the inner product of the vectors x and y."""
    return sum(a * b for a, b in zip(x, y))


def norm2(x):
    """Return the Euclidean norm of the vector x, as a float."""
    return math.sqrt(float(dot(x, x)))


def outer(x, y):
    """Return the outer product x y^T as a matrix."""
    return [[a * b for b in y] for a in x]


def _eliminate(a, rhs):
    """Reduce a to upper triangular form with partial pivoting.

    a is a copy of the square matrix, rhs a list of right side rows (one
    row per row of a) that receives the same row operations. Return the
    number of row swaps. Raise ValueError if a pivot is zero.
    """
    n = len(a)
    swaps = 0
    for k in range(n):
        p = max(range(k, n), key=lambda i: abs(a[i][k]))
        if a[p][k] == 0:
            raise ValueError("matrix is singular")
        if p != k:
            a[k], a[p] = a[p], a[k]
            rhs[k], rhs[p] = rhs[p], rhs[k]
            swaps += 1
        for i in range(k + 1, n):
            f = a[i][k] / a[k][k]
            if f == 0:
                continue
            for j in range(k, n):
                a[i][j] -= f * a[k][j]
            for j in range(len(rhs[i])):
                rhs[i][j] -= f * rhs[k][j]
    return swaps


def solve(a, b):
    """Solve a x = b by Gaussian elimination with partial pivoting.

    b is a vector (the result is a vector) or a matrix with one column per
    right side (the result is a matrix). Fraction entries stay exact.
    Raise ValueError if a is singular.
    """
    n = len(a)
    work = [list(row) for row in a]
    vector = not _is_matrix(b)
    rhs = [[v] for v in b] if vector else [list(row) for row in b]
    _eliminate(work, rhs)
    m = len(rhs[0]) if n else 0
    x = [[0] * m for _ in range(n)]
    for i in range(n - 1, -1, -1):
        for j in range(m):
            s = rhs[i][j]
            for k in range(i + 1, n):
                s -= work[i][k] * x[k][j]
            x[i][j] = s / work[i][i]
    if vector:
        return [row[0] for row in x]
    return x


def inv(a):
    """Return the inverse of the square matrix a."""
    return solve(a, eye(len(a)))


def det(a):
    """Return the determinant of the square matrix a (0 if singular)."""
    work = [list(row) for row in a]
    rhs = [[] for _ in a]
    try:
        swaps = _eliminate(work, rhs)
    except ValueError:
        return 0
    d = -1 if swaps % 2 else 1
    for i in range(len(a)):
        d *= work[i][i]
    return d


def cholesky(a):
    """Return the lower triangular L with a = L L^T, in floats.

    Raise ValueError if a is not symmetric positive definite.
    """
    n = len(a)
    low = [[0.0] * n for _ in range(n)]
    for j in range(n):
        s = float(a[j][j]) - sum(low[j][k] ** 2 for k in range(j))
        if s <= 0.0:
            raise ValueError("matrix is not positive definite")
        low[j][j] = math.sqrt(s)
        for i in range(j + 1, n):
            t = float(a[i][j]) - sum(low[i][k] * low[j][k] for k in range(j))
            low[i][j] = t / low[j][j]
    return low


def cholesky_solve(low, b):
    """Solve L L^T x = b, with L from cholesky, for a vector b."""
    n = len(low)
    y = [0.0] * n
    for i in range(n):
        y[i] = (float(b[i]) - sum(low[i][k] * y[k] for k in range(i))) / low[i][i]
    x = [0.0] * n
    for i in range(n - 1, -1, -1):
        x[i] = (y[i] - sum(low[k][i] * x[k] for k in range(i + 1, n))) / low[i][i]
    return x


def err_l1(e, dx=1):
    """Return the discrete L1 norm sum |e_j| dx."""
    return sum(abs(v) for v in e) * dx


def err_l2(e, dx=1):
    """Return the discrete L2 norm sqrt(sum e_j^2 dx), as a float."""
    return math.sqrt(float(sum(v * v for v in e) * dx))


def err_linf(e, dx=1):
    """Return the max norm max |e_j|. dx is accepted for a uniform call and not used."""
    return max(abs(v) for v in e)


def observed_order(errors):
    """Return [log2(E_i / E_(i+1))] for a list of errors on meshes h, h/2, h/4, ..."""
    return [math.log2(float(errors[i]) / float(errors[i + 1])) for i in range(len(errors) - 1)]
test_quasicontinuum_method.py 157 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/quasicontinuum-method/. The authors are listed in prov/7F8PW8.jsonl.
import random

import pytest

from quasicontinuum_method import (Chain, full_atomistic, interpolation, lennard_jones, positions,
                                   qce_energy, qce_gradient_hessian, qcf_residual_jacobian,
                                   quasicontinuum)

A0 = 1.1196108663112254  # equilibrium spacing of the LJ chain with first and second neighbors


def full_energy(chain, y):
    return sum(s * chain.pair(y[j] - y[i])[0] for i, j, s in chain.bonds())


def atom_energy_sum(chain, rep, nonlocal_set, z):
    """Oracle for E_QCE: add the energy of each atom, one atom at a time."""
    t_rows = interpolation(chain.n, rep)
    y = positions(t_rows, z)
    total = 0.0
    for i in range(chain.n):
        if i in nonlocal_set:
            total += 0.5 * sum(s * chain.pair(y[q] - y[p])[0]
                               for p, q, s in chain.bonds() if i in (p, q))
            continue
        k = max(k for k, p in enumerate(rep) if p <= i)
        if rep[k] == i:
            ws = []
            for e in (k - 1, k):
                h = (rep[e + 1] - rep[e]) * chain.a
                ws.append(chain.cauchy_born((z[e + 1] - z[e]) / h)[0])
            total += 0.5 * (ws[0] + ws[1])
        else:
            h = (rep[k + 1] - rep[k]) * chain.a
            total += chain.cauchy_born((z[k + 1] - z[k]) / h)[0]
    return total


def random_mesh(rng, n):
    nonlocal_set = set(range(0, 3)) | set(range(n - 3, n))
    mid = rng.randrange(8, n - 12)
    nonlocal_set |= set(range(mid, mid + rng.randrange(1, 5)))
    rep = set(nonlocal_set)
    for i in range(n):
        if rng.random() < 0.3:
            rep.add(i)
    return sorted(rep), nonlocal_set


def test_all_atoms_nonlocal_is_full_atomistics():
    rng = random.Random(1)
    chain = Chain(25, A0, lennard_jones, True, {(12, 13): 0.5})
    rep = list(range(25))
    y = [A0 * i + rng.uniform(-0.02, 0.02) for i in range(25)]
    assert qce_energy(chain, rep, set(rep), y) == pytest.approx(full_energy(chain, y), rel=1e-13)


@pytest.mark.parametrize("seed", range(6))
def test_energy_equals_sum_of_atom_energies(seed):
    rng = random.Random(seed)
    n = 40
    chain = Chain(n, A0, lennard_jones, nnn=rng.random() < 0.7)
    rep, nonlocal_set = random_mesh(rng, n)
    z = [A0 * 1.01 * p + rng.uniform(-0.01, 0.01) for p in rep]
    assert qce_energy(chain, rep, nonlocal_set, z) == pytest.approx(
        atom_energy_sum(chain, rep, nonlocal_set, z), rel=1e-12)


def test_gradient_and_hessian_match_finite_differences():
    rng = random.Random(7)
    n = 30
    chain = Chain(n, A0, lennard_jones, True)
    rep, nonlocal_set = random_mesh(rng, n)
    z = [A0 * 1.01 * p + rng.uniform(-0.01, 0.01) for p in rep]
    g, kmat = qce_gradient_hessian(chain, rep, nonlocal_set, z)
    e = 1e-6
    for k in range(len(rep)):
        zp, zm = list(z), list(z)
        zp[k] += e
        zm[k] -= e
        fd = (qce_energy(chain, rep, nonlocal_set, zp) - qce_energy(chain, rep, nonlocal_set, zm)) / (2 * e)
        assert g[k] == pytest.approx(fd, abs=1e-6)
        gp, _ = qce_gradient_hessian(chain, rep, nonlocal_set, zp, False)
        gm, _ = qce_gradient_hessian(chain, rep, nonlocal_set, zm, False)
        for m in range(len(rep)):
            assert kmat[m][k] == pytest.approx((gp[m] - gm[m]) / (2 * e), abs=1e-5)


def test_ghost_forces_at_the_reference_lattice():
    n = 31
    nonlocal_set = set(range(0, 11)) | set(range(21, 31))
    rep = list(range(n))
    z = [A0 * i for i in range(n)]
    chain = Chain(n, A0, lennard_jones, True)
    g, _ = qce_gradient_hessian(chain, rep, nonlocal_set, z, False)
    half = 0.5 * lennard_jones(2 * A0)[1]
    expected = {9: -half, 10: half, 11: half, 12: -half, 19: half, 20: -half, 21: -half, 22: half}
    for i in range(2, n - 2):
        assert -g[i] == pytest.approx(expected.get(i, 0.0), abs=1e-12)
    # With nearest neighbors only, or with the force-based coupling, there are no ghost forces.
    g_nn, _ = qce_gradient_hessian(Chain(n, A0, lennard_jones, False), rep, nonlocal_set, z, False)
    r_qcf, _ = qcf_residual_jacobian(chain, rep, nonlocal_set, z)
    for i in range(2, n - 2):
        assert abs(g_nn[i]) < 1e-12
        assert abs(r_qcf[i]) < 1e-12


def defect_problem():
    n = 81
    chain = Chain(n, A0, lennard_jones, True, {(40, 41): 0.5})
    y0 = [1.02 * A0 * i for i in range(n)]
    fixed_atoms = [0, 1, n - 2, n - 1]
    nonlocal_set = set(range(0, 4)) | set(range(32, 50)) | set(range(77, 81))
    rep = sorted(nonlocal_set | set(range(4, 32, 4)) | set(range(50, 77, 4)))
    z0 = [y0[p] for p in rep]
    fixed = [rep.index(p) for p in fixed_atoms]
    exact = full_atomistic(chain, y0, fixed_atoms)
    return chain, rep, nonlocal_set, z0, fixed, exact


def test_weak_bond_qcf_matches_full_atomistics_with_half_the_unknowns():
    chain, rep, nonlocal_set, z0, fixed, exact = defect_problem()
    assert len(rep) == 40
    _, y_qcf = quasicontinuum(chain, rep, nonlocal_set, z0, fixed, "qcf")
    _, y_qce = quasicontinuum(chain, rep, nonlocal_set, z0, fixed, "qce")
    err_qcf = max(abs(p - q) for p, q in zip(y_qcf, exact))
    err_qce = max(abs(p - q) for p, q in zip(y_qce, exact))
    assert err_qcf < 1e-8
    assert 1e-4 < err_qce < 1e-2
    # The weak bond opens more than the mean spacing.
    assert exact[41] - exact[40] > 1.02 * A0 + 0.03


def test_qce_minimizer_has_zero_gradient_and_qcf_keeps_uniform_strain():
    n = 41
    chain = Chain(n, A0, lennard_jones, True)
    nonlocal_set = set(range(0, 4)) | set(range(18, 23)) | set(range(37, 41))
    rep = sorted(nonlocal_set | {6, 9, 12, 15, 26, 30, 34})
    z0 = [1.03 * A0 * p for p in rep]
    fixed = [rep.index(p) for p in (0, 1, n - 2, n - 1)]
    z_qcf, _ = quasicontinuum(chain, rep, nonlocal_set, z0, fixed, "qcf")
    assert max(abs(p - q) for p, q in zip(z_qcf, z0)) < 1e-12
    z_qce, _ = quasicontinuum(chain, rep, nonlocal_set, z0, fixed, "qce")
    g, _ = qce_gradient_hessian(chain, rep, nonlocal_set, z_qce, False)
    free = [k for k in range(len(rep)) if k not in fixed]
    assert max(abs(g[k]) for k in free) < 1e-10
    assert max(abs(p - q) for p, q in zip(z_qce, z0)) > 1e-4


def test_bad_meshes_are_rejected():
    with pytest.raises(ValueError):  # the last atom is not a repatom
        quasicontinuum(Chain(10, A0, lennard_jones), [0, 3, 8], {0, 8}, [0.0, 3.0, 8.0], [0, 2])
    chain = Chain(10, A0, lennard_jones, True, {(4, 5): 0.5})
    with pytest.raises(ValueError):  # the weak bond is in the local region
        quasicontinuum(chain, [0, 4, 5, 9], {0, 9}, [0.0, 4.0, 5.0, 9.0], [0, 3])

History

Tadmor, Ortiz and Phillips introduced the quasicontinuum method in 1996 for the analysis of defects in solids, with the finite element interpolation of atom positions and Cauchy-Born energies for the elements. Shenoy, Miller, Tadmor, Rodney, Phillips and Ortiz gave in 1999 the adaptive formulation with local and nonlocal repatoms, identified the ghost forces at the interface and proposed a correction by fixed forces. Over the next decade many coupling methods followed. Miller and Tadmor (2009) put fourteen of them in one framework and benchmark, and a numerical analysis of consistency and stability grew from work such as Dobson and Luskin (2008), reviewed by Luskin and Ortner (2013).

References

  1. Ellad B. Tadmor, Michael Ortiz and Rob Phillips, Quasicontinuum analysis of defects in solids, Philosophical Magazine A 73(6), 1996, 1529-1563, the representative atoms, the finite element interpolation of the atom positions and the Cauchy-Born energy of the elements
  2. V. B. Shenoy, R. Miller, E. B. Tadmor, D. Rodney, R. Phillips and M. Ortiz, An adaptive finite element approach to atomic-scale mechanics: the quasicontinuum method, Journal of the Mechanics and Physics of Solids 47(3), 1999, 611-642, the local and nonlocal representative atoms, the ghost forces at the interface and their correction, and the adaptive mesh
  3. Ronald E. Miller and Ellad B. Tadmor, A unified framework and performance benchmark of fourteen multiscale atomistic/continuum coupling methods, Modelling and Simulation in Materials Science and Engineering 17(5), 2009, 053001, the energy-based and force-based couplings in one framework, and the benchmark of their errors and costs
  4. Matthew Dobson and Mitchell Luskin, Analysis of a force-based quasicontinuum approximation, ESAIM Mathematical Modelling and Numerical Analysis 42(1), 2008, 113-139, the force-based coupling, which has no ghost forces and no energy
  5. Mitchell Luskin and Christoph Ortner, Atomistic-to-continuum coupling, Acta Numerica 22, 2013, 397-508, the numerical analysis of the couplings, the consistency error of the energy-based coupling and the patch test
  6. Ellad B. Tadmor and Ronald E. Miller, Modeling Materials: Continuum, Atomistic and Multiscale Techniques, Cambridge University Press, 2011, chapter 12 (atomistic-continuum coupling, static methods)

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