Algorithm Search⌘K

Algorithmcore

Zienkiewicz-Zhu error estimator

Also called ZZ estimator, superconvergent patch recovery.

Recovers a smoother gradient by local least squares fits on patches and uses its difference from the raw gradient as an error estimate.

Time
Θ(M) average
Space
Θ(M) extra
Where
M = the number of triangles
Properties
asymptotically exact on superconvergent meshesdeterministiclocalproblem independent
Origin
Olgierd C. Zienkiewicz, Jian Zhong Zhu, 1987

The Zienkiewicz-Zhu (ZZ) estimator measures the error of a finite element solution by how rough its gradient is. A piecewise linear solution uhu_h has a gradient that jumps from one element to the next, while the gradient of the exact solution is continuous. The estimator builds a continuous gradient GG from uhu_h, called the recovered gradient, and uses ηK=∥G−∇uh∥L2(K)\eta_K = \|G - \nabla u_h\|_{L^2(K)} as the error indicator of element KK. The superconvergent patch recovery (SPR) computes GG at each vertex by a least squares fit of a linear polynomial to the element gradients of the patch around that vertex. The estimator needs only the mesh and the solution. It does not look at the equation, so one code works for heat flow, elasticity and other problems. When GG is much closer to the true gradient than ∇uh\nabla u_h is, the estimate is asymptotically exact: η\eta divided by the true error tends to 1.

In plain words

The computed solution has a slope that is constant on each triangle and jumps between triangles. The true solution has a smooth slope. So make a smooth slope from the computed one: at each corner, look at the slopes of the triangles around it and fit a plane through them. This gives a slope at every corner, and in between we interpolate linearly. Where the computed slope is far from the smooth slope, the solution is probably bad, and that triangle should be refined. The total difference is the estimate of the error. On good meshes the estimate is almost exactly the true error.

The problem

Input. A conforming triangle mesh of a polygon and the nodal values UU of a continuous piecewise linear finite element solution uhu_h.

Output. An indicator ηK≥0\eta_K \ge 0 for each triangle KK and the total η=(∑KηK2)1/2\eta = (\sum_K\eta_K^2)^{1/2}, which estimates the energy error ∥∇u−∇uh∥L2(Ω)\|\nabla u - \nabla u_h\|_{L^2(\Omega)}.

The algorithm

ZZ-ESTIMATE is the estimator. SPR-RECOVER is the recovery of the 1992 paper. The averaging recovery of the 1987 paper replaces lines L6 to L10 by the area weighted mean of the element gradients around each vertex.

  1. ZZ-ESTIMATE(mesh, U)
  2. 1G <- SPR-RECOVER(mesh, U) ▷ one vector per vertex
  3. 2for each triangle K do
  4. 3s <- (|K| / 3) * sum over the edge midpoints m of |G(m) - grad u_h on K|^2
  5. 4eta_K <- sqrt(s)
  6. 5return (eta_K for all K), sqrt(sum of eta_K^2)
  7. SPR-RECOVER(mesh, U)
  8. 6for each interior vertex v do
  9. 7fit p(x) = a + b x + c y to the gradients of the triangles at v, at their centroids, by least squares (one fit per component)
  10. 8G(v) <- p(v)
  11. 9for each boundary vertex w of the patch of v do add p(w) to the sum at w
  12. 10for each boundary vertex w do G(w) <- the mean of the sums at w
  13. 11return G

At line L3, G(m)G(m) is the mean of GG at the two ends of the edge, because GG is linear on the edge. The rule is exact, because the integrand is a quadratic polynomial on KK.

Example

One dimension, by hand. Take −u′′=−2-u'' = -2 on (0,1)(0, 1) with u(0)=0u(0) = 0 and u(1)=1u(1) = 1, so u=x2u = x^2. With 4 elements of size h=14h = \tfrac14, the linear finite element solution matches uu at the nodes, so its slope on an element is 22 times the midpoint.

Element Slope of uhu_h GG at the left end GG at the right end ηK2\eta_K^2 True ∥u′−uh′∥K2\|u' - u_h'\|_K^2
[0,14][0, \tfrac14] 14\tfrac14 0 12\tfrac12 1192\tfrac{1}{192} 1192\tfrac{1}{192}
[14,12][\tfrac14, \tfrac12] 34\tfrac34 12\tfrac12 1 1192\tfrac{1}{192} 1192\tfrac{1}{192}
[12,34][\tfrac12, \tfrac34] 54\tfrac54 1 32\tfrac32 1192\tfrac{1}{192} 1192\tfrac{1}{192}
[34,1][\tfrac34, 1] 74\tfrac74 32\tfrac32 2 1192\tfrac{1}{192} 1192\tfrac{1}{192}

