Algorithm Search⌘K

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.

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
Properties
contraction with dorfler markingdeterministicerror never increasesnested spaces
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 Ω⊂R2\Omega \subset \mathbb{R}^2, the model problem −∇⋅(κ∇u)=f-\nabla\cdot(\kappa\nabla u) = f in Ω\Omega with u=gu = g on ∂Ω\partial\Omega (the code takes κ=1\kappa = 1), a conforming initial triangulation T0\mathcal{T}_0 with refinement edges, a marking parameter θ∈(0,1]\theta \in (0, 1], 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 T0,T1,…\mathcal{T}_0, \mathcal{T}_1, \ldots and continuous P1 Galerkin solutions UkU_k with error indicators ηk(K)\eta_k(K), where the last mesh meets the stopping rule. The aim is a small energy error ∣∣∣u−Uk∣∣∣=∥∇(u−Uk)∥|||u - U_k||| = \|\nabla(u - U_k)\| for the number of unknowns NkN_k.

The algorithm

The estimator is the residual estimator in the form of Cascon, Kreuzer, Nochetto and Siebert, with hK=∣K∣1/2h_K = |K|^{1/2}:

ηk(K)2=hK2∥f∥K2+hK∑E⊂∂K∖∂Ω∥[ ⁣[∂nUk] ⁣]∥E2,ηk=(∑Kηk(K)2)1/2.\eta_k(K)^2 = h_K^2\|f\|_K^2 + h_K\sum_{E \subset \partial K \setminus \partial\Omega}\bigl\|[\![\partial_n U_k]\!]\bigr\|_E^2, \qquad \eta_k = \Bigl(\sum_{K}\eta_k(K)^2\Bigr)^{1/2}.

The jump [ ⁣[∂nUk] ⁣][\![\partial_n U_k]\!] of the normal derivative across an interior edge is constant on the edge for P1 functions. The element term has no ΔUk\Delta U_k because UkU_k is linear on each triangle.

  1. AFEM(T0, f, g, theta, max_nodes, max_steps)
  2. 1for k <- 0, 1, ..., max_steps - 1 do ▷ T <- T0 before the first pass
  3. 2U <- SOLVE(T, f, g) ▷ P1 Galerkin solution, conjugate gradients
  4. 3eta <- ESTIMATE(T, U, f) ▷ eta(K)^2 for every triangle K
  5. 4if the number of nodes of T > max_nodes then
  6. 5break
  7. 6M <- DORFLER(eta, theta) ▷ smallest set with sum of eta(K)^2 >= theta eta^2
  8. 7T <- REFINE(T, M) ▷ newest vertex bisection with closure
  9. 8return the list of (T, U, eta) of all passes

With θ=1\theta = 1 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 f=1f = 1 and g=0g = 0, and refine the two initial triangles once, so that the mesh has four triangles of area 14\tfrac14 around the center v4=(12,12)v_4 = (\tfrac12, \tfrac12). The only free node is v4v_4. Its hat function has gradient of length 22 on each triangle, so the stiffness entry is 4⋅14⋅4=44 \cdot \tfrac14 \cdot 4 = 4. The load is 4⋅112=134 \cdot \tfrac1{12} = \tfrac13, so U(v4)=112U(v_4) = \tfrac1{12}. The exact value of the solution at the center is about 0.07370.0737.

For the estimator, hK=12h_K = \tfrac12 and the element term is hK2∥1∥K2=14⋅14=116h_K^2\|1\|_K^2 = \tfrac14\cdot\tfrac14 = \tfrac1{16}. On the triangle with corners (0,0)(0,0), (1,0)(1,0), v4v_4 the solution is U=112⋅2yU = \tfrac1{12}\cdot 2y, and on its neighbor with corners (0,0)(0,0), (0,1)(0,1), v4v_4 it is 112⋅2x\tfrac1{12}\cdot 2x. Across the shared half diagonal, with unit normal (1,−1)/2(1, -1)/\sqrt2, the jump of the normal derivative has size 112⋅42=26\tfrac1{12}\cdot\tfrac{4}{\sqrt2} = \tfrac{\sqrt2}{6}. The edge has length 22\tfrac{\sqrt2}{2}, so the edge term is hK⋅22⋅236=272h_K\cdot\tfrac{\sqrt2}{2}\cdot\tfrac{2}{36} = \tfrac{\sqrt2}{72}. Each triangle has two interior edges, so

