INHOMOGENEOUS ELASTICITY · THE CODE EXPLAINED

Equivalent eigenstrain, derived, then coded.

We first derive the method and show why it must work. Then we write the code, with every stress, strain and acoustic-tensor entry as an explicit polynomial in the components. We keep the worked code blocks visible here, so we can follow the implementation step by step. The complete notebook is available on request.

Code use: teaching, learning and demonstration only. Any other use requires my written permission.

We keep the code examples visible below. For the complete notebook, email me and clearly state which code you want, why you need it and how you intend to use it. Request details .

How can a uniform solid have a hole in it?

In the calculation behind the left picture, the solid has the same stiffness everywhere, including inside the circle. Yet the circle behaves like a hole: almost no stress inside, and stress crowding around its sides. What empties it? The right picture shows the trick. A strain that no atom in the real material undergoes, a virtual strain, lives only inside the circle and grows until the stress there has gone.

Stress sigma 11 divided by the applied stress around a circular hole under load along x: near zero inside the hole and raised above and below itVirtual strain v 11, nonzero only inside the circle and zero in the surrounding solid
A circular hole of radius 10 nm in a 256 nm box under a uniaxial stress \(\sigma=160\) MPa along \(x\), seen close up. The black circle marks the hole. The diffuse interface rounds off the peak stress at the hole edge.

So we ask one question: which fictitious strain makes a uniform solid carry the same stress as the real one? Once we can answer it, the Fourier solution for a uniform solid does the rest, for a hole, a free surface, a particle in vacuum and two stiff phases alike.

Why does this matter? In almost every evolving microstructure some region wants to change its size or shape and is held back by the material around it: a misfitting precipitate, a lithium-rich region in a battery particle, a film on a substrate or set free from it, a sintering compact full of pores. Each needs, at every time step of a phase-field simulation, the stress produced by an eigenstrain in a body whose stiffness varies, and vanishes where there is a pore, a free surface or vacuum. This method gives that stress with a few fast Fourier transforms on the same grid as the phase fields.

This page explains the second of the two inhomogeneous elasticity solvers; the first is the direct iterative perturbation. For voids and rigid inclusions of infinite contrast, the augmented Lagrangian and the hard constraint with CG and MINRES are on the homogenization page. The method is the effective stress-free strain approach of Wang, Jin and Khachaturyan (WJK), which Soumya Bandyopadhyay used in his PhD work, in C and on GPUs, for ferroelectric thin films with a free surface. Our \(\boldsymbol\varepsilon^*\) is the physical eigenstrain (their \(\epsilon^*_{ij}\)), our \(\boldsymbol q\) is the virtual part, and \(\boldsymbol\varepsilon^0=\boldsymbol\varepsilon^*+\boldsymbol q\) is their effective stress-free strain \(\epsilon^0_{ij}\). The complete notebook, with every plot, is available on request.

The trick, told by the solid, the hole and the virtual strain

1

A hole has no stiffness

Pull me and the load must flow around the hole. My stiffness drops to zero there.

And zero is no small perturbation of you. A Fourier solver for a uniform solid cannot see me.

2

Fill it, then cheat

So fill the hole with my own stiffness. Now the box is uniform and its strain has a closed form.

And I live only in the hole, as a strain that costs no stress. I grow until the stress in the hole is gone.

3

One unknown left

When I am right, the uniform box carries exactly the stress of the real one, point by point.

So the whole problem is to find q. The rest of this page is how. (The symbol in the picture is \(\tau=-\mathsf C^0\boldsymbol q\), the same unknown as a stress.)

PART 1 · DERIVE

Step 1: The equivalence

A region whose stiffness \(\mathsf C(\boldsymbol r)\) differs from the reference \(\mathsf C^0\) is reproduced by a homogeneous body carrying the stress-free strain \(\boldsymbol\varepsilon^0\), chosen so that the two stresses agree at every point:

\[\mathsf C^0\big(\boldsymbol\varepsilon-\boldsymbol\varepsilon^0\big)=\mathsf C(\boldsymbol r)\big(\boldsymbol\varepsilon-\boldsymbol\varepsilon^*\big),\qquad \boldsymbol q\equiv\boldsymbol\varepsilon^0-\boldsymbol\varepsilon^*.\tag{1}\]

This is Eshelby's equivalent inclusion made into a field equation. It is implicit: the strain \(\boldsymbol\varepsilon\) on both sides depends on \(\boldsymbol\varepsilon^0\) through the elastic solution. Solving it is the whole game, and this page is about how to solve it.

We work in two dimensions (plane strain) on a periodic \(N\times N\) grid of unit spacing, one cell being 1 nm. Symmetric tensors are stored as three-vectors with tensor shear, \(\boldsymbol a=(a_{11},a_{22},a_{12})\), so that \(\boldsymbol a:\boldsymbol b=a_{11}b_{11}+a_{22}b_{22}+2a_{12}b_{12}\). The reference solid has \(\sigma_{11}=C_{11}\varepsilon_{11}+C_{12}\varepsilon_{22}\), \(\sigma_{22}=C_{12}\varepsilon_{11}+C_{11}\varepsilon_{22}\), \(\sigma_{12}=2C_{44}\varepsilon_{12}\). The matrix is a superalloy at high temperature, isotropic with \(\mu=80\) GPa and \(\nu=1/3\), so \(C_{11}=320\), \(C_{12}=160\), \(C_{44}=80\) GPa (1997, 999 and 499 eV/nm³, as on the other elasticity pages). Stresses are in GPa in the code and quoted in MPa.

Loading. Either the mean strain \(\bar{\boldsymbol E}\) is prescribed, or the mean stress \(\boldsymbol\Sigma\) is, and then the mean strain is exactly (WJK Eq. A2)

\[\bar{\boldsymbol E}=\langle\boldsymbol\varepsilon^0\rangle+\mathsf S^0\boldsymbol\Sigma,\qquad \mathsf S^0=(\mathsf C^0)^{-1}.\tag{2}\]

A free body in vacuum has \(\boldsymbol\Sigma=0\). A compatible \(\boldsymbol q\) inside the void changes \(\langle\boldsymbol q\rangle\) without changing any stress, so there we prescribe \(\bar{\boldsymbol E}=0\) instead and read the body's own mean strain from the field.

# ============================================================================================
# Parameters and libraries. NumPy for arrays, Matplotlib for plots, pyFFTW for the transforms.
# Units: GPa for stiffness and stress, grid cells for length.
# ============================================================================================
import numpy as np, time, os, sys, subprocess
try:
    import pyfftw
except ImportError:                                                        # on Colab: install the prebuilt wheel once (a few seconds)
    subprocess.run([sys.executable, '-m', 'pip', 'install', '-q', 'pyfftw'], check=True); import pyfftw
import pyfftw.interfaces.numpy_fft as fft                                  # FFTW behind NumPy's calling conventions, for the occasional one-off transform
pyfftw.config.PLANNER_EFFORT = 'FFTW_MEASURE'                              # time several algorithms once per array shape and keep the fastest
pyfftw.interfaces.cache.enable(); pyfftw.interfaces.cache.set_keepalive_time(300)   # keep the plans of one-off transforms too
FFT_THREADS = min(os.cpu_count(), 8)                                       # FFTW's OpenMP threads; measured: no gain beyond 8 on these grid sizes
import matplotlib.pyplot as plt
np.set_printoptions(precision=4, suppress=True)

QUICK = True          # True: 256^2 hole and 128^2 discs, about 5 minutes.  False: 512^2 hole with a 40-cell radius, about 15 minutes on a laptop.

# ---- material of the reference solid: isotropic, shear modulus mu = 80 GPa, Poisson ratio nu = 1/3 (a superalloy matrix).
# The cubic constants below are what the Green operator and the constitutive maps use; isotropy is the special case C44 = (C11 - C12)/2.
mu, nu = 80.0, 1/3
C44 = mu; C12 = 2*mu*nu/(1-2*nu); C11 = 2*mu*(1-nu)/(1-2*nu)
lam = C12
print(f"C11 = {C11:.1f} GPa, C12 = {C12:.1f} GPa, C44 = {C44:.1f} GPa")

Step 2: One pass, the uniform solid solved exactly