At the interior node 14\tfrac14, the patch has the slopes 14\tfrac14 and 34\tfrac34 at the midpoints 18\tfrac18 and 38\tfrac38. The line through them is 2x2x, so G(14)=12G(\tfrac14) = \tfrac12, and its value at the boundary node 0 is 0. The same happens at every node, so G=2x=u′G = 2x = u' exactly. On each element G−uh′G - u_h' is 2(x−xm)2(x - x_m) with xmx_m the midpoint, and ∫K4(x−xm)2 dx=h3/3=1192\int_K 4(x - x_m)^2\,dx = h^3/3 = \tfrac{1}{192}. So η2=4192=148\eta^2 = \tfrac{4}{192} = \tfrac{1}{48}, equal to the true error, and the effectivity is exactly 1.

Two dimensions, measured. The reference code solves −Δu=2π2sin⁡(πx)sin⁡(πy)-\Delta u = 2\pi^2\sin(\pi x)\sin(\pi y) on the unit square with u=0u = 0 on the boundary, on uniform meshes of 2m22m^2 triangles, and compares the estimate with the exact energy error.

mm Triangles Error ee η\eta (SPR) η/e\eta / e (SPR) η\eta (averaging) η/e\eta / e (averaging)
4 32 0.8386 0.8337 0.9943 0.8213 0.9794
8 128 0.4318 0.4340 1.0052 0.4394 1.0176
16 512 0.2175 0.2184 1.0038 0.2200 1.0115
32 2048 0.1090 0.1091 1.0013 0.1096 1.0055

The error halves when hh halves, and the effectivity tends to 1. With the interior nodes moved at random by up to h/4h/4 in each direction, the effectivity at m=16m = 16 and m=32m = 32 was still within 1 percent of 1 for SPR in this test, but no theorem covers such meshes.

Correctness

The full proof is in the correctness proof. Line L3 integrates a quadratic polynomial with a rule that is exact for quadratics, so ηK\eta_K is exactly ∥G−∇uh∥L2(K)\|G - \nabla u_h\|_{L^2(K)}. A least squares fit of data that come from a linear polynomial returns that polynomial when the points are not on one line. So if uhu_h is linear on the whole domain, the recovery returns its gradient and every indicator is 0. The main fact is one line of algebra: by the triangle inequality, ∣η−e∣≤∥∇u−G∥|\eta - e| \le \|\nabla u - G\|. If the recovered gradient superconverges, that is ∥∇u−G∥/e→0\|\nabla u - G\| / e \to 0, then η/e→1\eta / e \to 1.

Proof: The ZZ indicators are computed exactly, vanish on linear solutions, and are asymptotically exact when the recovery superconvergesfull

Setting. T\mathcal{T} is a conforming triangulation of a polygon Ω\Omega, and uhu_h is a continuous piecewise linear function on it with nodal values UU. Its gradient ∇uh\nabla u_h is constant on each triangle. A recovery returns one vector G(z)∈R2G(z) \in \mathbb{R}^2 for each vertex zz, and GG also denotes the continuous piecewise linear vector field with these nodal values. The indicator is ηK=∥G−∇uh∥L2(K)\eta_K = \|G - \nabla u_h\|_{L^2(K)}, and the total is η=(∑KηK2)1/2=∥G−∇uh∥L2(Ω)\eta = (\sum_K \eta_K^2)^{1/2} = \|G - \nabla u_h\|_{L^2(\Omega)}. ZZ-ESTIMATE is lines L1 to L5 of the main page, and SPR-RECOVER is lines L6 to L11. Arithmetic is exact (real-RAM).

We prove four claims.

  1. (Exact integration.) Line L3 computes ηK2\eta_K^2 exactly.
  2. (Linear fit.) If the points of a patch do not all lie on one line and the data are the values of a linear polynomial qq at these points, the least squares fit at line L7 returns qq.
  3. (Consistency.) If uhu_h is linear on all of Ω\Omega, then both the SPR and the averaging recovery give G=∇uhG = \nabla u_h, and every ηK\eta_K is 0.
  4. (Asymptotic exactness.) Let uu be the exact solution and e=∥∇u−∇uh∥L2(Ω)e = \|\nabla u - \nabla u_h\|_{L^2(\Omega)}. Then ∣η−e∣≤∥∇u−G∥L2(Ω)|\eta - e| \le \|\nabla u - G\|_{L^2(\Omega)}. So if ∥∇u−G∥/e→0\|\nabla u - G\| / e \to 0 on a sequence of meshes, the effectivity index η/e\eta / e tends to 1.

Proof of 1. On KK, GG is linear and ∇uh\nabla u_h is constant, so each component of G−∇uhG - \nabla u_h is a linear function and ∣G−∇uh∣2|G - \nabla u_h|^2 is a polynomial of degree 2. The edge midpoint rule ∫Kp≈∣K∣3∑r=13p(mr)\int_K p \approx \tfrac{|K|}{3}\sum_{r=1}^{3} p(m_r), with mrm_r the midpoints of the edges, is exact for all polynomials of degree 2 on a triangle. (Check it on 11, on λi\lambda_i and on λiλj\lambda_i\lambda_j in barycentric coordinates: the integrals are ∣K∣|K|, ∣K∣/3|K|/3, ∣K∣/12|K|/12 for i≠ji \ne j and ∣K∣/6|K|/6 for i=ji = j, and the rule gives the same numbers.) A linear function at the midpoint of an edge is the mean of its values at the two ends, which is the formula used at line L3. Line L4 takes the square root. □\square