η(K)2=116+236≈0.10178,η=4⋅0.10178≈0.638.\eta(K)^2 = \frac1{16} + \frac{\sqrt2}{36} \approx 0.10178, \qquad \eta = \sqrt{4 \cdot 0.10178} \approx 0.638.

All four indicators are equal. With θ=12\theta = \tfrac12, 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 Ω=(−1,1)2∖[0,1)×(−1,0]\Omega = (-1, 1)^2 \setminus [0, 1) \times (-1, 0], f=0f = 0 and gg equal to the exact solution u=r2/3sin⁡(2ϕ/3)u = r^{2/3}\sin(2\phi/3) in polar coordinates. The gradient of uu is infinite at the reentrant corner, and uu is not in H2H^2. The initial mesh has six triangles. The reference code with max_nodes = 1200 gives the following energy errors, where NN is the number of free nodes.

Method Step NN ∣∣∣u−U∣∣∣\lvert\lvert\lvert u - U\rvert\rvert\rvert η\eta η/∣∣∣u−U∣∣∣\eta / \lvert\lvert\lvert u - U\rvert\rvert\rvert
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, θ=0.5\theta = 0.5 5 14 0.1967 0.6767 3.44
adaptive, θ=0.5\theta = 0.5 10 99 0.0866 0.3068 3.54
adaptive, θ=0.5\theta = 0.5 13 266 0.0525 0.1888 3.60
adaptive, θ=0.5\theta = 0.5 18 1376 0.0231 0.0847 3.67

A least squares fit of log⁡\log error against log⁡N\log N for N>30N > 30 gives the slope −0.296-0.296 for uniform refinement and −0.484-0.484 for the adaptive loop. The theory predicts N−1/3N^{-1/3} for uniform meshes, because uu is only in H1+2/3−ϵH^{1 + 2/3 - \epsilon}, and N−1/2N^{-1/2}, the best rate of P1 elements in 2D, for the adaptive meshes. The uniform slope is still pre-asymptotic. To reach an error of 0.060.06, 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 ∣∣∣u−Uk+1∣∣∣2=∣∣∣u−Uk∣∣∣2−∣∣∣Uk+1−Uk∣∣∣2|||u - U_{k+1}|||^2 = |||u - U_k|||^2 - |||U_{k+1} - U_k|||^2, so the error never grows. The estimator reduction lemma says that a bisection cuts hK2h_K^2 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 ∣∣∣Uk+1−Uk∣∣∣2|||U_{k+1} - U_k|||^2. With Dorfler marking and the reliability bound ∣∣∣u−Uk∣∣∣≤Crelηk|||u - U_k||| \le C_{\mathrm{rel}}\eta_k, these combine into the contraction

∣∣∣u−Uk+1∣∣∣2+γηk+12≤α2(∣∣∣u−Uk∣∣∣2+γηk2),0<α<1.|||u - U_{k+1}|||^2 + \gamma\eta_{k+1}^2 \le \alpha^2\bigl(|||u - U_k|||^2 + \gamma\eta_k^2\bigr), \qquad 0 < \alpha < 1.
Proof: The adaptive loop with Dorfler marking and newest vertex bisection contracts the errorfull

Setting. Ω⊂R2\Omega \subset \mathbb{R}^2 is a polygon, and u∈H01(Ω)u \in H^1_0(\Omega) solves (∇u,∇v)=(f,v)(\nabla u, \nabla v) = (f, v) for all v∈H01(Ω)v \in H^1_0(\Omega). The energy norm is ∣∣∣v∣∣∣=∥∇v∥L2(Ω)|||v||| = \|\nabla v\|_{L^2(\Omega)}. AFEM starts from a conforming triangulation T0\mathcal{T}_0 and builds T1,T2,…\mathcal{T}_1, \mathcal{T}_2, \ldots by the loop of the main page, lines L1 to L8. VkV_k is the space of continuous piecewise linear functions on Tk\mathcal{T}_k that vanish on ∂Ω\partial\Omega, and Uk∈VkU_k \in V_k is the Galerkin solution. For V∈VkV \in V_k and K∈TkK \in \mathcal{T}_k, with hK=∣K∣1/2h_K = |K|^{1/2} and J(V)J(V) the jump of ∂V/∂n\partial V / \partial n across interior edges,