For a stress-free strain field \(\boldsymbol\varepsilon^0\) in the uniform reference solid the strain is known in closed form (Khachaturyan 1983, Ch. 7). With \(\hat{(\cdot)}\) the FFT and \(\boldsymbol k\) the wavevector, one pass is:

  1. eigenstress \(\boldsymbol p=\mathsf C^0\boldsymbol\varepsilon^0\), and its three transforms \(\hat p\);
  2. force \(\hat f_1=k_1\hat p_{11}+k_2\hat p_{12}\), \(\hat f_2=k_1\hat p_{12}+k_2\hat p_{22}\);
  3. acoustic tensor \(Q_{11}=C_{11}k_1^2+C_{44}k_2^2\), \(Q_{22}=C_{44}k_1^2+C_{11}k_2^2\), \(Q_{12}=(C_{12}+C_{44})k_1k_2\), and its inverse \(\Omega=Q^{-1}\);
  4. \(\hat{\boldsymbol g}=\Omega\hat{\boldsymbol f}\), which is \(\mathrm i\hat{\boldsymbol u}\), the displacement up to a factor \(\mathrm i\);
  5. heterogeneous strain \(\hat e_{11}=k_1\hat g_1\), \(\hat e_{22}=k_2\hat g_2\), \(\hat e_{12}=\tfrac12(k_1\hat g_2+k_2\hat g_1)\), and three inverse transforms;
  6. total strain \(\boldsymbol\varepsilon=\bar{\boldsymbol E}+\boldsymbol e\), with \(\bar{\boldsymbol E}\) from the loading, and reference stress \(\boldsymbol\sigma^0=\mathsf C^0(\boldsymbol\varepsilon-\boldsymbol\varepsilon^0)\).

The \(\boldsymbol k=0\) entries of \(\Omega\) are zero, because the mean strain comes from the loading, and the Nyquist wavenumber is set to zero so that first derivatives of real fields stay real. Every line is a whole-array operation, so a pass is six FFTs and a few element-wise products. All iteration counts below are counted in passes, so they compare directly.