Proof of 2. The fit minimizes ∑t(a+bxt+cyt−dt)2\sum_t (a + b x_t + c y_t - d_t)^2 over (a,b,c)(a, b, c). The value 0 is the smallest possible, and (a,b,c)(a, b, c) equal to the coefficients of qq reaches it. The minimizer is unique: two minimizers p1p_1 and p2p_2 would both reach 0, so p1−p2p_1 - p_2 is a linear polynomial that is 0 at all points. A nonzero linear polynomial is 0 only on a line, and the points do not all lie on one line. So p1=p2=qp_1 = p_2 = q. The same condition makes the 3×33 \times 3 normal matrix regular, so Cramer's rule in the code finds this minimizer. □\square

Proof of 3. Let ∇uh=c\nabla u_h = c on every triangle. Averaging. Each nodal value is a weighted mean of copies of cc with positive weights, so it is cc. SPR. At an interior vertex the data at line L7 are the constant cc, which is a linear polynomial. If the centroids do not lie on one line, claim 2 gives the fit q=cq = c, and line L8 sets G(v)=cG(v) = c. If they lie on one line, the code uses the averaging value, which is also cc. At line L9 every evaluation of a fit is cc, so the mean at line L10 is cc. A boundary vertex that no interior patch reaches also takes the averaging value cc. So G≡cG \equiv c, and G−∇uh=0G - \nabla u_h = 0 on every triangle. □\square

Proof of 4. By the triangle inequality in L2(Ω)2L^2(\Omega)^2,

η=∥G−∇uh∥≤∥G−∇u∥+∥∇u−∇uh∥=∥∇u−G∥+e,\eta = \|G - \nabla u_h\| \le \|G - \nabla u\| + \|\nabla u - \nabla u_h\| = \|\nabla u - G\| + e,

and in the same way e≤∥∇u−G∥+ηe \le \|\nabla u - G\| + \eta. So ∣η−e∣≤∥∇u−G∥|\eta - e| \le \|\nabla u - G\|. Divide by e>0e > 0: ∣η/e−1∣≤∥∇u−G∥/e|\eta/e - 1| \le \|\nabla u - G\|/e, and the right side tends to 0 by the hypothesis. □\square

Remarks. Claim 4 is the theorem of Zienkiewicz and Zhu. Its hypothesis is a superconvergence property: the recovered gradient must be closer to ∇u\nabla u than the raw gradient by more than a constant factor. For P1 elements and smooth uu it is known on meshes with a structure, for example uniform meshes and meshes that are close to uniform in a precise sense. On general meshes, Carstensen and Bartels proved that averaging estimators are reliable and efficient up to constants and higher order terms, but the effectivity then does not have to tend to 1. The test file checks claims 2 and 3 on random data and random perturbed meshes, and it measures an effectivity within 2 percent of 1 on uniform meshes.

Cost. Each triangle sends its gradient to its three vertices. Each interior vertex solves one 3×33 \times 3 system with a patch of bounded size, and each triangle then does a fixed amount of work at lines L2 to L4. For a mesh with bounded vertex degree this is O(M)O(M) operations for MM triangles.

Complexity

For MM triangles of a mesh with bounded vertex degree, each step is local. Collecting the element gradients is Θ(M)\Theta(M), each vertex solves a 3×33 \times 3 least squares system in O(1)O(1) time, and lines L2 to L4 are Θ(M)\Theta(M). So the total is Θ(M)\Theta(M) time and Θ(M)\Theta(M) memory. This is much cheaper than the solve that produced uhu_h.

Properties

  • No equation needed. The estimator uses only uhu_h, so it is the same code for any second order problem. This is why many engineering codes use it.
  • Asymptotically exact under superconvergence. If ∥∇u−G∥=o(e)\|\nabla u - G\| = o(e), then η/e→1\eta / e \to 1. For linear triangles and smooth uu, this is known on uniform and almost uniform meshes.
  • Reliable up to constants on general meshes. Carstensen and Bartels proved that every averaging estimator bounds the error from above and below up to constants and higher order terms, on unstructured meshes.
  • Local. The indicator ηK\eta_K depends only on uhu_h in the patches of the vertices of KK.
  • Exact for linear solutions. If uhu_h is linear, all indicators are 0.

Variants and improvements

  • Simple averaging. The 1987 form takes the area weighted mean of the element gradients at each vertex. It is simpler than SPR and gives similar results on good meshes, as the table shows.
  • Higher order elements. For degree pp, SPR fits a polynomial of degree pp to the gradients at the Gauss points of the patch elements.
  • Stress recovery. In elasticity the same fit is applied to the stress components, which is the original engineering use.
  • Polynomial preserving recovery. Zhang and Naga fit the nodal values of uhu_h instead of the gradients, which gives superconvergence on a wider class of meshes.
  • Equilibrated recoveries. Some methods recover a flux that also satisfies the balance law. These estimators give guaranteed upper bounds with explicit constants, which ZZ does not.