ηk(V,K)2=hK2∥f∥K2+hK∥J(V)∥∂K∖∂Ω2,ηk(V,A)2=∑K∈Aηk(V,K)2,ηk=ηk(Uk,Tk).\eta_k(V, K)^2 = h_K^2\|f\|_K^2 + h_K\|J(V)\|_{\partial K \setminus \partial\Omega}^2, \qquad \eta_k(V, \mathcal{A})^2 = \sum_{K \in \mathcal{A}}\eta_k(V, K)^2, \qquad \eta_k = \eta_k(U_k, \mathcal{T}_k).

For P1 functions ΔV=0\Delta V = 0 inside each triangle, so the element residual is ff. We assume:

  1. (Exact solve.) UkU_k is the exact Galerkin solution on VkV_k.
  2. (Marking.) Mk\mathcal{M}_k satisfies ηk(Uk,Mk)2≥θ ηk2\eta_k(U_k, \mathcal{M}_k)^2 \ge \theta\,\eta_k^2 for a fixed θ∈(0,1]\theta \in (0, 1].
  3. (Refinement.) Tk+1\mathcal{T}_{k+1} is the output of newest vertex bisection for Mk\mathcal{M}_k. So it is conforming, every K∈MkK \in \mathcal{M}_k is bisected at least once, and all triangles stay in finitely many similarity classes (see newest vertex bisection).
  4. (Data.) The integrals of ff in the load vector and in ∥f∥K2\|f\|_K^2 are exact. The code uses the centroid rule, which is exact when ff is constant on each triangle of T0\mathcal{T}_0, as in the tests (f=0f = 0 and f=1f = 1).

We prove three claims.

  1. (Well defined.) Each step has a unique UkU_k, and the loop stops.
  2. (Reliability is used, not proved.) There is CrelC_{\mathrm{rel}} that depends only on the similarity classes of T0\mathcal{T}_0 with ∣∣∣u−Uk∣∣∣≤Crel ηk|||u - U_k||| \le C_{\mathrm{rel}}\,\eta_k. This is the standard upper bound of the residual error estimator (Verfurth 2013, Chapter 1), and we use it as a lemma.
  3. (Contraction.) There are γ>0\gamma > 0 and α∈(0,1)\alpha \in (0, 1), which depend only on θ\theta and on the similarity classes of T0\mathcal{T}_0, such that for every kk
∣∣∣u−Uk+1∣∣∣2+γ ηk+12≤α2(∣∣∣u−Uk∣∣∣2+γ ηk2).|||u - U_{k+1}|||^2 + \gamma\,\eta_{k+1}^2 \le \alpha^2\bigl(|||u - U_k|||^2 + \gamma\,\eta_k^2\bigr).

So ∣∣∣u−Uk∣∣∣→0|||u - U_k||| \to 0 and ηk→0\eta_k \to 0 at least as fast as αk\alpha^k 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 VkV_k is symmetric. For V≠0V \ne 0 in VkV_k the form ∣∣∣V∣∣∣2|||V|||^2 is positive, because a function in H01H^1_0 with zero gradient is zero (Poincare inequality). So the matrix is positive definite, and UkU_k exists and is unique. Conjugate gradients solve such a system, in exact arithmetic, in at most dim⁡Vk\dim V_k steps. The loop at line L1 has at most max_steps passes. Line L6 marks a nonempty set when ηk>0\eta_k > 0, 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). ∣∣∣u−Uk+1∣∣∣2=∣∣∣u−Uk∣∣∣2−∣∣∣Uk+1−Uk∣∣∣2|||u - U_{k+1}|||^2 = |||u - U_k|||^2 - |||U_{k+1} - U_k|||^2.

Proof. NVB gives a conforming refinement, so Vk⊂Vk+1V_k \subset V_{k+1} and Uk+1−Uk∈Vk+1U_{k+1} - U_k \in V_{k+1}. Galerkin orthogonality gives (∇(u−Uk+1),∇(Uk+1−Uk))=0(\nabla(u - U_{k+1}), \nabla(U_{k+1} - U_k)) = 0. Write u−Uk=(u−Uk+1)+(Uk+1−Uk)u - U_k = (u - U_{k+1}) + (U_{k+1} - U_k) and expand the square. □\square

Lemma B (estimator reduction). Let λ=1−2−1/2\lambda = 1 - 2^{-1/2}. There is CEC_E that depends only on the similarity classes, such that for every δ>0\delta > 0

ηk+12≤(1+δ)(ηk2−λ ηk(Uk,Mk)2)+(1+δ−1) CE ∣∣∣Uk+1−Uk∣∣∣2.\eta_{k+1}^2 \le (1 + \delta)\bigl(\eta_k^2 - \lambda\,\eta_k(U_k, \mathcal{M}_k)^2\bigr) + (1 + \delta^{-1})\,C_E\,|||U_{k+1} - U_k|||^2.

