Algorithmcore
Adaptive finite element method
Also called AFEM, solve-estimate-mark-refine loop.
Repeats solve, estimate, mark and refine, so the mesh concentrates where the error indicator is large.
- Solves
- Poisson equation
- Time
- O(k M log M + S) average
- Space
- Θ(M) extra
- Where
- M = the number of triangles of the final mesh; S = the total cost of the k linear solves; k = the number of steps
- Model
- Real RAM
- Properties
- contraction with dorfler markingdeterministicerror never increasesnested spaces
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Ivo Babuska, Werner C. Rheinboldt, Willy Dorfler, Peter Binev, Wolfgang Dahmen, Ronald DeVore, Rob Stevenson, J. Manuel Cascon, Christian Kreuzer, Ricardo H. Nochetto, Kunibert G. Siebert, 1978
The adaptive finite element method (AFEM) repeats four steps: SOLVE the discrete problem on the current mesh, ESTIMATE the error on each element with an a posteriori error estimator, MARK the elements with large indicators, and REFINE them by newest vertex bisection. The mesh gets fine only where the solution needs it, for example near a reentrant corner, where the solution has a singularity that uniform refinement resolves slowly. With Dorfler marking, an exact solve and the residual estimator, the error plus a multiple of the estimator shrinks by a fixed factor in each step, and the AFEM optimality theorem shows that the error decays at the best rate that any sequence of such meshes can reach.
In plain words
A uniform mesh spends the same effort everywhere, also where the solution is smooth and easy. The adaptive method starts with a coarse mesh and lets the computed solution show where the effort should go. After each solve, it measures for each triangle how badly the solution fails to satisfy the equation there. It refines the triangles with the largest values, solves again on the new mesh, and repeats. Near a corner where the solution is rough, the triangles get very small. Far from it, they stay large. For the same accuracy, the adaptive mesh can need far fewer unknowns than a uniform one.
The problem
Input. A polygon , the model problem in with on (the code takes ), a conforming initial triangulation with refinement edges, a marking parameter , and a stopping rule: a tolerance for the estimator, a maximum number of unknowns or a maximum number of steps.
Output. A sequence of nested triangulations and continuous P1 Galerkin solutions with error indicators , where the last mesh meets the stopping rule. The aim is a small energy error for the number of unknowns .
The algorithm
The estimator is the residual estimator in the form of Cascon, Kreuzer, Nochetto and Siebert, with :
The jump of the normal derivative across an interior edge is constant on the edge for P1 functions. The element term has no because is linear on each triangle.
AFEM(T0, f, g, theta, max_nodes, max_steps)- 1
for k <- 0, 1, ..., max_steps - 1 do ▷ T <- T0 before the first pass - 2
U <- SOLVE(T, f, g) ▷ P1 Galerkin solution, conjugate gradients - 3
eta <- ESTIMATE(T, U, f) ▷ eta(K)^2 for every triangle K - 4
if the number of nodes of T > max_nodes then - 5
break - 6
M <- DORFLER(eta, theta) ▷ smallest set with sum of eta(K)^2 >= theta eta^2 - 7
T <- REFINE(T, M) ▷ newest vertex bisection with closure - 8
return the list of (T, U, eta) of all passes
With the code marks every triangle, and the loop becomes uniform refinement by bisection. This gives the comparison in the example below.
Example
One free node, by hand. Take the unit square with and , and refine the two initial triangles once, so that the mesh has four triangles of area around the center . The only free node is . Its hat function has gradient of length on each triangle, so the stiffness entry is . The load is , so . The exact value of the solution at the center is about .
For the estimator, and the element term is . On the triangle with corners , , the solution is , and on its neighbor with corners , , it is . Across the shared half diagonal, with unit normal , the jump of the normal derivative has size . The edge has length , so the edge term is . Each triangle has two interior edges, so
All four indicators are equal. With , line L6 marks two triangles, because two of the four reach half of the sum. The test file checks these numbers.
The L-shaped domain. Take , and equal to the exact solution in polar coordinates. The gradient of is infinite at the reentrant corner, and is not in . The initial mesh has six triangles. The reference code with max_nodes = 1200 gives the following energy errors, where is the number of free nodes.
| Method | Step | ||||
|---|---|---|---|---|---|
| uniform | 3 | 17 | 0.2288 | 0.6896 | 3.01 |
| uniform | 6 | 161 | 0.1188 | 0.3667 | 3.09 |
| uniform | 9 | 1473 | 0.0606 | 0.1886 | 3.11 |
| adaptive, | 5 | 14 | 0.1967 | 0.6767 | 3.44 |
| adaptive, | 10 | 99 | 0.0866 | 0.3068 | 3.54 |
| adaptive, | 13 | 266 | 0.0525 | 0.1888 | 3.60 |
| adaptive, | 18 | 1376 | 0.0231 | 0.0847 | 3.67 |
A least squares fit of error against for gives the slope for uniform refinement and for the adaptive loop. The theory predicts for uniform meshes, because is only in , and , the best rate of P1 elements in 2D, for the adaptive meshes. The uniform slope is still pre-asymptotic. To reach an error of , the uniform mesh needs 1473 unknowns and the adaptive mesh needs about 200. The effectivity index stays between 2.6 and 3.7 over all steps of both runs. These are measurements on this problem, not bounds.
Correctness
The full proof is in the correctness proof. Each step is well defined because the P1 Galerkin matrix is symmetric positive definite, and NVB keeps the mesh conforming, so the spaces are nested. Galerkin orthogonality on nested spaces gives the Pythagoras identity , so the error never grows. The estimator reduction lemma says that a bisection cuts at least in half, so the estimator of the old solution on the new mesh loses a fixed fraction of the marked part, up to a term in . With Dorfler marking and the reliability bound , these combine into the contraction
Proof: The adaptive loop with Dorfler marking and newest vertex bisection contracts the errorfull
Setting. is a polygon, and solves for all . The energy norm is . AFEM starts from a conforming triangulation and builds by the loop of the main page, lines L1 to L8. is the space of continuous piecewise linear functions on that vanish on , and is the Galerkin solution. For and , with and the jump of across interior edges,
For P1 functions inside each triangle, so the element residual is . We assume:
- (Exact solve.) is the exact Galerkin solution on .
- (Marking.) satisfies for a fixed .
- (Refinement.) is the output of newest vertex bisection for . So it is conforming, every is bisected at least once, and all triangles stay in finitely many similarity classes (see newest vertex bisection).
- (Data.) The integrals of in the load vector and in are exact. The code uses the centroid rule, which is exact when is constant on each triangle of , as in the tests ( and ).
We prove three claims.
- (Well defined.) Each step has a unique , and the loop stops.
- (Reliability is used, not proved.) There is that depends only on the similarity classes of with . This is the standard upper bound of the residual error estimator (Verfurth 2013, Chapter 1), and we use it as a lemma.
- (Contraction.) There are and , which depend only on and on the similarity classes of , such that for every
So and at least as fast as in the step count. This is the contraction theorem of Cascon, Kreuzer, Nochetto and Siebert (2008), in the special case of the Laplacian and P1 elements.
Proof of 1. The Galerkin matrix of is symmetric. For in the form is positive, because a function in with zero gradient is zero (Poincare inequality). So the matrix is positive definite, and exists and is unique. Conjugate gradients solve such a system, in exact arithmetic, in at most steps. The loop at line L1 has at most max_steps passes. Line L6 marks a nonempty set when , and each bisection adds one vertex, so the node count grows in each pass, and line L4 stops the loop when it passes max_nodes.
Lemma A (Pythagoras). .
Proof. NVB gives a conforming refinement, so and . Galerkin orthogonality gives . Write and expand the square.
Lemma B (estimator reduction). Let . There is that depends only on the similarity classes, such that for every
Proof. Write for the fine estimator of any . The element part does not depend on , and is linear in . So is the Euclidean norm of a vector whose entries are and , and the triangle inequality gives
where in the second term the element part is left out. For a P1 function the gradient is constant on each triangle, and on an edge the jump satisfies . Also and with constants from the similarity classes. Summing over edges gives . Young's inequality then gives
It remains to bound , the fine estimator of the coarse solution. Take . If is not refined, its term is the same on both meshes. If is refined, let be a child. Then , so and . is linear on , so its jump on every new edge inside is zero. Every edge part of where the jump is not zero lies on , and these parts cover each edge of once. With exact integrals (assumption 4), . So
Every marked triangle is refined, so .
Proof of 3. Write and . Lemma B and the marking rule give
Choose . Add Lemma A:
The term cancels, which is the reason for this choice of . Fix so small that , which is possible because . For , reliability gives . So
Choose so small that . Then works. All constants depend only on , and , and so only on and the similarity classes of .
What the proof does not give. Contraction gives linear convergence in the number of steps, not a rate in the number of unknowns. The rate needs two more facts, the optimal marking lemma and the closure estimate of NVB. They are on the AFEM optimality theorem page. The proof also does not cover an inexact solve, which breaks Lemma A, or a quadrature rule that is not exact for , which breaks Galerkin orthogonality and the sum over children in Lemma B. With conjugate gradients stopped at a tolerance, as in the code, the claims hold up to the solver error.
Complexity
Count operations per step in the real-RAM model for a mesh of triangles. ESTIMATE costs , with a hash map from edges to triangles. MARK costs with a sort, or with a selection method (see Dorfler marking). REFINE costs expected time. SOLVE is the expensive step. The code uses unpreconditioned conjugate gradients, which costs per iteration, and the number of iterations grows with the condition number of the matrix, which grows as the mesh gets finer and more graded. A multigrid or multilevel preconditioner adapted to the bisection hierarchy brings the cost of a solve close to . The memory is .
Over steps the cost is the sum over the steps. In the L-shape run above the number of triangles grows by a factor of about 1.37 per step, so the sum is a small multiple of the cost of the last step. This growth factor is a measurement. With Dorfler marking alone there is no proved lower bound on the growth per step.
Properties
- Nested spaces. NVB refinement gives , so the Galerkin error in the energy norm never increases with an exact solve.
- Contraction. With Dorfler marking, the quantity decreases by the factor in each step. The constants depend on and on the shapes of .
- Optimal rate. If is small enough and the marked set is nearly minimal, the error plus oscillation decays like for every for which the solution is in the approximation class . This is the AFEM optimality theorem.
- Two-sided estimator. The residual estimator is reliable, , and efficient up to oscillation, . So is a reliable stopping criterion up to the unknown constants.
- No parameters from the solution. The loop needs no knowledge of where the singularity is. The corner in the example is found by the indicators alone.
Variants and improvements
- Other marking rules. The maximum strategy of Babuska and Vogelius marks every with , and equidistribution marks indicators above the mean. They often work, but the optimal rate is proved only for bulk marking and some close relatives.
- Other estimators. The Zienkiewicz-Zhu estimator is cheaper to explain to engineers and is often used in practice. Equilibrated flux estimators give a guaranteed upper bound with constant 1. The convergence theory is cleanest for the residual estimator.
- Goal-oriented adaptivity. The dual weighted residual method marks by the error in a quantity of interest, using a dual solution.
- hp adaptivity. The hp finite element method chooses for each marked element between a smaller element and a higher degree, which can give exponential rates.
- Coarsening. Binev, Dahmen and DeVore added a coarsening step to prove optimal rates. Stevenson and Cascon, Kreuzer, Nochetto and Siebert showed it is not needed for the model problem. Coarsening is still useful for time dependent problems, where a feature moves.
- Inexact solves. Practical codes stop the iterative solver when its error is small compared to . Later work extends the contraction and the rates to such loops.
When to use it
Use AFEM when the solution has local features whose place is not known in advance: corner and crack singularities, point loads, jumps in the coefficients, interior and boundary layers. For a smooth solution on a convex domain, uniform refinement already gives the optimal rate, and adaptivity only adds cost. For time dependent problems with moving fronts, the static loop must be combined with coarsening or replaced by block-structured AMR or the general adaptive mesh refinement of finite volume codes. For strongly directional features such as boundary layers, isotropic bisection wastes unknowns; anisotropic mesh adaptation stretches the elements.
Pitfalls
- Theta too large. With close to 1, almost all triangles are marked, and the loop is close to uniform refinement. The rate theorem needs a small ; values from 0.25 to 0.6 are common. These values are a rule of thumb.
- Counting the wrong size. Plot the error against the number of unknowns , not against the step number or the mesh size , which is not uniform. The rate for P1 in 2D corresponds to on uniform meshes.
- Pre-asymptotic slopes. The first steps on a coarse mesh do not show the final rate. Fit the slope only over the later steps, as in the example.
- Unknown constants. is an error bound only up to , which the code does not know. In the example is about three times the error.
- Loose solver tolerance. If the iterative solver stops too early, the estimator measures the solver error, and the marking goes to the wrong places.
- Inexact data. A quadrature rule that is too weak for or adds an error that the estimator does not see. The data oscillation term must be small.
- Boundary data on new nodes. When a Dirichlet edge is bisected, the new node must get at the midpoint. Losing the boundary list during refinement gives a wrong problem, as the NVB page warns.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/adaptive-finite-element-method/. The authors are listed in prov/ZK2C1A.jsonl.
"""Adaptive P1 finite elements for -Laplacian(u) = f with Dirichlet data in 2D.
The loop is SOLVE, ESTIMATE, MARK, REFINE:
- SOLVE: conforming P1 elements on triangles, conjugate gradients
(scisparse.cg) on the free nodes;
- ESTIMATE: the residual estimator eta_K^2 = h_K^2 ||f||_K^2
+ h_K sum over the interior edges E of K of ||[du_h/dn]||_E^2,
with h_K = |K|^(1/2), the form used by Cascon, Kreuzer, Nochetto and
Siebert (2008), because h_K shrinks under every bisection;
- MARK: Dorfler marking with parameter theta (sort, then take the largest);
- REFINE: newest vertex bisection with closure, so the mesh stays conforming.
A mesh is (coords, elements, boundary). coords is a list of (x, y).
An element [z1, z2, z3] has the refinement edge z1 z2 and the newest
vertex z3. boundary is a list of Dirichlet edges [a, b]. Real-RAM cost
per step: O(M log M) for M elements plus the cost of the CG solve.
"""
import math
import scisparse
def l_shape_mesh():
"""Return the six-triangle mesh of the L-shaped domain (-1, 1)^2 minus [0, 1) x (-1, 0].
The refinement edges are the diagonals of the three squares, so the
labeling is compatible: each diagonal is the refinement edge of both
triangles that share it.
"""
coords = [(-1.0, -1.0), (0.0, -1.0), (-1.0, 0.0), (0.0, 0.0),
(1.0, 0.0), (-1.0, 1.0), (0.0, 1.0), (1.0, 1.0)]
elements = [[0, 3, 1], [3, 0, 2], [3, 5, 2], [5, 3, 6], [3, 7, 4], [7, 3, 6]]
boundary = [[0, 1], [1, 3], [3, 4], [4, 7], [7, 6], [6, 5], [5, 2], [2, 0]]
return coords, elements, boundary
def square_mesh():
"""Return the two-triangle mesh of the unit square with the diagonal as refinement edge."""
coords = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)]
elements = [[0, 2, 1], [2, 0, 3]]
boundary = [[0, 1], [1, 2], [2, 3], [3, 0]]
return coords, elements, boundary
def _edge(a, b):
return (a, b) if a < b else (b, a)
def refine_nvb(coords, elements, boundary, marked):
"""Newest vertex bisection of the marked elements, with closure.
Return new (coords, elements, boundary). Every marked element is bisected
at least once; more elements are bisected only to remove hanging nodes.
"""
coords = list(coords)
touching = {}
for t, z in enumerate(elements):
for r in range(3):
touching.setdefault(_edge(z[r], z[(r + 1) % 3]), []).append(t)
edge_mark = {}
stack = []
for t in marked:
z = elements[t]
e = _edge(z[0], z[1])
if e not in edge_mark:
edge_mark[e] = None
stack.append(e)
while stack: # closure: a marked edge forces the refinement edge
for t in touching[stack.pop()]:
z = elements[t]
r = _edge(z[0], z[1])
if r not in edge_mark:
edge_mark[r] = None
stack.append(r)
for e in edge_mark:
(xa, ya), (xb, yb) = coords[e[0]], coords[e[1]]
edge_mark[e] = len(coords)
coords.append(((xa + xb) / 2, (ya + yb) / 2))
new = []
for z1, z2, z3 in elements:
m = edge_mark.get(_edge(z1, z2))
if m is None:
new.append([z1, z2, z3])
continue
m2 = edge_mark.get(_edge(z3, z1))
m1 = edge_mark.get(_edge(z2, z3))
if m2 is None:
new.append([z3, z1, m])
else:
new.extend([[m, z3, m2], [z1, m, m2]])
if m1 is None:
new.append([z2, z3, m])
else:
new.extend([[m, z2, m1], [z3, m, m1]])
bnew = []
for a, b in boundary:
m = edge_mark.get(_edge(a, b))
if m is None:
bnew.append([a, b])
else:
bnew.extend([[a, m], [m, b]])
return coords, new, bnew
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, boundary, f, g, tol=1e-10):
"""Return the nodal values U of the P1 Galerkin solution.
u = g on the boundary nodes (nodal interpolation of g); the load uses the
centroid rule f(c) |K| / 3 for each vertex of K, which is exact for
constant f. The free system is solved by conjugate gradients.
"""
n = len(coords)
dirichlet = sorted({v for e in boundary for v in e})
U = [0.0] * n
is_dir = [False] * n
for v in dirichlet:
is_dir[v] = True
U[v] = g(*coords[v])
free = [v for v in range(n) if not is_dir[v]]
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)
cx = sum(coords[v][0] for v in z) / 3
cy = sum(coords[v][1] for v in z) / 3
fk = f(cx, cy) * area / 3
for r in range(3):
i = index.get(z[r])
if i is None:
continue
b[i] += fk
gr = grads[r]
row = A[i]
for s in range(3):
gs = grads[s]
val = area * (gr[0] * gs[0] + gr[1] * gs[1])
j = index.get(z[s])
if j is None:
b[i] -= val * U[z[s]]
else:
row[j] = row.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 gradient(coords, z, U):
"""Return the constant gradient of the P1 function U on the element z."""
_, grads = _geometry(coords, z)
return (sum(U[z[r]] * grads[r][0] for r in range(3)),
sum(U[z[r]] * grads[r][1] for r in range(3)))
def estimate(coords, elements, U, f):
"""Return the list of squared residual indicators eta_K^2 for P1 and -Laplacian(u) = f."""
eta2 = []
owner = {}
grads = []
hk = []
for t, z in enumerate(elements):
area, _ = _geometry(coords, z)
cx = sum(coords[v][0] for v in z) / 3
cy = sum(coords[v][1] for v in z) / 3
eta2.append(area * area * f(cx, cy) ** 2) # h_K^2 ||f||^2 with h_K^2 = |K|
hk.append(math.sqrt(area))
grads.append(gradient(coords, z, U))
for r in range(3):
owner.setdefault(_edge(z[r], z[(r + 1) % 3]), []).append(t)
for (a, b), ts in owner.items():
if len(ts) != 2:
continue # a boundary edge: no jump term for Dirichlet data
(xa, ya), (xb, yb) = coords[a], coords[b]
length = math.hypot(xb - xa, yb - ya)
nx, ny = (yb - ya) / length, (xa - xb) / length
g0, g1 = grads[ts[0]], grads[ts[1]]
jump = (g0[0] - g1[0]) * nx + (g0[1] - g1[1]) * ny
term = length * jump * jump # ||J||_E^2, J constant on E
eta2[ts[0]] += hk[ts[0]] * term # h_K ||J||_E^2 on both sides of E
eta2[ts[1]] += hk[ts[1]] * term
return eta2
def dorfler_mark(eta2, theta):
"""Return a set of minimal size with sum of eta2 over it >= theta times the total."""
order = sorted(range(len(eta2)), key=lambda t: -eta2[t])
goal = theta * sum(eta2)
marked, acc = [], 0.0
for t in order:
if acc >= goal and marked:
break
marked.append(t)
acc += eta2[t]
return marked
def afem(mesh, f, g, theta=0.5, max_nodes=400, max_steps=40):
"""Run SOLVE, ESTIMATE, MARK, REFINE until the mesh has more than max_nodes nodes.
Return a list of (coords, elements, boundary, U, eta2), one entry per step.
theta = 1 marks every element, which is uniform bisection.
"""
coords, elements, boundary = mesh
history = []
for _ in range(max_steps): # @line L1
U = solve_p1(coords, elements, boundary, f, g) # @line L2
eta2 = estimate(coords, elements, U, f) # @line L3
history.append((coords, elements, boundary, U, eta2))
if len(coords) > max_nodes: # @line L4
break # @line L5
marked = dorfler_mark(eta2, theta) if theta < 1 else list(range(len(elements))) # @line L6
coords, elements, boundary = refine_nvb(coords, elements, boundary, marked) # @line L7
return history # @line L8
# Points and weights of the 7-point rule of degree 5 on the reference triangle (Radon).
_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, the H1 seminorm error, by the 7-point rule on each element.
The rule has no point on the boundary of the element, so it can be used
when grad_u is singular at a vertex. Near such a vertex the result is a
quadrature approximation.
"""
total = 0.0
for z in elements:
area, _ = _geometry(coords, z)
gx, gy = gradient(coords, z, U)
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)
def l_shape_exact(x, y):
"""u = r^(2/3) sin(2 phi / 3) with phi in [0, 3 pi / 2]; harmonic, zero on the reentrant edges."""
r = math.hypot(x, y)
if r == 0.0:
return 0.0
phi = math.atan2(y, x)
if phi < 0:
phi += 2 * math.pi
return r ** (2 / 3) * math.sin(2 * phi / 3)
def l_shape_gradient(x, y):
"""Gradient of l_shape_exact (not defined at the origin)."""
r = math.hypot(x, y)
phi = math.atan2(y, x)
if phi < 0:
phi += 2 * math.pi
c = (2 / 3) * r ** (-1 / 3)
ur, uphi = c * math.sin(2 * phi / 3), c * math.cos(2 * phi / 3)
return (ur * math.cos(phi) - uphi * math.sin(phi), ur * math.sin(phi) + uphi * math.cos(phi))
scisparse.py 189 lines
# 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
test_adaptive_finite_element_method.py 109 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/adaptive-finite-element-method/. The authors are listed in prov/ZK2C1A.jsonl.
import itertools
import math
import random
from adaptive_finite_element_method import (afem, dorfler_mark, energy_error, estimate,
l_shape_exact, l_shape_gradient, l_shape_mesh,
refine_nvb, solve_p1, square_mesh)
def zero(x, y):
return 0.0
def one(x, y):
return 1.0
def free_nodes(coords, boundary):
return len(coords) - len({v for e in boundary for v in e})
def conforming(elements, boundary):
count = {}
for z in elements:
for r in range(3):
a, b = z[r], z[(r + 1) % 3]
e = (min(a, b), max(a, b))
count[e] = count.get(e, 0) + 1
bset = {(min(a, b), max(a, b)) for a, b in boundary}
return all(c == 2 or (c == 1 and e in bset) for e, c in count.items()) and \
all(count.get(e) == 1 for e in bset)
def fitted_slope(history):
pts = []
for coords, elements, boundary, U, _ in history:
n = free_nodes(coords, boundary)
if n > 30:
pts.append((math.log(n), math.log(energy_error(coords, elements, U, l_shape_gradient))))
mx = sum(p[0] for p in pts) / len(pts)
my = sum(p[1] for p in pts) / len(pts)
return sum((x - mx) * (y - my) for x, y in pts) / sum((x - mx) ** 2 for x, _ in pts)
def test_hand_example_one_free_node():
coords, elements, boundary = square_mesh()
coords, elements, boundary = refine_nvb(coords, elements, boundary, [0, 1])
assert coords[4] == (0.5, 0.5) and len(elements) == 4
U = solve_p1(coords, elements, boundary, one, zero)
assert abs(U[4] - 1 / 12) < 1e-14
eta2 = estimate(coords, elements, U, one)
assert all(abs(v - (1 / 16 + math.sqrt(2) / 36)) < 1e-14 for v in eta2)
assert len(dorfler_mark(eta2, 0.5)) == 2 # four equal indicators: two reach one half
def test_linear_solution_is_reproduced_and_estimator_vanishes():
def u(x, y):
return 1 + 2 * x - 3 * y
mesh = square_mesh()
rng = random.Random(5)
coords, elements, boundary = mesh
for _ in range(5):
marked = [t for t in range(len(elements)) if rng.random() < 0.4] or [0]
coords, elements, boundary = refine_nvb(coords, elements, boundary, marked)
U = solve_p1(coords, elements, boundary, zero, u, tol=1e-13)
assert max(abs(U[v] - u(*coords[v])) for v in range(len(coords))) < 1e-10
assert max(estimate(coords, elements, U, zero)) < 1e-18
def test_dorfler_mark_is_minimal_against_brute_force():
rng = random.Random(11)
for _ in range(60):
n = rng.randint(1, 8)
eta2 = [rng.random() ** 3 for _ in range(n)]
theta = rng.choice([0.2, 0.5, 0.8, 0.95])
marked = dorfler_mark(eta2, theta)
assert len(set(marked)) == len(marked)
assert sum(eta2[t] for t in marked) >= theta * sum(eta2) - 1e-15
best = min(k for k in range(1, n + 1)
for s in itertools.combinations(range(n), k)
if sum(eta2[t] for t in s) >= theta * sum(eta2))
assert len(marked) == best
def test_meshes_stay_conforming_and_area_is_kept():
history = afem(l_shape_mesh(), zero, l_shape_exact, theta=0.5, max_nodes=300)
for coords, elements, boundary, _, eta2 in history:
assert conforming(elements, boundary)
assert len(eta2) == len(elements)
total = 0.0
for z in elements:
(x0, y0), (x1, y1), (x2, y2) = (coords[v] for v in z)
total += abs((x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0)) / 2
assert abs(total - 3.0) < 1e-12
def test_l_shape_adaptive_rate_beats_uniform():
uniform = afem(l_shape_mesh(), zero, l_shape_exact, theta=1.0, max_nodes=600)
adaptive = afem(l_shape_mesh(), zero, l_shape_exact, theta=0.5, max_nodes=600)
su, sa = fitted_slope(uniform), fitted_slope(adaptive)
assert -0.36 < su < -0.26 # theory for uniform meshes: N^(-1/3)
assert -0.56 < sa < -0.44 # optimal for P1 in 2D: N^(-1/2)
for coords, elements, boundary, U, eta2 in adaptive:
err = energy_error(coords, elements, U, l_shape_gradient)
assert 1.0 < math.sqrt(sum(eta2)) / err < 4.5 # measured effectivity 2.6 to 3.7
History
Ivo Babuska and Werner Rheinboldt introduced a posteriori error estimates and adaptive refinement for finite elements in 1978, and Babuska and Vogelius proved convergence of a feedback method in one dimension in 1984. For a long time the loop in 2D and 3D was used without a proof that it converges. Willy Dorfler gave the first proof in 1996 for Poisson's equation, with the bulk marking rule and a fine enough initial mesh. Pedro Morin, Ricardo Nochetto and Kunibert Siebert removed the condition on the initial mesh in 2000, with marking for the data oscillation and an interior node in each refined element. Peter Binev, Wolfgang Dahmen and Ronald DeVore proved optimal rates in 2004 with a coarsening step, Rob Stevenson removed the coarsening in 2007, and Manuel Cascon, Christian Kreuzer, Nochetto and Siebert gave the simple proof by contraction in 2008. Carsten Carstensen, Michael Feischl, Marcus Page and Dirk Praetorius collected the common structure of these proofs in the axioms of adaptivity in 2014.
References
- Willy Dorfler, A convergent adaptive algorithm for Poisson's equation, SIAM Journal on Numerical Analysis 33(3) (1996) 1106-1124, the bulk marking criterion and the first proof that the adaptive loop converges
- Pedro Morin, Ricardo H. Nochetto and Kunibert G. Siebert, Data oscillation and convergence of adaptive FEM, SIAM Journal on Numerical Analysis 38(2) (2000) 466-488, convergence with oscillation marking and the interior node property
- J. Manuel Cascon, Christian Kreuzer, Ricardo H. Nochetto and Kunibert G. Siebert, Quasi-optimal convergence rate for an adaptive finite element method, SIAM Journal on Numerical Analysis 46(5) (2008) 2524-2550, the contraction of the error plus the scaled estimator, and the optimal rate
- Ricardo H. Nochetto, Kunibert G. Siebert and Andreas Veeser, Theory of adaptive finite element methods: an introduction, in Multiscale, Nonlinear and Adaptive Approximation, Springer, 2009, 409-542, the full theory of the loop for the model problem, with proofs
- Stefan Funken, Dirk Praetorius and Philipp Wissgott, Efficient implementation of adaptive P1-FEM in Matlab, Computational Methods in Applied Mathematics 11(4) (2011) 460-490, the P1 solver, the residual estimator and the refinement in vectorized form
- Carsten Carstensen, Michael Feischl, Marcus Page and Dirk Praetorius, Axioms of adaptivity, Computers and Mathematics with Applications 67(6) (2014) 1195-1253, the four axioms (stability, reduction, discrete reliability, quasi-orthogonality) that give linear convergence and optimal rates
Where this leads
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 ZK2C1A Edit this page History Report an error Markdown