When to use it

Use ZZ when you need a cheap, robust indicator for refinement and you do not want to code element residuals and jumps for each new equation. It is a good choice for engineering problems with smooth solutions on good meshes. Use the residual estimator when a proof of convergence of the adaptive loop is needed, because the convergence theory of AFEM is built on it. Use the dual weighted residual method when you need the error in one output quantity, not in the energy norm.

Pitfalls

  • Exactness needs superconvergence. Near a singularity or on a mesh with a bad structure, the recovered gradient is not much better than ∇uh\nabla u_h, and the effectivity can be far from 1. The estimator then still marks the right region in most cases, but the number η\eta is not a guaranteed bound.
  • Boundary vertices. A fit centered at a boundary vertex uses a one sided patch and is less accurate. SPR uses the fits of the interior patches nearby, as at lines L9 and L10.
  • Collinear centroids. A patch with fewer than 3 triangles, or with centroids on one line, gives a singular least squares system. The code then uses the averaged value.
  • Scaling. Center the coordinates at the vertex before the fit, as the code does, or the normal equations become badly conditioned on small elements.
  • Data oscillation. The estimator does not see the right side ff, so it misses error caused by a rough ff on a coarse mesh.

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.

scisparse.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the scientific-computing pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Tridiagonal solvers, sparse matrices and simple iterative solvers.

A vector is a list. A sparse matrix is a list of rows, and each row is a
dict that maps a column index to a value. Entries may be int, float or
fractions.Fraction. thomas, thomas_periodic, spmatvec, from_dense and
to_dense keep Fraction entries exact. cg takes square roots and works in
float.

API (fixed; other pages copy this file byte for byte):
    thomas(a, b, c, d)             solve a tridiagonal system. Row i reads
                                   a[i] x[i-1] + b[i] x[i] + c[i] x[i+1] = d[i];
                                   a[0] and c[n-1] are not used.
    thomas_periodic(a, b, c, d)    solve a cyclic tridiagonal system: as
                                   thomas, but a[0] multiplies x[n-1] and
                                   c[n-1] multiplies x[0]. Uses the
                                   Sherman-Morrison formula. n >= 3.
    from_dense(A)                  sparse copy of a dense matrix (drops zeros)
    to_dense(A, ncols=None)        dense copy of a sparse matrix
    spmatvec(A, x)                 A times x
    poisson2d(nx, ny, dx, dy, bc="dirichlet")
                                   the matrix of MINUS the 5-point Laplacian
                                   on nx by ny unknowns, numbered
                                   k = i + nx * j (i along x, j along y).
                                   bc = "dirichlet": unknowns at the interior
                                   nodes ((i + 1) dx, (j + 1) dy) with zero
                                   values outside; the matrix is symmetric
                                   positive definite.
                                   bc = "periodic": the grid wraps around in
                                   both directions; the matrix is symmetric
                                   positive semidefinite, and its null space
                                   is the constant vectors.
                                   bc = "neumann": unknowns at cell centers,
                                   zero normal derivative at the walls (a
                                   missing neighbor drops out of the
                                   stencil); null space as for "periodic".
    cg(A, b, tol=1e-10, maxit=None, x0=None)
                                   conjugate gradient for a symmetric
                                   positive (semi)definite A. Stops when
                                   ||b - A x||_2 <= tol * ||b||_2. Returns
                                   (x, iterations). For a singular A, b must
                                   be in the range of A (for the Poisson
                                   matrices above: sum(b) = 0).
    gauss_seidel(A, b, iters, x0=None)
                                   iters forward Gauss-Seidel sweeps; every
                                   row needs a nonzero diagonal entry.
