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
- Model
- Real RAM
- Properties
- asymptotically exact on superconvergent meshesdeterministiclocalproblem independent
- Evidence
- Proof sketchCode in 1 languages
- 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 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 from , called the recovered gradient, and uses as the error indicator of element . The superconvergent patch recovery (SPR) computes 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 is much closer to the true gradient than is, the estimate is asymptotically exact: 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 of a continuous piecewise linear finite element solution .
Output. An indicator for each triangle and the total , which estimates the energy error .
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.
ZZ-ESTIMATE(mesh, U)- 1
G <- SPR-RECOVER(mesh, U) ▷ one vector per vertex - 2
for each triangle K do - 3
s <- (|K| / 3) * sum over the edge midpoints m of |G(m) - grad u_h on K|^2 - 4
eta_K <- sqrt(s) - 5
return (eta_K for all K), sqrt(sum of eta_K^2) SPR-RECOVER(mesh, U)- 6
for each interior vertex v do - 7
fit 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) - 8
G(v) <- p(v) - 9
for each boundary vertex w of the patch of v do add p(w) to the sum at w - 10
for each boundary vertex w do G(w) <- the mean of the sums at w - 11
return G
At line L3, is the mean of at the two ends of the edge, because is linear on the edge. The rule is exact, because the integrand is a quadratic polynomial on .
Example
One dimension, by hand. Take on with and , so . With 4 elements of size , the linear finite element solution matches at the nodes, so its slope on an element is times the midpoint.
| Element | Slope of | at the left end | at the right end | True | |
|---|---|---|---|---|---|
| 0 | |||||
| 1 | |||||
| 1 | |||||
| 2 |
At the interior node , the patch has the slopes and at the midpoints and . The line through them is , so , and its value at the boundary node 0 is 0. The same happens at every node, so exactly. On each element is with the midpoint, and . So , equal to the true error, and the effectivity is exactly 1.
Two dimensions, measured. The reference code solves on the unit square with on the boundary, on uniform meshes of triangles, and compares the estimate with the exact energy error.
| Triangles | Error | (SPR) | (SPR) | (averaging) | (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 halves, and the effectivity tends to 1. With the interior nodes moved at random by up to in each direction, the effectivity at and 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 is exactly . 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 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, . If the recovered gradient superconverges, that is , then .
Proof: The ZZ indicators are computed exactly, vanish on linear solutions, and are asymptotically exact when the recovery superconvergesfull
Setting. is a conforming triangulation of a polygon , and is a continuous piecewise linear function on it with nodal values . Its gradient is constant on each triangle. A recovery returns one vector for each vertex , and also denotes the continuous piecewise linear vector field with these nodal values. The indicator is , and the total is . 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.
- (Exact integration.) Line L3 computes exactly.
- (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 at these points, the least squares fit at line L7 returns .
- (Consistency.) If is linear on all of , then both the SPR and the averaging recovery give , and every is 0.
- (Asymptotic exactness.) Let be the exact solution and . Then . So if on a sequence of meshes, the effectivity index tends to 1.
Proof of 1. On , is linear and is constant, so each component of is a linear function and is a polynomial of degree 2. The edge midpoint rule , with the midpoints of the edges, is exact for all polynomials of degree 2 on a triangle. (Check it on , on and on in barycentric coordinates: the integrals are , , for and for , 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.
Proof of 2. The fit minimizes over . The value 0 is the smallest possible, and equal to the coefficients of reaches it. The minimizer is unique: two minimizers and would both reach 0, so 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 . The same condition makes the normal matrix regular, so Cramer's rule in the code finds this minimizer.
Proof of 3. Let on every triangle. Averaging. Each nodal value is a weighted mean of copies of with positive weights, so it is . SPR. At an interior vertex the data at line L7 are the constant , which is a linear polynomial. If the centroids do not lie on one line, claim 2 gives the fit , and line L8 sets . If they lie on one line, the code uses the averaging value, which is also . At line L9 every evaluation of a fit is , so the mean at line L10 is . A boundary vertex that no interior patch reaches also takes the averaging value . So , and on every triangle.
Proof of 4. By the triangle inequality in ,
and in the same way . So . Divide by : , and the right side tends to 0 by the hypothesis.
Remarks. Claim 4 is the theorem of Zienkiewicz and Zhu. Its hypothesis is a superconvergence property: the recovered gradient must be closer to than the raw gradient by more than a constant factor. For P1 elements and smooth 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 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 operations for triangles.
Complexity
For triangles of a mesh with bounded vertex degree, each step is local. Collecting the element gradients is , each vertex solves a least squares system in time, and lines L2 to L4 are . So the total is time and memory. This is much cheaper than the solve that produced .
Properties
- No equation needed. The estimator uses only , so it is the same code for any second order problem. This is why many engineering codes use it.
- Asymptotically exact under superconvergence. If , then . For linear triangles and smooth , 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 depends only on in the patches of the vertices of .
- Exact for linear solutions. If 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 , SPR fits a polynomial of degree 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 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 , and the effectivity can be far from 1. The estimator then still marks the right region in most cases, but the number 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 , so it misses error caused by a rough 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.
# 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
- 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
- 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 4WBQ50 Edit this page History Report an error Markdown