Proof. Write ηk+1(V)\eta_{k+1}(V) for the fine estimator of any V∈Vk+1V \in V_{k+1}. The element part hK∥f∥Kh_K\|f\|_K does not depend on VV, and JJ is linear in VV. So ηk+1(V)\eta_{k+1}(V) is the Euclidean norm of a vector whose entries are hK∥f∥Kh_K\|f\|_K and hK1/2∥J(V)∥∂Kh_K^{1/2}\|J(V)\|_{\partial K}, and the triangle inequality gives

ηk+1(Uk+1)≤ηk+1(Uk)+(∑K∈Tk+1hK∥J(W)∥∂K2)1/2,W=Uk+1−Uk,\eta_{k+1}(U_{k+1}) \le \eta_{k+1}(U_k) + \Bigl(\sum_{K \in \mathcal{T}_{k+1}} h_K\|J(W)\|_{\partial K}^2\Bigr)^{1/2}, \qquad W = U_{k+1} - U_k,

where in the second term the element part is left out. For a P1 function WW the gradient is constant on each triangle, and on an edge E=K∩K′E = K \cap K' the jump satisfies ∣J(W)∣2≤2∣∇W∣K∣2+2∣∇W∣K′∣2|J(W)|^2 \le 2|\nabla W|_K|^2 + 2|\nabla W|_{K'}|^2. Also hK∣E∣≤c ∣K∣h_K|E| \le c\,|K| and ∣K′∣≥c′∣K∣|K'| \ge c'|K| with constants from the similarity classes. Summing over edges gives ∑KhK∥J(W)∥∂K2≤CE∣∣∣W∣∣∣2\sum_K h_K\|J(W)\|_{\partial K}^2 \le C_E|||W|||^2. Young's inequality (a+b)2≤(1+δ)a2+(1+δ−1)b2(a + b)^2 \le (1 + \delta)a^2 + (1 + \delta^{-1})b^2 then gives

ηk+12≤(1+δ) ηk+1(Uk)2+(1+δ−1) CE ∣∣∣Uk+1−Uk∣∣∣2.\eta_{k+1}^2 \le (1 + \delta)\,\eta_{k+1}(U_k)^2 + (1 + \delta^{-1})\,C_E\,|||U_{k+1} - U_k|||^2.