"""

import math


def thomas(a, b, c, d):
    n = len(d)
    if n == 0:
        return []
    cp = [0] * n
    dp = [0] * n
    cp[0] = c[0] / b[0] if n > 1 else 0
    dp[0] = d[0] / b[0]
    for i in range(1, n):
        m = b[i] - a[i] * cp[i - 1]
        if i < n - 1:
            cp[i] = c[i] / m
        dp[i] = (d[i] - a[i] * dp[i - 1]) / m
    x = [0] * n
    x[n - 1] = dp[n - 1]
    for i in range(n - 2, -1, -1):
        x[i] = dp[i] - cp[i] * x[i + 1]
    return x


def thomas_periodic(a, b, c, d):
    """Cyclic tridiagonal solve. A = T + u v^T with u = (gamma, 0, .., 0, c[n-1])
    and v = (1, 0, .., 0, a[0] / gamma), so T is tridiagonal."""
    n = len(d)
    if n < 3:
        raise ValueError("thomas_periodic needs n >= 3")
    gamma = -b[0]
    bb = list(b)
    bb[0] = b[0] - gamma
    bb[n - 1] = b[n - 1] - c[n - 1] * a[0] / gamma
    y = thomas(a, bb, c, d)
    u = [0] * n
    u[0] = gamma
    u[n - 1] = c[n - 1]
    z = thomas(a, bb, c, u)
    vy = y[0] + a[0] * y[n - 1] / gamma
    vz = z[0] + a[0] * z[n - 1] / gamma
    f = vy / (1 + vz)
    return [y[i] - f * z[i] for i in range(n)]


def from_dense(A):
    return [{j: v for j, v in enumerate(row) if v != 0} for row in A]


def to_dense(A, ncols=None):
    if ncols is None:
        ncols = len(A)
    out = []
    for row in A:
        r = [0] * ncols
        for j, v in row.items():
            r[j] = v
        out.append(r)
    return out


def spmatvec(A, x):
    return [sum(v * x[j] for j, v in row.items()) for row in A]


def poisson2d(nx, ny, dx, dy, bc="dirichlet"):
    if bc not in ("dirichlet", "periodic", "neumann"):
        raise ValueError("bc must be dirichlet, periodic or neumann")
    cx = 1 / (dx * dx)
    cy = 1 / (dy * dy)
    A = []
    for j in range(ny):
        for i in range(nx):
            row = {}
            k = i + nx * j
            for (ii, jj, w) in ((i - 1, j, cx), (i + 1, j, cx), (i, j - 1, cy), (i, j + 1, cy)):
                inside = 0 <= ii < nx and 0 <= jj < ny
                if bc == "periodic":
                    ii %= nx
                    jj %= ny
                    inside = True
                if bc == "neumann" and not inside:
                    continue
                row[k] = row.get(k, 0) + w
                if inside:
                    m = ii + nx * jj
                    row[m] = row.get(m, 0) - w
            A.append({m: v for m, v in row.items() if v != 0})
    return A


def cg(A, b, tol=1e-10, maxit=None, x0=None):
    n = len(b)
    if maxit is None:
        maxit = 10 * n
    x = [0.0] * n if x0 is None else [float(v) for v in x0]
    if x0 is None:
        r = [float(v) for v in b]
    else:
        ax = spmatvec(A, x)
        r = [b[i] - ax[i] for i in range(n)]
    bnorm = math.sqrt(sum(float(v) * float(v) for v in b))
    stop = tol * bnorm
    rr = sum(v * v for v in r)
    if math.sqrt(rr) <= stop:
        return x, 0
    p = list(r)
    for it in range(1, maxit + 1):
        ap = spmatvec(A, p)
        pap = sum(p[i] * ap[i] for i in range(n))
        if pap <= 0:
            return x, it
        alpha = rr / pap
        for i in range(n):
            x[i] += alpha * p[i]
            r[i] -= alpha * ap[i]
        rr_new = sum(v * v for v in r)
        if math.sqrt(rr_new) <= stop:
            return x, it
        beta = rr_new / rr
        rr = rr_new
        p = [r[i] + beta * p[i] for i in range(n)]
    return x, maxit


def gauss_seidel(A, b, iters, x0=None):
    n = len(b)
    x = [0] * n if x0 is None else list(x0)
    for _ in range(iters):
        for i in range(n):
            row = A[i]
            s = b[i]
            diag = 0
            for j, v in row.items():
                if j == i:
                    diag = v
                else:
                    s -= v * x[j]
            x[i] = s / diag
    return x
zienkiewicz_zhu_estimator.py 225 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/zienkiewicz-zhu-estimator/. The authors are listed in prov/4WBQ50.jsonl.

"""Zienkiewicz-Zhu error estimator for P1 triangles in 2D.

The P1 solution u_h has a constant gradient on each triangle. The estimator
recovers a continuous piecewise linear gradient G from it and returns
eta_K = ||G - grad u_h||_{L2(K)} on every triangle. Two recoveries are here:
- superconvergent patch recovery (SPR, Zienkiewicz and Zhu 1992): at each
  interior vertex, fit a linear polynomial to the element gradients at the
  centroids of the patch by least squares, and evaluate it at the vertex;
  a boundary vertex takes the mean of the fits of the interior patches
  that contain it;
- simple averaging (Zienkiewicz and Zhu 1987): the area-weighted mean of
  the element gradients around each vertex.