class Green2D:
    '''The homogeneous Green solution on an N x N periodic grid of unit spacing (Section 3, Steps 1-8).

    Fields are stored as arrays of shape (3, N, N): the Voigt three-vector (11, 22, 12) with TENSOR shear (eps_12, not 2 eps_12),
    so the double contraction is a:b = a1 b1 + a2 b2 + 2 a3 b3 (function `inner`). The reference solid is cubic with axes along the grid
    (isotropic when C44 = (C11 - C12)/2). Everything is a whole-array operation; the only loops in this notebook are the outer iterations.

    Attributes: k1, k2 wavevector arrays on the half spectrum of a real FFT (Nyquist set to zero); O11, O22, O12 the inverse acoustic
    tensor Omega = Q^-1, with Omega = 0 wherever both wavevector components vanish (k = 0 and the Nyquist corners), because the mean
    strain is supplied by the loading, not by the Fourier solve.

    Transforms: two FFTW plans, made once here with FFTW_MEASURE on fixed, aligned buffers (`_r` real input, `_c` half spectrum, `_o`
    real output) and executed on every pass. Planning once and reusing the buffers is what makes FFTW fast: no planning, no
    allocation and no copying inside the iterations.'''
    def __init__(self, n, C11, C12, C44):
        self.n = n; self.C11, self.C12, self.C44 = C11, C12, C44; self.det = C11**2 - C12**2
        self.th = FFT_THREADS
        self._r = pyfftw.empty_aligned((3, n, n)); self._c = pyfftw.empty_aligned((3, n, n//2 + 1), dtype=complex); self._o = pyfftw.empty_aligned((3, n, n))
        self._fw = pyfftw.FFTW(self._r, self._c, axes=(-2, -1), direction='FFTW_FORWARD', threads=self.th, flags=('FFTW_MEASURE',))   # three r2c FFTs in one plan
        self._bw = pyfftw.FFTW(self._c, self._o, axes=(-2, -1), direction='FFTW_BACKWARD', threads=self.th,
                               flags=('FFTW_MEASURE', 'FFTW_DESTROY_INPUT'))   # three c2r FFTs; divides by N^2 (normalise_idft=True)
        k = 2*np.pi*fft.fftfreq(n); k[n//2] = 0.0                      # wavenumbers 2 pi m / N; the Nyquist term m = N/2 is set to zero so first derivatives of real fields stay real
        self.k1 = k[:, None] * np.ones((1, n//2 + 1))                      # axis 0: full spectrum
        self.k2 = np.ones((n, 1)) * k[None, :n//2 + 1]                     # axis 1: rfft half spectrum
        # acoustic tensor Q_ik = C_ijkl k_j k_l of the reference solid, and its 2x2 inverse Omega (Step 4 of Section 3)
        Q11 = C11*self.k1**2 + C44*self.k2**2; Q22 = C44*self.k1**2 + C11*self.k2**2; Q12 = (C12 + C44)*self.k1*self.k2
        null = (self.k1 == 0) & (self.k2 == 0)                             # k = 0, and the Nyquist corners after zeroing
        det = Q11*Q22 - Q12**2; det[null] = 1.0
        self.O11 = np.where(null, 0.0, Q22/det); self.O22 = np.where(null, 0.0, Q11/det); self.O12 = np.where(null, 0.0, -Q12/det)
    # --- constitutive maps of the reference solid, elementwise on (3, N, N) arrays
    def stiff(self, e):
        '''sigma = C0 : eps for a tensor-shear three-vector: (C11 e1 + C12 e2, C12 e1 + C11 e2, 2 C44 e3).'''
        return np.array([self.C11*e[0] + self.C12*e[1], self.C12*e[0] + self.C11*e[1], 2*self.C44*e[2]])
    def compl(self, s):
        '''eps = S0 : sigma, the inverse of `stiff`: (C11 s1 - C12 s2, C11 s2 - C12 s1)/(C11^2 - C12^2) and s3/(2 C44).'''
        return np.array([(self.C11*s[0] - self.C12*s[1])/self.det, (self.C11*s[1] - self.C12*s[0])/self.det, s[2]/(2*self.C44)])
    # --- the Green solve: heterogeneous (zero-mean) strain produced by a stress-free strain field eps0
    def heterogeneous_strain(self, eps0):
        '''Zero-mean strain e(r) produced in the reference solid by the stress-free strain field eps0 (Steps 1-6 of Section 3).'''
        self._r[:] = self.stiff(eps0); P = self._fw()                      # Step 1-2: eigenstress p = C0 eps0, transformed; P is the buffer _c
        f1 = self.k1*P[0] + self.k2*P[2]; f2 = self.k1*P[2] + self.k2*P[1]  # Step 3: force f_i = k_j p_ij
        g1 = self.O11*f1 + self.O12*f2;  g2 = self.O12*f1 + self.O22*f2     # Step 5: g = Omega f (this is i times the displacement)
        P[0] = self.k1*g1; P[1] = self.k2*g2; P[2] = 0.5*(self.k1*g2 + self.k2*g1)   # Step 6: strain symbols e_ij = (k_i g_j + k_j g_i)/2, written into _c
        return self._bw().copy()                                             # three inverse FFTs; copied, because the buffer is reused by the next pass
    def run(self, eps0, Sigma=None, Ebar=None):
        '''One pass (Steps 1-8): total strain, reference stress sigma0 = C0 (eps - eps0), and the mean strain, for the stress-free strain
        field eps0 under either a prescribed mean stress Sigma (stress control, Eq. 2) or a prescribed mean strain Ebar. Give exactly one.'''
        e = self.heterogeneous_strain(eps0)
        Eb = eps0.mean(axis=(1, 2)) + self.compl(np.asarray(Sigma, float)) if Sigma is not None else np.asarray(Ebar, float)   # Step 7: Eq. (2) or prescribed
        eps = e + Eb[:, None, None]                                          # total strain = homogeneous + heterogeneous
        return eps, self.stiff(eps - eps0), Eb                               # Step 8: reference stress

def inner(x, y):
    '''Double contraction summed over the grid: sum of x:y with the shear counted twice (metric M = diag(1,1,2)).'''
    return float(np.sum(x[0]*y[0] + x[1]*y[1] + 2*x[2]*y[2]))

def grid(n):
    '''Cell-centered coordinates in cells with the origin at (n/2, n/2): x, y, radius r and polar angle theta, each (n, n).'''
    x, y = np.meshgrid(np.arange(n) - n/2, np.arange(n) - n/2, indexing='ij')
    return x, y, np.sqrt(x**2 + y**2), np.arctan2(y, x)

def tanh_void(r, R, w):
    '''Fractional void indicator: 1 in the hole, 0 in the solid, tanh rim of half-width w cells (10-90 % over 2.2 w cells).'''
    return 0.5*(1 - np.tanh((r - R)/w))
Names in this code
In the codeSymbolMeaning
k1, k2\(k_1,\ k_2\)Wavevector components on the half spectrum of a real FFT, Nyquist set to zero.
O11, O22, O12\(\Omega=Q^{-1}\)Inverse acoustic tensor of the reference solid; zero at \(\boldsymbol k=0\).
stiff, compl\(\mathsf C^0\), \(\mathsf S^0\)Hooke's law of the reference solid and its inverse, on whole fields.
run(eps0, Sigma | Ebar)one passTotal strain, reference stress \(\boldsymbol\sigma^0\) and mean strain for the stress-free strain \(\boldsymbol\varepsilon^0\).
inner\(\sum\boldsymbol x:\boldsymbol y\)Double contraction summed over the grid, shear counted twice.
tanh_void(r, R, w)\(\phi\)Void indicator: 1 in the hole, 0 in the solid, a \(\tanh\) rim of half-width \(w\) cells.

Before any iteration we check the pass alone. A stress-free strain that depends on \(x_1\) only is compatible, so it must return as strain with no stress: it does, to \(4\times10^{-16}\). A uniform cell under 160 MPa must carry exactly 160 MPa: it does, to \(3\times10^{-17}\) GPa.

Step 3: Where the material is, the indicator

The original papers mark the hole with a Heaviside indicator: every grid cell is solid or void. We use a fractional indicator \(\phi(\boldsymbol r)\in[0,1]\), 1 in the void and 0 in the solid, with a smooth \(\tanh\) rim a few cells wide, because in a phase-field model the stiffness will be slaved to a field. In the rim the stiffness is \(\mathsf C=(1-\phi)\mathsf C^0\): a soft material of finite contrast. This small change is what separates the solvers of Step 4.

Left: the void indicator phi, black inside a hole of radius 20 cells. Right: phi and the stiffness fraction 1 minus phi along a line through the center, one marker per grid point, crossing at r = 20
The hole of Step 6: radius 20 cells, rim half-width 2 cells, so five grid points lie between \(\phi=0.9\) and \(\phi=0.1\).

A \(\tanh\) rim has a tail: \(1-\phi\approx e^{-2(R-r)/w}\), so the hole contains cells of stiffness \(10^{-2}\), \(10^{-4}\), \(10^{-8}\) of \(\mathsf C^0\). Cells softer than \(10^{-8}\,\mathsf C^0\) are declared exact vacuum, and cells with \(\phi<10^{-8}\) exact solid, where \(\boldsymbol q=0\) as in the original papers. Far from the rim the indicator is therefore a Heaviside function; only the rim is fractional.

Step 4: Three ways to find \(\boldsymbol q\)

For the void branch \(\mathsf C=(1-\phi)\mathsf C^0\), Eq. (1) becomes, cell by cell,

\[\boldsymbol q=\phi\big(\boldsymbol q+\mathsf S^0\boldsymbol\sigma^0\big).\tag{3}\]

In the void (\(\phi=1\)) it says \(\boldsymbol\sigma^0=0\); in the solid (\(\phi=0\)) it says \(\boldsymbol q=0\); in the rim it is the law \(\boldsymbol\sigma=(1-\phi)\mathsf C^0(\boldsymbol\varepsilon-\boldsymbol\varepsilon^*)\).

The TDGL loop. WJK relax the virtual strain by a gradient flow, which inside a void is \(\partial\boldsymbol q/\partial t=L\boldsymbol\sigma^0\). With an explicit step and the indicator multiplied in,

\[\boldsymbol q\leftarrow\big(\boldsymbol q+\Delta t\,L\,\boldsymbol\sigma^0\big)\,\phi.\tag{4}\]

This is the loop of our 2019–2022 C and CUDA codes. It is stable for \(\Delta t\,L\,(C_{11}+C_{12})<2\), independent of the grid spacing, and it stops when the stress stops changing. In a rim cell its fixed point is \(\boldsymbol q(1-\phi)=\Delta t\,L\,\phi\,\boldsymbol\sigma^0\): the step has become part of the material law. On a fractional indicator the TDGL loop does not solve Eq. (3); it solves it only on a Heaviside one.

The compliance map. Iterate Eq. (3) as written, \(\boldsymbol q\leftarrow\phi(\boldsymbol q+\mathsf S^0\boldsymbol\sigma^0)\). This is the TDGL step with \(\Delta t\,L\) replaced by the compliance \(\mathsf S^0\), the largest stable step, mode by mode. It is also the basic scheme of Moulinec and Suquet written in the eigenstrain variable. It solves Eq. (3) exactly at its fixed point.

The corrector. Everything in Eq. (3) is linear in \(\boldsymbol q\). Collecting terms gives a linear system,

\[\mathcal H\boldsymbol q=\mathsf C^0\boldsymbol b,\qquad \mathcal H=\mathsf W+\mathsf C^0\big(\mathsf I-\bar{\mathcal A}\big),\qquad \mathsf W=\frac{1-\phi}{\phi}\,\mathsf C^0,\tag{5}\]

where \(\bar{\mathcal A}\) maps a stress-free strain to the total strain it produces (one pass, no load) and \(\boldsymbol b\) is the strain at \(\boldsymbol q=0\) minus \(\boldsymbol\varepsilon^*\). \(\mathcal H\) is the Hessian of the WJK energy. It is self-adjoint in the pairing \(\boldsymbol x:\boldsymbol y\) summed over the grid, and positive semidefinite when no cell is stiffer than the reference. Its residual is a stress,

\[\boldsymbol r=\boldsymbol\sigma^0-\mathsf W\boldsymbol q=\frac1\phi\big(\boldsymbol\sigma^0-\boldsymbol\sigma\big),\tag{6}\]

the disagreement between the two laws; in the void it is just \(\boldsymbol\sigma^0\). So we solve Eq. (5) by preconditioned conjugate gradients, with a preconditioner that follows the local compliance:

\[\mathcal P_\vartheta^{-1}=\frac{\phi}{1-\phi+\vartheta\phi}\,\mathsf S^0,\qquad \vartheta=1\ \text{or}\ \vartheta=\tfrac23.\tag{7}\]

\(\vartheta=1\) is the map's own step; \(\vartheta=2/3\) is the two-dimensional average of the compatible projector. Each conjugate-gradient iteration costs one pass, the same as one map step. A predictor, one map step, can start it; so can zero, or the previous time step of a phase-field simulation.

Three ways down the same valley

1

A fixed step

TDGL and the map take the same kind of step every time. In a long narrow valley I zigzag.

And with a TDGL step that is not my compliance, you even settle at the wrong bottom in the rim.

2

A step chosen by the problem

Conjugate gradients pick each step length from the operator and never undo an earlier direction.

Same equation as the map, same cost per pass, far fewer passes.

3

Why the rim decides

On a sharp edge every cell is me or vacuum, and all three methods agree.

In a diffuse rim the cells are thin springs. Only the map and the corrector give them the right law.

class VoidProblem:
    '''A hole / free-surface problem: fractional indicator phi (1 = void), physical eigenstrain eps_star (3,n,n), loading.
    Cells softer than void_floor * C0 are declared exact vacuum (the exact-zero branch of Wang, Jin and Khachaturyan), and cells
    with phi below solid_floor are declared exact solid (q = 0 there, as in the original papers' "solve only within the domains").
    Far from the rim the indicator is therefore a Heaviside function; the fractional cells are the rim alone.

    Attributes: D, the mask where q lives (phi > 0); w, the scalar field (1 - phi)/phi so that the local Hessian term is W = w C0;
    s, the stress scale (rms of sigma0 at q = 0 in the compliance norm), fixed once so that every relative residual is comparable;
    solid, the mask phi < 0.01 where the physical stress is judged; ref, an optional converged stress used by `solid_error`.'''
    def __init__(self, G, phi, eps_star, Sigma=None, Ebar=None, void_floor=1e-8, solid_floor=1e-8):
        phi = np.where(1 - phi < void_floor, 1.0, np.where(phi < solid_floor, 0.0, phi))
        self.G, self.phi, self.eps_star = G, phi, eps_star
        self.Sigma, self.Ebar = Sigma, Ebar
        self.D = phi > 0.0                                                     # where q lives
        self.solid = phi < 0.01                                                # where the physical stress is judged
        self.w = np.where(self.D, (1 - phi)/np.where(self.D, phi, 1.0), 0.0)  # W = w C0
        eps, sig0 = self.pass_(np.zeros_like(eps_star))
        self.s = max(np.sqrt(inner(sig0, G.compl(sig0))/G.n**2), 1e-300)      # stress scale, fixed once: rms of sig0 at q = 0
        self.ref = None                                                        # a converged reference stress, for tracking the solid error
    def pass_(self, q):
        '''Loaded pass with eps0 = eps_star + q. Returns eps, sig0.'''
        eps, sig0, Eb = self.G.run(self.eps_star + q, Sigma=self.Sigma, Ebar=self.Ebar); return eps, sig0
    def sig0_hom(self, d):
        '''Reference stress produced by the eigenstrain d alone, with the linear part of the loading only.'''
        if self.Sigma is not None: eps, sig0, _ = self.G.run(d, Sigma=(0.0, 0.0, 0.0))      # Ebar = <d>
        else:                      eps, sig0, _ = self.G.run(d, Ebar=(0.0, 0.0, 0.0))
        return sig0
    def residual(self, q, sig0):
        '''r = sig0 - W q on D (Eq. 6).'''
        return np.where(self.D, sig0 - self.w*self.G.stiff(q), 0.0)
    def apply_H(self, d):
        '''H d = W d - sig0_hom(d), masked to D (Eq. 5). Also returns sig0_hom(d), so the current stress can be updated for free.'''
        sh = self.sig0_hom(d)
        return np.where(self.D, self.w*self.G.stiff(d) - sh, 0.0), sh
    def Pinv(self, r, theta):
        p = np.where(self.D, self.phi/(1 - self.phi + theta*self.phi), 0.0)
        return p*self.G.compl(r)
    def rel(self, r):
        '''Relative residual: rms of r in the compliance norm over the scale s.'''
        return np.sqrt(inner(r, self.G.compl(r))/self.G.n**2)/self.s
    def solid_error(self, sig0):
        '''rms difference of the stress in the solid from the reference, in the compliance norm, over the scale s (dimensionless). nan if no reference.'''
        if self.ref is None: return np.nan
        d = np.where(self.solid, sig0 - self.ref, 0.0); return np.sqrt(inner(d, self.G.compl(d))/self.solid.sum())/self.s
    def physical_stress(self, eps):
        return (1 - self.phi)*self.G.stiff(eps - self.eps_star)
    def predictor(self, q, sig0):
        '''One compliance-map step (Eq. 3).'''
        return self.phi*(q + self.G.compl(sig0))

def finish(P, q, passes, history, solid_hist, rule, t0, name):
    '''One final loaded pass and the result dictionary shared by all solvers: fields, pass count, histories, stopping rule, timings.'''
    eps, sig0 = P.pass_(q); sig = P.physical_stress(eps); r = P.residual(q, sig0)
    return dict(name=name, strain=eps, stress=sig, sig0=sig0, q=q, passes=passes + 1, history=np.array(history), solid_history=np.array(solid_hist),
                rule=rule, time=time.time() - t0, final_rel_residual=P.rel(r), solid_error=P.solid_error(sig0))

def solve_tdgl(P, dtL=None, tol=1e-7, max_it=20000, name='TDGL loop'):
    '''Eq. (4): q <- (q + dtL sig0) phi. Stop on the rms change of sig0 between passes relative to the fixed stress scale (the rule of the 2019-2022 codes, with a fixed scale so that it also works when the stress itself tends to zero).'''
    t0 = time.time(); G = P.G
    if dtL is None: dtL = 1.2/(G.C11 + G.C12)
    q = np.zeros_like(P.eps_star); prev = None; hist = []; shist = []
    for it in range(1, max_it + 1):
        eps, sig0 = P.pass_(q); shist.append(P.solid_error(sig0))           # one pass with the current virtual strain
        q = (q + dtL*sig0)*P.phi                                              # Eq. (4): relax toward sigma0 = 0, then confine to the void
        if prev is not None:
            change = P.rel(sig0 - prev); hist.append(change)                        # rms change in the compliance norm over the fixed scale s
            if change < tol: break
        prev = sig0
    else: print(name, 'did not converge')
    return finish(P, q, it, hist, shist, f'rel. stress change < {tol:g}', t0, name)

def solve_map(P, tol=1e-4, max_it=3000, name='compliance map'):
    '''Eq. (3) iterated: q <- phi (q + S0 sig0). Stop on the relative residual (6), the same rule as the corrector.'''
    t0 = time.time(); q = np.zeros_like(P.eps_star); hist = []; shist = []
    for it in range(1, max_it + 1):
        eps, sig0 = P.pass_(q); r = P.residual(q, sig0); rel = P.rel(r); hist.append(rel); shist.append(P.solid_error(sig0))
        if rel < tol: break
        q = P.phi*(q + P.G.compl(sig0))                                       # Eq. (3): the local equivalence, exact in the void, local compliance in the rim
    else: print(name, f'reached the cap of {max_it} passes, residual {rel:.2e}')
    return finish(P, q, it, hist, shist, f'rel. residual < {tol:g}', t0, name)

def solve_pcg(P, theta=2/3, tol=1e-4, max_it=3000, start='zero', name=None):
    '''Preconditioned conjugate gradients on (5) with the varying compliance (7). start: "zero" or "predictor".'''
    t0 = time.time(); G = P.G
    if name is None: name = f'PCG theta={theta:.3g}' + (' from predictor' if start == 'predictor' else '')
    q = np.zeros_like(P.eps_star); eps, sig0 = P.pass_(q); passes = 1
    if start == 'predictor': q = P.predictor(q, sig0); eps, sig0 = P.pass_(q); passes += 1
    r = P.residual(q, sig0); z = P.Pinv(r, theta); d = z.copy(); rho = inner(r, z); hist = []; shist = [P.solid_error(sig0)]
    # Standard preconditioned conjugate gradients. r is a stress (the residual of Eq. 5), z = P^-1 r and d are strains,
    # every inner product pairs a stress with a strain, and one iteration costs exactly one Green pass (inside apply_H).
    for k in range(1, max_it + 1):
        h, sh = P.apply_H(d); passes += 1                                     # h = H d (a stress); sh = sigma0_hom(d) comes for free
        curv = inner(d, h)                                                    # <d, H d>: must be positive for a positive semidefinite H
        if not curv > 0:
            print(name, f'stopped: curvature <d,Hd> = {curv:.3e} is not positive. Is some cell stiffer than the reference? Raise C0 or use MINRES.'); break
        alpha = rho/curv; q = q + alpha*d; r = r - alpha*h; sig0 = sig0 + alpha*sh        # step length from the operator; sig0 follows q at no extra cost
        rel = P.rel(r); hist.append(rel); shist.append(P.solid_error(sig0))
        if rel < tol: break
        z = P.Pinv(r, theta); rho_new = inner(r, z); d = z + (rho_new/rho)*d; rho = rho_new   # new search direction, conjugate to the old ones
    else: print(name, f'reached the cap of {max_it} iterations, residual {rel:.2e}')
    return finish(P, q, passes, hist, shist, f'rel. residual < {tol:g}', t0, name)

def set_reference(P, tol=1e-7, max_it=6000):
    '''A well-converged corrector solution whose solid stress serves as the reference for the error histories.'''
    P.ref = None; ref = solve_pcg(P, theta=2/3, tol=tol, max_it=max_it, name='reference'); P.ref = ref['sig0']
    print(f"reference solution: {ref['passes']} passes, relative residual {ref['final_rel_residual']:.1e}")
    return ref
Names in this code
In the codeSymbolMeaning
D\(\phi>0\)Cells where \(\boldsymbol q\) may be nonzero.
w\((1-\phi)/\phi\)So that the local Hessian term is \(\mathsf W=w\,\mathsf C^0\).
residual, rel\(\boldsymbol r\), \(\|\boldsymbol r\|/s\)Eq. (6), and its rms in the compliance norm over a stress scale fixed once at \(\boldsymbol q=0\).
apply_H(d)\(\mathcal H\boldsymbol d\)One pass with eigenstrain \(\boldsymbol d\) and no load; also returns its stress, so \(\boldsymbol\sigma^0\) follows \(\boldsymbol q\) for free.
Pinv(r, theta)\(\mathcal P_\vartheta^{-1}\boldsymbol r\)The preconditioner of Eq. (7).
solve_tdgl, solve_map, solve_pcgEqs. (4), (3), (5)The three iterations; every one stops at a strict cap and says so.
solid_errorrms difference of the stress in the solid (\(\phi<0.01\)) from a reference solution.

Step 5: Validation before any comparison

A comparison is worthless if the operator or the metric is wrong, so three checks come first.

PART 2 · TEST AGAINST EXACT SOLUTIONS

Step 6: Kirsch's hole under uniaxial stress

A hole of radius \(R\) in an infinite plate under a uniaxial stress \(\sigma\) along \(x\), with \(\theta\) measured from the load axis, carries the stress found by Kirsch in 1898:

\[\sigma_{rr}=\frac\sigma2\Big(1-\frac{R^2}{r^2}\Big)+\frac\sigma2\Big(1-\frac{4R^2}{r^2}+\frac{3R^4}{r^4}\Big)\cos2\theta,\] \[\sigma_{\theta\theta}=\frac\sigma2\Big(1+\frac{R^2}{r^2}\Big)-\frac\sigma2\Big(1+\frac{3R^4}{r^4}\Big)\cos2\theta,\qquad \sigma_{r\theta}=-\frac\sigma2\Big(1+\frac{2R^2}{r^2}-\frac{3R^4}{r^4}\Big)\sin2\theta.\]

At the wall \(\sigma_{rr}=\sigma_{r\theta}=0\), the traction-free condition the virtual strain must reproduce, and \(\sigma_{\theta\theta}=\sigma(1-2\cos2\theta)\): \(3\sigma\) across the load and \(-\sigma\) along it, whatever the size of the hole and the elastic constants. See the Kirsch equations, and Timoshenko and Goodier, Theory of Elasticity, §35, for the derivation from the Airy stress function. Our cell is periodic, so we judge the solution in annuli between \(1.25R\) and \(3R\), where the image holes matter little.

def kirsch_polar(r, th, R, sig):
    '''Kirsch stresses (srr, stt, srt) for a hole of radius R under uniaxial sig along x, zero inside the hole.'''
    rr = np.maximum(r, 1e-9); q = (R/rr)**2
    srr = sig/2*(1 - q) + sig/2*(1 - 4*q + 3*q**2)*np.cos(2*th)
    stt = sig/2*(1 + q) - sig/2*(1 + 3*q**2)*np.cos(2*th)
    srt = -sig/2*(1 + 2*q - 3*q**2)*np.sin(2*th)
    for a_ in (srr, stt, srt): a_[r < R] = 0.0
    return srr, stt, srt

def to_polar(S, th):
    '''Cartesian three-vector (s11, s22, s12) -> polar components (srr, stt, srt) at angle th.'''
    ct, st = np.cos(th), np.sin(th)
    return (S[0]*ct**2 + S[1]*st**2 + 2*S[2]*ct*st, S[0]*st**2 + S[1]*ct**2 - 2*S[2]*ct*st, (S[1] - S[0])*ct*st + S[2]*(ct**2 - st**2))

def to_cart(srr, stt, srt, th):
    '''Polar components -> Cartesian three-vector.'''
    ct, st = np.cos(th), np.sin(th)
    return np.array([srr*ct**2 + stt*st**2 - 2*srt*ct*st, srr*st**2 + stt*ct**2 + 2*srt*ct*st, (srr - stt)*ct*st + srt*(ct**2 - st**2)])

def kirsch_errors(S, r, th, R, sig, R_kirsch=None):
    '''rms error of the polar stress components in annuli (masks at radius R), relative to the applied stress, against Kirsch with radius R_kirsch (default R).'''
    srr, stt, srt = to_polar(S, th); K = kirsch_polar(r, th, R if R_kirsch is None else R_kirsch, sig); out = {}
    for lo, hi in ((1.25, 1.5), (1.5, 2.0), (2.0, 3.0)):
        A = (r >= lo*R) & (r < hi*R)
        out[f'err {lo}-{hi} R'] = np.sqrt(np.mean((srr - K[0])[A]**2 + (stt - K[1])[A]**2 + 2*(srt - K[2])[A]**2))/sig
    hoop = (r >= 1.05*R) & (r < 1.15*R) & (np.abs(np.abs(th) - np.pi/2) < 0.1)
    out['hoop 1.05-1.15R / Kirsch'] = np.mean(stt[hoop])/np.mean(K[1][hoop])
    return out

def lame_exact(r, a, b, es):
    '''Lame stresses (srr, stt) and the core stress for a dilatational core of radius a and eigenstrain es in a free disc of radius b.'''
    D = (lam + mu)*es*a**2/(lam + 2*mu); B = mu*es*a**2/((lam + 2*mu)*b**2)
    core = -2*mu*(lam + mu)*es/(lam + 2*mu)*(1 - a**2/b**2); rr = np.maximum(r, 1e-9)
    srr = np.where(r < a, core, 2*(lam + mu)*B - 2*mu*D/rr**2); stt = np.where(r < a, core, 2*(lam + mu)*B + 2*mu*D/rr**2)
    srr[r > b] = 0; stt[r > b] = 0
    return srr, stt, core

The test: \(256^2\) cells, \(R=20\) cells, rim half-width 2 cells, 160 MPa along \(x\) under stress control. The reference solution for the error histories ran to the cap of 10,000 passes and stopped at a residual of \(1.2\times10^{-6}\); it is a reference at that level, not a converged solution.

n, Rc = (256, 20) if QUICK else (512, 40)
w = 2.0; sig = 0.16                                           # rim half-width in cells; applied stress in GPa (160 MPa)
G = Green2D(n, C11, C12, C44); x, y, r, th = grid(n); phi = tanh_void(r, Rc, w)
# Test 1 runs: a converged reference first (for the solid-stress-error histories), then every solver at the same tolerance TOL,
# plus one corrector run to 1e-6 to show the slow regime.
P_hole = VoidProblem(G, phi, np.zeros((3, n, n)), Sigma=(sig, 0.0, 0.0))
print(f'cells declared exact vacuum after the 1e-8 floor: {(P_hole.phi == 1).sum()}; cells in the fractional rim (0 < phi < 1): {((P_hole.phi > 0) & (P_hole.phi < 1)).sum()}')
ref_hole = set_reference(P_hole, tol=1e-7, max_it=10000)
TOL = 1e-4; CAP = 3000
runs_hole = []
runs_hole.append(solve_tdgl(P_hole, tol=1e-7));                                 print(runs_hole[-1]['name'], runs_hole[-1]['passes'], 'passes', f"{runs_hole[-1]['time']:.0f} s")
runs_hole.append(solve_map(P_hole, tol=TOL, max_it=CAP));                        print(runs_hole[-1]['name'], runs_hole[-1]['passes'], 'passes', f"{runs_hole[-1]['time']:.0f} s")
for theta, start in ((1.0, 'zero'), (2/3, 'zero'), (2/3, 'predictor')):
    runs_hole.append(solve_pcg(P_hole, theta=theta, tol=TOL, max_it=CAP, start=start)); print(runs_hole[-1]['name'], runs_hole[-1]['passes'], 'passes', f"{runs_hole[-1]['time']:.0f} s")
runs_hole.append(solve_pcg(P_hole, theta=2/3, tol=1e-6, max_it=CAP, name='PCG theta=0.667 to 1e-6')); print(runs_hole[-1]['name'], runs_hole[-1]['passes'], 'passes', f"{runs_hole[-1]['time']:.0f} s")
Kirsch hole. Stress and strain along the x and y axes for every solver against Kirsch's solution: all solvers overlap Kirsch outside the hole, with the hoop stress peaking near 3 sigma at the wall across the load. A map of sigma xx over sigma. Convergence histories: the corrector with theta 2/3 reaches 1e-4 fastest; the TDGL solid-stress error levels off near 1e-2
Kirsch's hole. Top and middle: stress and strain along the two axes; inside the hole the strain is the virtual strain. Right: \(\sigma_{xx}/\sigma\), and the histories, thin for the residual, dashed for the stress error in the solid.
SolverPassesResidual (6)Solid stress errorError in \(1.25\)–\(1.5R\)Error in \(2\)–\(3R\)
TDGL loop (its own rule)1234\(1.4\times10^{-1}\)\(7.6\times10^{-3}\)5.7 %2.4 %
compliance map665\(1.0\times10^{-4}\)\(9.8\times10^{-5}\)2.9 %1.7 %
corrector, \(\vartheta=1\)1507\(9.6\times10^{-5}\)\(6.2\times10^{-6}\)2.9 %1.7 %
corrector, \(\vartheta=2/3\)188\(9.8\times10^{-5}\)\(5.6\times10^{-5}\)2.9 %1.7 %
corrector, \(\vartheta=2/3\), from the predictor204\(9.4\times10^{-5}\)\(4.1\times10^{-5}\)2.9 %1.7 %

The map and the correctors agree with each other to the last digit shown and with Kirsch to 2–3 %, the remainder being the periodic images and the two-cell rim, which also lowers the hoop stress just outside the wall to 0.80 of Kirsch's peak. The TDGL loop stops on its own rule with a residual of 0.14, and its error in the solid levels off at \(7.6\times10^{-3}\): that floor is the rim law of Eq. (4), and no number of passes removes it. The corrector with \(\vartheta=2/3\) reaches \(10^{-4}\) in 188 passes, 3.5 times fewer than the map.

Step 7: Lamé's core–shell disc, free in vacuum

A misfitting core of radius \(a\) with a dilatational eigenstrain \(e^*\) sits inside a disc of radius \(b\), with vacuum outside. With the 2D Lamé constants \(\lambda=C_{12}\), \(\mu=C_{44}\), the core is under the uniform stress

\[\sigma_{rr}=\sigma_{\theta\theta}=-\frac{2\mu(\lambda+\mu)}{\lambda+2\mu}\,e^*\Big(1-\frac{a^2}{b^2}\Big)\quad(r<a),\] \[\sigma_{rr}=2(\lambda+\mu)B-\frac{2\mu D}{r^2},\quad \sigma_{\theta\theta}=2(\lambda+\mu)B+\frac{2\mu D}{r^2}\quad(a<r<b),\quad D=\frac{(\lambda+\mu)e^*a^2}{\lambda+2\mu},\ B=\frac{\mu e^*a^2}{(\lambda+2\mu)b^2}.\]

A traction-free body also obeys the mean-strain theorem: the strain averaged over the disc equals the eigenstrain averaged over it, a check that needs no fitting. There is no load and we prescribe \(\bar{\boldsymbol E}=0\); the vacuum carries the compensating virtual strain.

# Test 2: Lame core-shell disc. Vacuum outside b, core eigenstrain inside a (intrinsic: e* where the core indicator is 1), Ebar = 0.
n_l = 128; G_l = Green2D(n_l, C11, C12, C44); xl, yl, rl, thl = grid(n_l)
cases = [(16, 32, 0.003), (24, 48, 0.003)] if QUICK else [(16, 32, 0.003), (24, 48, 0.003), (16, 32, 0.01)]
runs_lame = {}
for a_c, b_c, es in cases:
    phi_l = 1 - tanh_void(rl, b_c, 2.0)                       # vacuum outside b
    core = tanh_void(rl, a_c, 2.0)                            # 1 inside the core
    eps_star = np.array([es*core, es*core, 0*core])
    P_l = VoidProblem(G_l, phi_l, eps_star, Ebar=(0.0, 0.0, 0.0)); set_reference(P_l, tol=1e-7, max_it=8000)
    rr = [solve_tdgl(P_l, tol=1e-7), solve_map(P_l, tol=1e-4, max_it=20000),
          solve_pcg(P_l, theta=1.0, tol=1e-4, max_it=6000), solve_pcg(P_l, theta=2/3, tol=1e-4, max_it=6000), solve_pcg(P_l, theta=2/3, tol=1e-4, max_it=6000, start='predictor')]
Lame core-shell discs with a = 16, b = 32 and a = 24, b = 48 cells: radial and hoop stress along x for every solver against Lame's sharp solution, with rounding at the two diffuse rims; below, convergence histories
Lamé's disc for two sizes, stresses over the core stress, and the convergence histories.
DiscTDGLMapCorrector \(\vartheta=1\)Corrector \(\vartheta=2/3\)Core stress / Lamé\(\langle\varepsilon_{xx}\rangle/\langle\varepsilon^*\rangle\)
\(a=16\), \(b=32\)108877316312250.99230.9991
\(a=24\), \(b=48\)1960186544804970.99700.9990

The core stress agrees with Lamé to 0.8 % and 0.3 %, the mean strain to 0.1 %. What the eye sees as deviation from the sharp curve is the two diffuse rims: the spike in hoop stress at the core wall is cut by the two-cell rim, and the shell stress falls to zero across the rim at \(b\) rather than at \(b\) itself.

Step 8: The exact free disc, every solver

Step 5 used the corrector alone. Here every solver faces the free disc, whose answer is known exactly. The rim law does not matter here: uniform strain \(e^*\) and zero stress are a fixed point of all three schemes, because there is no stress for the rim to carry. What differs is the number of passes: TDGL 1005, map 1006, corrector 775 with \(\vartheta=1\) and 254 with \(\vartheta=2/3\), each with a stress in the material below \(4\times10^{-4}\,C_{11}e^*\).

Free disc: strain over e star equal to 1 in the disc for every solver, with the virtual strain varying in the vacuum outside; stress in the material of order 1e-4 times C11 e star; convergence histories
The free disc: strain \(e^*\) in the material for every solver; outside the disc the strain is the virtual strain of the vacuum, which the equations leave free.
PART 3 · WHAT DECIDES THE SPEED, AND WHAT TO DO ABOUT IT

Step 9: A fixed step converges, quickly, to a step-dependent answer

The free disc cannot show the rim law, so we use Lamé's disc, whose free surface at \(b\) carries the shell stress, and run the TDGL loop with two stable steps, \(\Delta t\,L=0.5/(C_{11}+C_{12})\) and \(1.5/(C_{11}+C_{12})\). Inside the shell all curves coincide. Through the rim at \(b\) the two TDGL curves differ from each other and from the corrector, and their stress in the solid differs from the corrector's by \(4.7\times10^{-2}\) and \(1.2\times10^{-2}\). Nothing warns us: the stopping rule is met and the curves are smooth. For a pure hole this is harmless. For a particle whose stiffness is interpolated through the rim it is the wrong physics.

Radial and hoop stress through the free surface of the Lame disc for two TDGL steps and the corrector: they agree inside the shell and separate in the rim
Through the free surface at \(b\): the TDGL stress in the rim depends on its step; the corrector returns the declared law \(\mathsf C=(1-\phi)\mathsf C^0\).

Step 10: The spectrum, and the modes that live in the hole

On a grid small enough to build the operator as a matrix we compute every eigenvalue of \(\mathcal P_\vartheta^{-1}\mathcal H\). The number of conjugate-gradient passes depends on how the eigenvalues are spread: a cluster is cheap, an isolated outlier costs one pass, and a continuum over many decades costs about one group of passes per decade.

Histogram of eigenvalues of the preconditioned operator on a 32 by 32 grid: the finite-contrast disc between 0.1 and 1.4; the exact Heaviside void with a flat spread of eigenvalues from 1e-10 to 1e-2; the tanh void from 1e-4 upwards
Eigenvalues of the preconditioned operator, \(\vartheta=2/3\), hole of radius 8 cells on a \(32^2\) grid.

A disc of finite contrast (stiffness \(0.1\,\mathsf C^0\)) has all its eigenvalues between 0.14 and 1.43: a tight cluster. The exact void has 143 exactly null eigenvalues and then thirteen to twenty-four per decade from \(10^{-10}\) to \(10^{-2}\). The null ones are compatible fields inside the void: the symmetric gradient of any displacement confined to the hole costs no stress, so the equations do not determine it, and it is harmless because the system stays consistent. The small nonzero ones are nearly compatible: displacement modes that live in the hole and leak a little stress into the rim. They are a property of a void in this formulation, not of the grid or the preconditioner, and no pointwise preconditioner removes them, because they are global. They are expected, and we live with them.

What we take away

1

Fast is not right

A fixed step with the wrong compliance converges fast, to the wrong rim.

Its stopping rule is satisfied all the same. Only the law residual (6) would have told us.

2

The hole keeps some secrets

Any strain that fits inside me without stress is allowed. You will never pin all of it down.

Fine. I only need my own stress, and that is right to \(10^{-4}\) long before the hole is settled.

3

Pay once

When the interface moves a fifth of a cell, start me from the last time step.

My slow modes are already settled then. About 185 passes become 15 to 60.

Step 11: When to stop, and warm starts

If the slow modes carried no stress into the solid, the solid stress and the energy would converge before the residual, and the right stopping rule would watch them. Along one corrector run on the hole of Step 6 the three measures first fall below each level at these passes:

LevelLaw residual (6)Stress error in the solidEnergy error
\(10^{-3}\)4082
\(10^{-4}\)1861064
\(10^{-5}\)8398667
Left: law residual, stress error in the solid and energy error along one corrector run on the hole, the energy error far below the other two. Right: the share of the residual norm inside the void core, between 5 and 30 percent
What converges when, along one corrector run on the hole.

At a residual of \(10^{-4}\) the solid stress is already at that level, reached in about half the passes, and the Kirsch error agrees with the reference to four digits (0.02919 against 0.02920). The energy, which conjugate gradients minimize, is converged within a few passes. Below \(10^{-4}\) the solid stress and the residual fall together, and only 5–20 % of the residual sits in the void core; the rest is in the rim, exactly where a nearly compatible mode leaks. The rule we use: stop at \(10^{-4}\) on the law residual, which a phase-field model needs, and the solid stress is good to that level.

In a phase-field loop the interface moves a fraction of a cell per time step. We move the hole by 0.2 cell per step, by growth and by translation, and start each solve either from zero or from the previous step's \(\boldsymbol q\):

Passes to a residual of \(10^{-4}\)Cold start, every stepWarm start from the previous \(\boldsymbol q\)
growing hole177–20015–20
translating hole182–19518–64
to a solid stress error of \(10^{-4}\)92–1143–5
Passes per step for a growing and a translating hole: cold starts about 180 to 200 every step; warm starts drop to about 15 to 60 after the first step
A warm start pays for the slow modes once, at the first step.

Warm-started solutions are also slightly more accurate at the same residual, because the modes carried over are already converged. For an evolving particle this is the number that matters: a few tens of passes per time step once the loop is running.

Step 12: The reverse geometry, a particle in a vacuum box

An embedded-particle model turns the hole inside out: a solid particle sits in a periodic box of vacuum and has an image in every neighboring cell. We take a free disc of radius \(R\) with a dilatational eigenstrain that grows with radius, \(\varepsilon^*=\varepsilon_0(r/R)^2\), as from a concentration gradient in an intercalating particle. With \(\beta=2(\lambda+\mu)/(\lambda+2\mu)\) the exact stress is

\[\sigma_{rr}=\tfrac12\mu\beta\varepsilon_0\,\frac{R^2-r^2}{R^2},\qquad \sigma_{\theta\theta}=\tfrac12\mu\beta\varepsilon_0\,\frac{R^2-3r^2}{R^2}:\]

tension at the center, hoop compression at the surface. How much vacuum does the box need? The gap \(g=N/2-R\) is the vacuum between the particle and the cell edge, so the next image is \(2g\) away. We shrink it two ways, by growing the disc in a \(256^2\) box and by shrinking the box around a disc of \(R=48\), and run the corrector with \(\vartheta=2/3\) to \(10^{-4}\).

Gap \(g\) (cells)Growing disc: passesStress errorShrinking box: passesStress error
801210.3 %1210.3 %
481900.09 %1850.2 %
322460.06 %2180.2 %
165190.04 %4320.2 %
85651.5 %4961.0 %
454242 %47835 %
Left: passes to 1e-4 against the vacuum gap for the two scans, close to each other. Middle: stress error against the gap, large below 8 cells. Right: stress along y = 0 for a wide gap matching the exact curve, and for a 4-cell gap far from it
A solid disc in a vacuum box: the gap, not the vacuum fraction, sets both the rate and the accuracy.

At equal gap the two scans agree to about 20 %, while at equal vacuum fraction (0.56) a 32-cell gap needs 246 passes and a 16-cell gap 432: the gap sets the rate. Below eight cells the particle feels its image through the tail of the rim: at a gap of \(2w\) the stiffness left at the cell edge is \(1.8\times10^{-2}\) and the particle is glued to its neighbor. Exact vacuum, \(1-\phi<10^{-8}\), begins about \(9w\) from the surface, so we keep the gap at eight rim widths or more.

Left: the particle, its rim, the gap g to the cell edge and the distance 2g to the next image. Right: the stiffness fraction 1 minus phi along the line to the image for gaps of 2w, 4w, 8w and 16w, the two tails meeting at the cell edge
How much vacuum a particle needs: the two \(\tanh\) tails meet at the cell edge, and their height there is the bridge to the image.
PART 4 · TWO STIFF PHASES

Step 13: Case B, a stiff plate or a soft one

The same equivalence handles two solid phases. A misfitting plate softer or stiffer than the matrix, with stiffness \(f(\boldsymbol r)\,\mathsf C_{\rm matrix}\) and eigenstrain \(\varepsilon^*_{11}=\epsilon_\eta\), \(\varepsilon^*_{22}=t\,\epsilon_\eta\) inside it, with \(\epsilon_\eta=0.003\) and tetragonality \(t=-0.5\), is the plate of my PhD thesis and of the direct method. We take the reference as the stiffest phase, \(\mathsf C^0=(\max f)\,\mathsf C_{\rm matrix}\), so that \(\mathsf C^0\ge\mathsf C\) everywhere, and start \(\boldsymbol\varepsilon^0\) at the eigenstrain. Each step relaxes the equivalence semi-implicitly, mode by mode:

\[\boldsymbol\varepsilon^0\leftarrow\frac{(\mathsf C^0-\mathsf C)\big(\boldsymbol\varepsilon^0+\mathsf S^0\boldsymbol\sigma^0\big)+\mathsf C\,\boldsymbol\varepsilon^*}{\mathsf C^0}.\]

This is finite everywhere: where \(\mathsf C=\mathsf C^0\) it gives \(\boldsymbol\varepsilon^0=\boldsymbol\varepsilon^*\), and where \(\mathsf C=0\) it is the compliance map of Step 4. WJK's explicit form, their Eq. (23), contains \((\mathsf C^0-\mathsf C)^{-1}\), which is infinite wherever \(\mathsf C=\mathsf C^0\); multiplying through, as here, avoids that. With stiffness proportional to the matrix every mode has the same ratio \(\mathsf C/\mathsf C^0=f/\max f\), so one scalar field does it, and the pass is the same Green2D as above. Contrast is finite here, so the spectrum is a tight cluster (Step 10) and the fixed point needs only 19 to 49 passes.

def ellipse(n, angle=30.0, a=0.23, b=0.075, width=0.35):
    """Smooth plate indicator h: 1 inside an ellipse with semi-axes a n, b n tilted by 'angle' degrees, 0 outside."""
    x, y = np.meshgrid(np.arange(n)/n - .5, np.arange(n)/n - .5, indexing='ij')
    t = np.deg2rad(angle); along = x*np.cos(t) + y*np.sin(t); across = -x*np.sin(t) + y*np.cos(t)
    return .5*(1 - np.tanh(((along/a)**2 + (across/b)**2 - 1)/width))

def plate(n, contrast, misfit=0.003, tetragonality=-0.5):
    """Case B: a misfitting plate whose stiffness is 'contrast' times the matrix. Stiffness factor f(r), eigenstrain eps_star (3,n,n)."""
    h = ellipse(n); f = 1 + h*(contrast - 1)
    eps_star = np.array([misfit*h, tetragonality*misfit*h, 0*h])
    return f, eps_star, h

def solve_two_phase(n, f, eps_star, Sigma=None, Ebar=(0.0, 0.0, 0.0), tol=1e-8, max_it=20000):
    """Case B: stiffness f(r) C_matrix with 0 < f. Reference C0 = (max f) C_matrix, so C0 >= C everywhere.
    The equivalence C0 (eps - eps0) = f C_matrix (eps - eps_star) is relaxed mode by mode with the semi-implicit step
    eps0 <- [(C0 - C)(eps0 + S0 sigma0) + C eps_star]/C0, which is finite also where C = C0 (there eps0 = eps_star).
    In the matrix-scaled form used here every mode has the same ratio C/C0 = f/max f, so one scalar field does it."""
    G = Green2D(n, *(f.max()*np.array([C11, C12, C44]))); c = f/f.max()
    eps0 = eps_star.copy(); prev = None
    for it in range(1, max_it + 1):
        eps, sig0, Eb = G.run(eps0, Sigma=Sigma, Ebar=None if Sigma is not None else Ebar)
        eps0 = (1 - c)*(eps0 + G.compl(sig0)) + c*eps_star
        if prev is not None:
            change = np.sqrt(inner(sig0 - prev, G.compl(sig0 - prev)))/max(np.sqrt(inner(sig0, G.compl(sig0))), 1e-300)
            if change < tol: break
        prev = sig0
    else:
        print(f'not converged: reached the cap of {max_it} iterations')
    eps, sig0, Eb = G.run(eps0, Sigma=Sigma, Ebar=None if Sigma is not None else Ebar)
    sig = c*G.stiff(eps - eps_star)                                 # physical stress f C_matrix (eps - eps_star) = c C0 (eps - eps_star)
    energy = 0.5*inner(sig, eps - eps_star)/n**2
    return dict(strain=eps, stress=sig, mean_strain=Eb, iterations=it, energy=energy)

Step 14: Case B check, the same answer as the direct method

The direct method iterates on the displacement; this one iterates on a virtual strain. They share nothing but the physics, so they must agree. The stiffness ratios bracket those of WJK Fig. 2. On a \(128^2\) grid, stress-free under both controls, energy density in kJ/m³:

Plate stiffness / matrixControlEquivalent eigenstrainDirect methodLargest strain differenceIterations
0.5 (soft)strain16.0383659616.03836596\(7.7\times10^{-11}\)19
0.5 (soft)stress14.1594051014.15940510\(3.7\times10^{-11}\)20
2 (hard)strain31.2864213131.28642131\(7.9\times10^{-11}\)19
2 (hard)stress26.2023094526.20230945\(5.8\times10^{-11}\)19
0.2 (very soft)strain9.865518019.86551801\(1.1\times10^{-9}\)49
0.2 (very soft)stress8.949773818.94977381\(9.9\times10^{-10}\)49

Strain control holds the mean strain at zero; stress control sets the mean strain every pass from Eq. (2) so that the mean stress vanishes, which the direct method reaches by a different route, \(\bar E=\langle C\rangle^{-1}(\sigma^a+\langle C:\epsilon^0\rangle-\langle C:\delta\epsilon\rangle)\). Pulling on the box with a prescribed mean stress is the subject of the homogenization page.

# Same plate, same grid; the direct method is solve_direct_voigt from the direct-iteration page, given the same stiffness in GPa.
# Its shear is engineering (g12 = 2 eps12), hence the factors of 2.
n = 128
for contrast in (0.5, 2.0, 0.2):
    for control in ('strain', 'stress'):
        f, eps_star, h = plate(n, contrast)
        virtual = solve_two_phase(n, f, eps_star, Sigma=(0.0, 0.0, 0.0) if control == 'stress' else None)
        S = tuple(f*c for c in (C11, C12, C44)); reference = tuple(.5*(Sk.max() + Sk.min()) for Sk in S)
        direct = solve_direct_voigt(S, (eps_star[0], eps_star[1], 2*eps_star[2]), reference, control=control, max_iterations=20000)
        e, d = virtual['strain'], direct['strain']
        diff = max(np.abs(e[0] - d[0]).max(), np.abs(e[1] - d[1]).max(), np.abs(2*e[2] - d[2]).max())
        print(f"contrast {contrast}, {control} control: virtual {1e6*virtual['energy']:.8f} kJ/m^3 ({virtual['iterations']} iterations), "
              f"direct {1e6*direct['energy']:.8f} kJ/m^3; largest strain difference {diff:.1e}")
OPTIONAL · SPEED

Step 15: Faster passes, with Numba and in C

Every NumPy line runs a compiled loop, so why would C be faster? Because NumPy runs one loop per operation: f1 = k1*P[0] + k2*P[2] is three loops, each writing a temporary array to memory and reading it back. On a \(512^2\) grid the arrays are larger than the processor's fast caches, so most of the time goes into moving data. The notebook's optional section fuses the element-wise steps, once with Numba and once in C with FFTW called directly: one fused loop for \(\boldsymbol p=\mathsf C^0\boldsymbol\varepsilon^0\), one FFTW guru plan for the three forward transforms, one fused Fourier-space loop, one plan for the three inverse transforms. The heart of the C version:

/* Excerpt from green2d_fftw.c, written by the notebook with %%writefile. */
/* In g2_new: two FFTW guru plans, made once, for the three components together. */
    /* Guru plans. dims: the two transformed axes, with input and output strides in elements of each array;
       howmany: the three components, one after the other in memory. */
    fftw_plan_with_nthreads(nthreads);
    fftw_iodim dr[2] = {{n, n, m}, {n, 1, 1}};            /* r2c: real rows have stride n, complex rows stride m */
    fftw_iodim hr[1] = {{3, N, M}};
    g->fw = fftw_plan_guru_dft_r2c(2, dr, 1, hr, g->r, (fftw_complex *)g->c, FFTW_MEASURE);
    fftw_iodim db[2] = {{n, m, n}, {n, 1, 1}};            /* c2r: the logical (real) size n on both axes */
    fftw_iodim hb[1] = {{3, M, N}};
    g->bw = fftw_plan_guru_dft_c2r(2, db, 1, hb, (fftw_complex *)g->c, g->o, FFTW_MEASURE | FFTW_DESTROY_INPUT);

/* Steps 1-6: zero-mean strain e produced by eps0; result left in g->o. Returns the means of eps0 in mean[3]. */
static void g2_hetero(G2 *g, const double *eps0, double mean[3])
{
    const int n = g->n, m = g->m; const long N = (long)n*n, M = (long)n*m;
    const double C11 = g->C11, C12 = g->C12, C44 = g->C44, inv = 1.0/(double)N;
    double s0 = 0, s1 = 0, s2 = 0;
    #pragma omp parallel for reduction(+:s0,s1,s2) schedule(static)
    for (long t = 0; t < N; t++) {                                  /* Step 1: eigenstress p = C0 eps0 */
        double a = eps0[t], b = eps0[N + t], c = eps0[2*N + t];
        g->r[t] = C11*a + C12*b; g->r[N + t] = C12*a + C11*b; g->r[2*N + t] = 2.0*C44*c;
        s0 += a; s1 += b; s2 += c;
    }
    mean[0] = s0*inv; mean[1] = s1*inv; mean[2] = s2*inv;
    fftw_execute(g->fw);                                            /* Step 2: three r2c transforms */
    double complex *P = g->c;
    #pragma omp parallel for schedule(static)
    for (int i = 0; i < n; i++) {                                   /* Steps 3-6, fused, with the 1/N^2 of the inverse */
        const double a = g->k1[i];
        for (int j = 0; j < m; j++) {
            const long t = (long)i*m + j; const double b = g->k2[j];
            double complex p0 = P[t], p1 = P[M + t], p2 = P[2*M + t];
            double complex f1 = a*p0 + b*p2, f2 = a*p2 + b*p1;                       /* force f = k . p */
            double complex g1 = g->O11[t]*f1 + g->O12[t]*f2, g2 = g->O12[t]*f1 + g->O22[t]*f2;   /* g = Omega f */
            P[t] = inv*a*g1; P[M + t] = inv*b*g2; P[2*M + t] = inv*0.5*(a*g2 + b*g1);         /* e = sym(k g) */
        }
    }
    fftw_execute(g->bw);                                            /* three c2r transforms into g->o */
}
GridNumPy + FFTWNumba + FFTWC + FFTW guru plans
\(256^2\)1.98 ms1.08 ms0.65 ms
\(512^2\)8.45 ms3.30 ms2.03 ms
\(1024^2\)37.9 ms11.2 ms5.96 ms

Time per pass on eight FFTW threads; the three versions agree to \(3\times10^{-14}\). A whole corrector solve on Kirsch's hole takes the same 188 passes in each, and running the corrector itself in C as well brings it from 4.7 ms to 1.4 ms per iteration on \(256^2\), and from 18.3 to 4.7 ms on \(512^2\). The NumPy code stays the reference version of everything on this page; the C file is in the notebook.

What to conclude

IterationLocal compliance it usesIn a fractional rimPasses to \(10^{-4}\) (hole, Lamé, free disc)
TDGL loop, Eq. (4)a uniform step \(\Delta t\,L\)the wrong rim law, set by the step; the solid is close1234, 1088, 1005 (its own rule)
compliance map, Eq. (3)the local \(\mathsf S^0/(1-\phi)\)the right rim law665, 773, 1006
corrector, Eqs. (5)–(7)the local one, as a preconditionerthe right rim law188, 225, 254

A fixed step with the wrong compliance converges fast to the wrong answer. A fixed step with the right compliance converges to the right answer, more slowly. A Krylov corrector solves the implicit coupling of Eq. (1) instead of relaxing toward it, with the same cost per pass, in three to four times fewer passes on these tests, and a warm start in a phase-field loop brings it to a few tens of passes per time step. On a Heaviside indicator, with no soft cell, the three fixed points coincide, which is why the rim law went unnoticed in the original papers and in our own codes for years.

Request the complete notebook

References.