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
- Model
- Real RAM
- Properties
- deterministicnot exactiterativenot randomized
- Evidence
- Proof sketchCode in 1 languages
- 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 atoms with reference sites and a potential energy of the positions (here a pair potential with a cutoff), boundary conditions, and a defect. The output is an approximation of the local minimizer of , with about the same accuracy near the defect, but with only unknowns. The page uses a chain: atoms at , nearest neighbor bonds and second neighbor bonds , with energy
where is a scale factor of the bond ( except at the defect). The two atoms at each end are fixed at , which applies a mean stretch .
The QC method chooses a sorted set of repatoms with positions , and a subset of nonlocal repatoms. The positions of all atoms follow by linear interpolation, : an atom between neighboring repatoms gets . Each pair of neighboring repatoms forms an element with lattice spacings and the deformation gradient . The Cauchy-Born energy per atom is 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, for a local atom inside an element, and the mean of over the two elements for a local repatom. Collected bond by bond and element by element, this is
where is the number of ends of bond in . Bonds with drop out, and elements inside the atomistic region have and .
The algorithm
QUASICONTINUUM(φ, R, A, z, fixed, tol)- 1
build 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) - 2
c_b ← (number of ends of bond b in A) / 2, w_e ← n_e - (number of ends of element e in A) / 2 - 3
repeat - 4
y ← T z - 5
g ← 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) - 6
K ← the Hessian of the same energy, restricted to the free repatoms - 7
solve K δ = -g on the free repatoms - 8
z_free ← z_free + δ - 9
until max |g_free| < tol - 10
return 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 . The gradient of line L5 has two parts: the bond forces of the atomistic part, pulled back to the repatoms by (an interpolated atom passes its force to its two repatoms in the ratio of the weights), and the element forces with . The Hessian of line L6 adds for each bond, pulled back by on both sides, and 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 at , with all bonds of atom . For a local repatom, it is the gradient of the pure local energy . These forces are not the gradient of any energy, so is the Jacobian of the residual and is not symmetric.
Example
Ghost forces by hand. Take a long chain at the uniform state , with all atoms as repatoms, the atoms nonlocal and the atoms local. Collect the terms of by the function they contain. The nearest neighbor bond appears with weight , which is for every : for , for and for . So with nearest neighbors only, and there are no ghost forces. The second neighbor terms do not match. The true bonds have the weights for , for and , and for , while the elements add with for , for and for . At the uniform state the derivative of each term is , so the force on atom is
This gives , , , , and for all other . For the Lennard-Jones potential in reduced units, the chain with second neighbors has its equilibrium spacing at , which is . There , so the ghost forces are 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 Lennard-Jones atoms with , the bond scaled by , and the two end atoms on each side fixed at a mean stretch . The full atomistic minimizer, by Newton's method on all 77 free atoms, has the energy and opens the weak bond to , against a mean spacing of . 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 repatoms in place of 81 atoms. From the uniformly stretched start, the free gradient of falls in the Newton steps as
| step | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| () |
which is quadratic convergence. The QCE energy is . The largest error in the atom positions is 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 . With a nonlocal region of only two atoms on each side of the weak bond (32 repatoms), the QCF error grows to , 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, 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, for every bond and for every element, so QC is full atomistics. Third, the patch test: at a uniform state , 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 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 (or to the zero of the QCF residual) quadratically from a start close enough, when 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 have reference sites . The bonds are and , with a pair potential that is twice continuously differentiable on and a scale factor per bond. The repatoms contain and , the nonlocal set contains and , and every bond with has both ends in . The interpolation is (line L1), the elements are with and , and . We assume exact arithmetic.
Definition (atom energies). For a nonlocal atom , , where is the length of the bond at . For a local atom strictly inside the element , . For a local repatom , ; it has two elements because the ends are nonlocal.
Lemma 1 (the weights). With and of line L2, .
Proof. Split the sum over atoms into nonlocal and local atoms. The nonlocal part is . Exchange the two sums: the bond appears once for each of its ends in , with the factor , so its weight is . In the local part, the term comes from the atoms strictly inside , each with weight , and from each end of that is a local repatom, with weight . Each end of is in or is a local repatom, so the weight is .
Lemma 2 (the exact limit). If , then and for all .
Proof. Every atom is a repatom, so line L1 gives . Both ends of every bond are in , so . Every element has and two ends in , so . Then .
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 for all bonds and let for some , so that . Then the QCF residual is zero at every repatom with .
Proof. For a nonlocal repatom with , the atoms and exist. At the bonds to and have the same length , and their forces on are and ; the same holds for with . So the atomistic force on is zero. For a local repatom , the local energy has the derivative with respect to , and , so it is zero.
Lemma 4 (ghost forces of the energy-based form). Let all atoms be repatoms, let the nonlocal atoms be and the local atoms inside a long chain, with and . Then the force is at , at and , at , and zero at other atoms at a distance of more than two from both interfaces.
Proof. Shift the indices so that . With , the element contributes with . The coefficient of is , which is for , for , and for . So the nearest neighbor terms are those of , and their forces cancel at as in Lemma 3. The other terms are with equal to for , for and for , and . At each argument is . The derivative of the first sum with respect to is , and that of the second is . So . Insert the values: gives ; gives ; gives ; gives ; gives ; gives .
Lemma 4 shows that QCE fails the patch test whenever , and with nearest neighbors only the second neighbor terms are absent, so the forces are zero.
Lemma 5 (the Newton iteration). Let be the gradient of (or the QCF residual) restricted to the free repatoms, with the fixed repatoms held at their values. Lines L5 and L6 compute and its Jacobian exactly. If , is nonsingular and is Lipschitz near , then for a start close enough to the iterates of lines L4 to L8 converge to quadratically, and a returned satisfies .
Proof. The energy is a sum of terms with linear in (through ), and of terms with linear in . By the chain rule, the gradient of is , and its Hessian is , because is linear in . For a bond , , which is what line L5 adds for the bonds and line L6 for their Hessians; the elements are the same with . For QCF the residual rows are the same expressions restricted to the rows of the nonlocal or local repatoms, so is again the exact Jacobian. Lines L7 and L8 are then the Newton step 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.
Theorem. The procedure returns a stationary point of (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.
Complexity
In the real RAM model, one iteration computes in , the atomistic part in (a bounded number of bonds per nonlocal atom), the element part in , and the Newton step. The implementation solves with dense Gaussian elimination, , so the cost is for 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 ; in two and three dimensions sparse solvers apply as for finite elements. A production code never forms for all atoms: it needs only the positions of the atoms near the nonlocal repatoms, so the cost of an iteration scales with and not with . The memory is here and 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 to every bond that touches and to every element, the bonds across the interface are counted twice. The right weights are and , 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 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.
# 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
- 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
- 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
- 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 7F8PW8 Edit this page History Report an error Markdown