A mesh is (coords, elements) with coords a list of (x, y) and elements a
list of vertex triples. Cost: O(M) for M triangles of bounded vertex degree
(real-RAM), after the solve.
"""

import math

import scisparse


def square_grid(m):
    """Return (coords, elements) of the unit square with m by m squares, each cut by the diagonal from (x, y) to (x + h, y + h)."""
    coords = [(i / m, j / m) for j in range(m + 1) for i in range(m + 1)]
    elements = []
    for j in range(m):
        for i in range(m):
            a = i + (m + 1) * j
            b, c, d = a + 1, a + m + 2, a + m + 1
            elements.append([a, b, c])
            elements.append([a, c, d])
    return coords, elements


def boundary_nodes(coords, elements):
    """Return the set of vertices on edges that belong to one element only."""
    count = {}
    for z in elements:
        for r in range(3):
            e = tuple(sorted((z[r], z[(r + 1) % 3])))
            count[e] = count.get(e, 0) + 1
    return {v for e, c in count.items() if c == 1 for v in e}


def _geometry(coords, z):
    (x0, y0), (x1, y1), (x2, y2) = coords[z[0]], coords[z[1]], coords[z[2]]
    d = (x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0)
    grads = [((y1 - y2) / d, (x2 - x1) / d), ((y2 - y0) / d, (x0 - x2) / d),
             ((y0 - y1) / d, (x1 - x0) / d)]
    return abs(d) / 2, grads


def solve_p1(coords, elements, f, g, tol=1e-11):
    """Return nodal values of the P1 solution of -Laplacian(u) = f, u = g on the boundary.

    The load uses the edge midpoint rule (exact for quadratics).
    """
    n = len(coords)
    bnd = boundary_nodes(coords, elements)
    U = [0.0] * n
    for v in bnd:
        U[v] = g(*coords[v])
    free = [v for v in range(n) if v not in bnd]
    index = {v: i for i, v in enumerate(free)}
    A = [dict() for _ in free]
    b = [0.0] * len(free)
    for z in elements:
        area, grads = _geometry(coords, z)
        mids = []
        for r in range(3):
            p, q = coords[z[(r + 1) % 3]], coords[z[(r + 2) % 3]]
            mids.append(f((p[0] + q[0]) / 2, (p[1] + q[1]) / 2))
        for r in range(3):
            i = index.get(z[r])
            if i is None:
                continue
            # phi_r is 1/2 at the midpoints of the two edges at vertex r, 0 at the third
            b[i] += area / 3 * 0.5 * (mids[(r + 1) % 3] + mids[(r + 2) % 3])
            for s in range(3):
                val = area * (grads[r][0] * grads[s][0] + grads[r][1] * grads[s][1])
                j = index.get(z[s])
                if j is None:
                    b[i] -= val * U[z[s]]
                else:
                    A[i][j] = A[i].get(j, 0.0) + val
    if free:
        x, _ = scisparse.cg(A, b, tol=tol, maxit=20 * len(free) + 100)
        for v, val in zip(free, x):
            U[v] = val
    return U


def element_gradients(coords, elements, U):
    """Return the constant gradient of the P1 function U on each element."""
    out = []
    for z in elements:
        _, grads = _geometry(coords, z)
        out.append((sum(U[z[r]] * grads[r][0] for r in range(3)),
                    sum(U[z[r]] * grads[r][1] for r in range(3))))
    return out


def _fit_linear(points, values):
    """Least squares fit of a + b x + c y to the values at the points; return (a, b, c) or None."""
    s = [[0.0] * 3 for _ in range(3)]
    t = [0.0] * 3
    for (x, y), v in zip(points, values):
        row = (1.0, x, y)
        for i in range(3):
            t[i] += row[i] * v
            for j in range(3):
                s[i][j] += row[i] * row[j]
    det = (s[0][0] * (s[1][1] * s[2][2] - s[1][2] * s[2][1])
           - s[0][1] * (s[1][0] * s[2][2] - s[1][2] * s[2][0])
           + s[0][2] * (s[1][0] * s[2][1] - s[1][1] * s[2][0]))
    scale = max(abs(s[i][j]) for i in range(3) for j in range(3))
    if abs(det) <= 1e-12 * scale ** 3:
        return None
    out = []
    for k in range(3):  # Cramer's rule
        m = [[t[i] if j == k else s[i][j] for j in range(3)] for i in range(3)]
        dk = (m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1])
              - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])
              + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]))
        out.append(dk / det)
    return tuple(out)


def recover_average(coords, elements, U):
    """Return the recovered nodal gradients by area-weighted averaging (ZZ 1987)."""
    n = len(coords)
    gsum = [[0.0, 0.0] for _ in range(n)]
    wsum = [0.0] * n
    for z, (gx, gy) in zip(elements, element_gradients(coords, elements, U)):
        area, _ = _geometry(coords, z)
        for v in z:
            gsum[v][0] += area * gx
            gsum[v][1] += area * gy
            wsum[v] += area
    return [(gsum[v][0] / wsum[v], gsum[v][1] / wsum[v]) if wsum[v] else (0.0, 0.0) for v in range(n)]


def recover_spr(coords, elements, U):
    """Return the recovered nodal gradients by superconvergent patch recovery (ZZ 1992)."""
    n = len(coords)
    grads = element_gradients(coords, elements, U)
    patch = [[] for _ in range(n)]
    for t, z in enumerate(elements):
        for v in z:
            patch[v].append(t)
    bnd = boundary_nodes(coords, elements)
    G = [None] * n
    acc = {v: [0.0, 0.0, 0] for v in bnd}
    for v in range(n):  # @line L6
        if v in bnd:
            continue
        xv, yv = coords[v]
        pts, gxs, gys = [], [], []
        for t in patch[v]:
            z = elements[t]
            pts.append((sum(coords[w][0] for w in z) / 3 - xv, sum(coords[w][1] for w in z) / 3 - yv))
            gxs.append(grads[t][0])
            gys.append(grads[t][1])
        px, py = _fit_linear(pts, gxs), _fit_linear(pts, gys)  # @line L7
        if px is None or py is None:
            continue
        G[v] = (px[0], py[0])  # @line L8
        for w in {w for t in patch[v] for w in elements[t]} & bnd:  # @line L9
            dx, dy = coords[w][0] - xv, coords[w][1] - yv
            a = acc[w]
            a[0] += px[0] + px[1] * dx + px[2] * dy
            a[1] += py[0] + py[1] * dx + py[2] * dy
            a[2] += 1
    fallback = recover_average(coords, elements, U)
    for v in range(n):
        if v in bnd and acc[v][2] > 0:
            G[v] = (acc[v][0] / acc[v][2], acc[v][1] / acc[v][2])  # @line L10
        elif G[v] is None:
            G[v] = fallback[v]
    return G  # @line L11


def zz_estimator(coords, elements, U, recovery="spr"):
    """Return the list of indicators eta_K = ||G - grad u_h||_K and the total eta."""
    G = recover_spr(coords, elements, U) if recovery == "spr" else recover_average(coords, elements, U)  # @line L1
    grads = element_gradients(coords, elements, U)
    eta = []
    for t, z in enumerate(elements):  # @line L2
        area, _ = _geometry(coords, z)
        gx, gy = grads[t]
        s = 0.0
        for r in range(3):  # edge midpoint rule, exact for the quadratic integrand  # @line L3
            a, b = z[(r + 1) % 3], z[(r + 2) % 3]
            dx = (G[a][0] + G[b][0]) / 2 - gx
            dy = (G[a][1] + G[b][1]) / 2 - gy
            s += area / 3 * (dx * dx + dy * dy)
        eta.append(math.sqrt(s))  # @line L4
    return eta, math.sqrt(sum(e * e for e in eta))  # @line L5


# 7-point rule of degree 5 on the reference triangle, in barycentric coordinates.
_A1, _B1 = 0.059715871789770, 0.470142064105115
_A2, _B2 = 0.797426985353087, 0.101286507323456
_W0, _W1, _W2 = 0.225, 0.132394152788506, 0.125939180544827
QUAD7 = [((1 / 3, 1 / 3, 1 / 3), _W0),
         ((_A1, _B1, _B1), _W1), ((_B1, _A1, _B1), _W1), ((_B1, _B1, _A1), _W1),
         ((_A2, _B2, _B2), _W2), ((_B2, _A2, _B2), _W2), ((_B2, _B2, _A2), _W2)]


def energy_error(coords, elements, U, grad_u):
    """Return |u - u_h|_1 computed with the 7-point rule on each element."""
    total = 0.0
    for z, (gx, gy) in zip(elements, element_gradients(coords, elements, U)):
        area, _ = _geometry(coords, z)
        for lam, w in QUAD7:
            x = sum(lam[r] * coords[z[r]][0] for r in range(3))
            y = sum(lam[r] * coords[z[r]][1] for r in range(3))
            ux, uy = grad_u(x, y)
            total += w * area * ((ux - gx) ** 2 + (uy - gy) ** 2)
    return math.sqrt(total)
test_zienkiewicz_zhu_estimator.py 105 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/zienkiewicz-zhu-estimator/. The authors are listed in prov/4WBQ50.jsonl.

import math
import random

import zienkiewicz_zhu_estimator as Z

PI = math.pi


def u(x, y):
    return math.sin(PI * x) * math.sin(PI * y)


def grad_u(x, y):
    return (PI * math.cos(PI * x) * math.sin(PI * y), PI * math.sin(PI * x) * math.cos(PI * y))


def f(x, y):
    return 2 * PI * PI * u(x, y)


def zero(x, y):
    return 0.0


def perturbed_grid(m, seed, amount=0.25):
    coords, elements = Z.square_grid(m)
    bnd = Z.boundary_nodes(coords, elements)
    rng = random.Random(seed)
    h = 1.0 / m
    coords = [p if v in bnd else (p[0] + rng.uniform(-amount, amount) * h, p[1] + rng.uniform(-amount, amount) * h)
              for v, p in enumerate(coords)]
    return coords, elements


def test_effectivity_near_one_on_regular_grid():
    for m in (16, 32):
        c, e = Z.square_grid(m)
        U = Z.solve_p1(c, e, f, zero)
        err = Z.energy_error(c, e, U, grad_u)
        _, eta_spr = Z.zz_estimator(c, e, U, "spr")
        _, eta_avg = Z.zz_estimator(c, e, U, "average")
        assert 0.98 < eta_spr / err < 1.02
        assert 0.97 < eta_avg / err < 1.03


def test_error_and_estimator_halve_with_h():
    rows = []
    for m in (8, 16):
        c, e = Z.square_grid(m)
        U = Z.solve_p1(c, e, f, zero)
        rows.append((Z.energy_error(c, e, U, grad_u), Z.zz_estimator(c, e, U)[1]))
    assert 1.9 < rows[0][0] / rows[1][0] < 2.1
    assert 1.9 < rows[0][1] / rows[1][1] < 2.1


def test_effectivity_on_perturbed_grid():
    c, e = perturbed_grid(16, seed=5)
    U = Z.solve_p1(c, e, f, zero)
    err = Z.energy_error(c, e, U, grad_u)
    _, eta = Z.zz_estimator(c, e, U)
    assert 0.9 < eta / err < 1.1


def test_linear_solution_gives_zero_estimate():
    for seed in range(3):
        c, e = perturbed_grid(6, seed=seed, amount=0.3)
        lin = lambda x, y: 1.0 + 2.0 * x - 3.0 * y
        U = Z.solve_p1(c, e, zero, lin)
        assert max(abs(U[v] - lin(*c[v])) for v in range(len(c))) < 1e-9
        for rec in ("spr", "average"):
            eta, total = Z.zz_estimator(c, e, U, rec)
            assert total < 1e-8
            assert len(eta) == len(e)


def test_least_squares_fit_reproduces_linear_data():
    rng = random.Random(11)
    for _ in range(50):
        pts = [(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(rng.randint(3, 8))]
        a, b, cc = rng.uniform(-2, 2), rng.uniform(-2, 2), rng.uniform(-2, 2)
        fit = Z._fit_linear(pts, [a + b * x + cc * y for x, y in pts])
        assert fit is not None
        assert max(abs(p - q) for p, q in zip(fit, (a, b, cc))) < 1e-9
    assert Z._fit_linear([(0, 0), (1, 1), (2, 2)], [1.0, 2.0, 3.0]) is None  # collinear points


def test_indicator_is_exact_integral():
    # one triangle with prescribed nodal gradients G and a P1 function U
    coords = [(0.0, 0.0), (2.0, 0.0), (0.0, 1.0)]
    elements = [[0, 1, 2]]
    U = [0.0, 2.0, 0.0]  # u_h = x, gradient (1, 0)
    G = [(1.0, 0.0), (3.0, 0.0), (1.0, 0.0)]  # G - grad u_h = (x, 0)
    gx, gy = Z.element_gradients(coords, elements, U)[0]
    assert abs(gx - 1.0) < 1e-14 and abs(gy) < 1e-14
    # integral of x^2 over the triangle with legs 2 and 1 is 2/3
    original = Z.recover_spr
    try:
        Z.recover_spr = lambda c, e, v: G
        eta, total = Z.zz_estimator(coords, elements, U)
    finally:
        Z.recover_spr = original
    assert abs(eta[0] ** 2 - 2.0 / 3.0) < 1e-13

History

Olgierd Zienkiewicz and Jian Zhong Zhu published the estimator in 1987. It came from engineering practice: stress values averaged at the nodes were known to be more accurate than the raw element stresses, and the difference was a natural measure of the error. In 1992 they gave the superconvergent patch recovery, which fits a polynomial to the values at the points where the finite element gradient is most accurate, and they showed the effectivity tends to 1 in many tests. The method spread quickly in commercial codes. Mathematical analysis followed: superconvergence results for the recovered gradient on structured meshes, and in 2002 the proof by Carsten Carstensen and Soren Bartels that averaging gives a reliable estimate on any mesh.

References

  1. O. C. Zienkiewicz and J. Z. Zhu, A simple error estimator and adaptive procedure for practical engineering analysis, International Journal for Numerical Methods in Engineering 24(2) (1987) 337-357, the estimator with the averaged gradient and the effectivity index
  2. O. C. Zienkiewicz and J. Z. Zhu, The superconvergent patch recovery and a posteriori error estimates. Part 1: The recovery technique, International Journal for Numerical Methods in Engineering 33(7) (1992) 1331-1364, the least squares fit on element patches at the superconvergent points
  3. O. C. Zienkiewicz and J. Z. Zhu, The superconvergent patch recovery and a posteriori error estimates. Part 2: Error estimates and adaptivity, International Journal for Numerical Methods in Engineering 33(7) (1992) 1365-1382, the asymptotic exactness argument and the adaptive examples
  4. Carsten Carstensen and Soren Bartels, Each averaging technique yields reliable a posteriori error control in FEM on unstructured grids. Part I: Low order conforming, nonconforming, and mixed FEM, Mathematics of Computation 71(239) (2002) 945-969, reliability of averaging estimators on general meshes
  5. Mark Ainsworth and J. Tinsley Oden, A Posteriori Error Estimation in Finite Element Analysis, Wiley (2000), the chapter on recovery based estimators

About this page

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

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example