It remains to bound ηk+1(Uk)\eta_{k+1}(U_k), the fine estimator of the coarse solution. Take K∈TkK \in \mathcal{T}_k. If KK is not refined, its term is the same on both meshes. If KK is refined, let K′K' be a child. Then ∣K′∣≤∣K∣/2|K'| \le |K|/2, so hK′≤2−1/2hKh_{K'} \le 2^{-1/2}h_K and hK′2≤12hK2≤2−1/2hK2h_{K'}^2 \le \tfrac12 h_K^2 \le 2^{-1/2}h_K^2. UkU_k is linear on KK, so its jump on every new edge inside KK is zero. Every edge part of ∂K′\partial K' where the jump is not zero lies on ∂K\partial K, and these parts cover each edge of KK once. With exact integrals (assumption 4), ∑K′∥f∥K′2=∥f∥K2\sum_{K'}\|f\|_{K'}^2 = \|f\|_K^2. So

∑K′⊂Kηk+1(Uk,K′)2≤2−1/2ηk(Uk,K)2.\sum_{K' \subset K}\eta_{k+1}(U_k, K')^2 \le 2^{-1/2}\eta_k(U_k, K)^2.

Every marked triangle is refined, so ηk+1(Uk)2≤ηk2−(1−2−1/2) ηk(Uk,Mk)2\eta_{k+1}(U_k)^2 \le \eta_k^2 - (1 - 2^{-1/2})\,\eta_k(U_k, \mathcal{M}_k)^2. □\square

Proof of 3. Write ek=∣∣∣u−Uk∣∣∣e_k = |||u - U_k||| and Ek=∣∣∣Uk+1−Uk∣∣∣E_k = |||U_{k+1} - U_k|||. Lemma B and the marking rule give

ηk+12≤(1+δ)(1−λθ) ηk2+(1+δ−1) CE Ek2.\eta_{k+1}^2 \le (1 + \delta)(1 - \lambda\theta)\,\eta_k^2 + (1 + \delta^{-1})\,C_E\,E_k^2.

Choose γ=1/((1+δ−1)CE)\gamma = 1 / ((1 + \delta^{-1})C_E). Add Lemma A:

ek+12+γ ηk+12≤ek2−Ek2+γ(1+δ)(1−λθ) ηk2+Ek2=ek2+γ(1+δ)(1−λθ) ηk2.e_{k+1}^2 + \gamma\,\eta_{k+1}^2 \le e_k^2 - E_k^2 + \gamma(1 + \delta)(1 - \lambda\theta)\,\eta_k^2 + E_k^2 = e_k^2 + \gamma(1 + \delta)(1 - \lambda\theta)\,\eta_k^2.

The term Ek2E_k^2 cancels, which is the reason for this choice of γ\gamma. Fix δ>0\delta > 0 so small that q=(1+δ)(1−λθ)<1q = (1 + \delta)(1 - \lambda\theta) < 1, which is possible because λθ>0\lambda\theta > 0. For β∈(0,1)\beta \in (0, 1), reliability gives ek2≤(1−β)ek2+βCrel2ηk2e_k^2 \le (1 - \beta)e_k^2 + \beta C_{\mathrm{rel}}^2\eta_k^2. So

ek+12+γ ηk+12≤(1−β) ek2+γ(q+βCrel2γ)ηk2.e_{k+1}^2 + \gamma\,\eta_{k+1}^2 \le (1 - \beta)\,e_k^2 + \gamma\Bigl(q + \frac{\beta C_{\mathrm{rel}}^2}{\gamma}\Bigr)\eta_k^2.

Choose β\beta so small that q+βCrel2/γ<1q + \beta C_{\mathrm{rel}}^2 / \gamma < 1. Then α2=max⁡(1−β, q+βCrel2/γ)<1\alpha^2 = \max(1 - \beta,\ q + \beta C_{\mathrm{rel}}^2/\gamma) < 1 works. All constants depend only on θ\theta, CrelC_{\mathrm{rel}} and CEC_E, and so only on θ\theta and the similarity classes of T0\mathcal{T}_0. □\square

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 (#Tk)−s(\#\mathcal{T}_k)^{-s} 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 ff, 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 MM triangles. ESTIMATE costs Θ(M)\Theta(M), with a hash map from edges to triangles. MARK costs Θ(Mlog⁡M)\Theta(M\log M) with a sort, or Θ(M)\Theta(M) with a selection method (see Dorfler marking). REFINE costs Θ(M)\Theta(M) expected time. SOLVE is the expensive step. The code uses unpreconditioned conjugate gradients, which costs Θ(M)\Theta(M) 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 O(M)O(M). The memory is Θ(M)\Theta(M).

Over kk 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 V0⊂V1⊂⋯V_0 \subset V_1 \subset \cdots, so the Galerkin error in the energy norm never increases with an exact solve.
  • Contraction. With Dorfler marking, the quantity ∣∣∣u−Uk∣∣∣2+γηk2|||u - U_k|||^2 + \gamma\eta_k^2 decreases by the factor α2<1\alpha^2 < 1 in each step. The constants depend on θ\theta and on the shapes of T0\mathcal{T}_0.
  • Optimal rate. If θ\theta is small enough and the marked set is nearly minimal, the error plus oscillation decays like (#Tk)−s(\#\mathcal{T}_k)^{-s} for every ss for which the solution is in the approximation class As\mathbb{A}_s. This is the AFEM optimality theorem.
  • Two-sided estimator. The residual estimator is reliable, ∣∣∣u−Uk∣∣∣≤Crelηk|||u - U_k||| \le C_{\mathrm{rel}}\eta_k, and efficient up to oscillation, ηk≤Ceff(∣∣∣u−Uk∣∣∣+osck)\eta_k \le C_{\mathrm{eff}}(|||u - U_k||| + \mathrm{osc}_k). So ηk\eta_k 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 KK with η(K)≥θmax⁡η\eta(K) \ge \theta\max\eta, 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 ηk\eta_k. 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 θ\theta close to 1, almost all triangles are marked, and the loop is close to uniform refinement. The rate theorem needs a small θ\theta; 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 NN, not against the step number or the mesh size hh, which is not uniform. The rate N−1/2N^{-1/2} for P1 in 2D corresponds to h1h^1 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. ηk\eta_k is an error bound only up to CrelC_{\mathrm{rel}}, which the code does not know. In the example η\eta 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 ff or gg 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 gg 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.

adaptive_finite_element_method.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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
  4. 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
  5. 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
  6. 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.

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