Algorithm Search⌘K

Algorithmadvanced

hp finite element method

Also called hp-FEM, p-version finite element method.

Refines both mesh size h and degree p, small h near singularities and high p where the solution is smooth. On geometric meshes, piecewise analytic solutions converge like exp(-b N^(1/3)) in 2D.

Time
Θ(N) average
Space
Θ(N) extra
Where
N = the number of unknowns
Properties
conformingdeterministicexponential convergencehierarchic basis
Origin
Ivo Babuska, Benqi Guo, Wen Gui, 1986

The hp finite element method improves a finite element solution in two ways at once: by smaller elements (h refinement) and by higher polynomial degree (p refinement). Where the solution is smooth, a higher degree gives errors that fall faster than any power of the number of unknowns NN. Near a singularity, such as the corner of an L-shaped domain, high degree does not help much, and small elements graded toward the singular point do. A geometric mesh, with element sizes that shrink by a fixed factor σ\sigma toward the singularity, combined with degrees that grow linearly away from it, gives exponential convergence: exp⁡(−bN)\exp(-b\sqrt{N}) in 1D and exp⁡(−bN1/3)\exp(-bN^{1/3}) in 2D for solutions that are piecewise analytic with corner singularities. Uniform h refinement with a fixed degree can only reach an algebraic rate N−sN^{-s}, with ss limited by the singularity.

In plain words

There are two ways to make a finite element solution better. You can cut the elements into smaller ones, or you can use polynomials of higher degree on the same elements. Higher degree is very effective where the solution is smooth, but bad at a sharp corner, where the solution has a kink in its slope. Small elements are the right tool at the corner. The hp method does both: it puts layers of smaller and smaller elements toward the corner, and it uses a low degree on the tiny elements and a higher degree on the large ones farther away. Then the error falls faster than with either tool alone.

The problem

Input. An elliptic boundary value problem with a solution that is analytic except at known points, such as the corners of a polygon. Here the 1D model problem −u′′=f-u'' = f on (0,1)(0, 1) with u(0)=u(1)=0u(0) = u(1) = 0 and a solution like u=xα−xu = x^{\alpha} - x with 12<α<1\tfrac12 < \alpha < 1, singular at 0. Also a number of layers nn, a grading factor 0<σ<10 < \sigma < 1 and a slope μ>0\mu > 0 for the degrees.

Output. The Galerkin solution uhu_h in the space of continuous piecewise polynomials on the geometric mesh with degree pip_i on element ii, and its energy error ∣u−uh∣1|u - u_h|_1.

The algorithm

HP-GEOMETRIC builds the a priori hp space and solves on it. The basis is the hat functions at the nodes plus, on each element, the integrated Legendre bubbles ψk=(Pk−Pk−2)/2(2k−1)\psi_k = (P_k - P_{k-2})/\sqrt{2(2k-1)}, k=2,…,pik = 2, \ldots, p_i, in the local coordinate ξ∈[−1,1]\xi \in [-1, 1]. In 1D their derivatives are scaled Legendre polynomials, so the bubbles are orthogonal to each other and to the hats in the energy product.

  1. HP-GEOMETRIC(n, sigma, mu, u)
  2. 1x_0 <- 0; x_i <- sigma^(n - i) for i = 1..n ▷ n layers toward the singularity at 0
  3. 2p_i <- max(1, ceil(mu * i)) for i = 1..n ▷ the degree grows away from the singularity
  4. 3for each element K_i: add (1 / h_i) [[1, -1], [-1, 1]] to the hat system and its loads to b
  5. 4V <- solve the tridiagonal hat system ▷ the Thomas algorithm
  6. 5c_ik <- (h_i / 2) * b_ik for k = 2..p_i ▷ the bubble stiffness is the diagonal 2 / h_i
  7. 6return V and c

The loads are bj=∫u′ϕj′b_j = \int u'\phi_j' and bik=∫u′ψik′b_{ik} = \int u'\psi_{ik}', which equal ∫fϕj\int f\phi_j and ∫fψik\int f\psi_{ik} for the exact solution uu. In 2D the same basis has bubbles and edge functions that are coupled, and the solve is the main cost. There the interior bubbles are removed first by static condensation.

Example

By hand. Take one element [0,1][0, 1] with p=2p = 2 and u=x−x2u = x - x^2. There are no interior nodes, so the only unknown is the coefficient cc of ψ2=32(ξ2−1)/6\psi_2 = \tfrac{3}{2}(\xi^2 - 1)/\sqrt6. With x=(ξ+1)/2x = (\xi + 1)/2, u′=1−2x=−ξu' = 1 - 2x = -\xi, so b=3/2∫−11(−ξ) ξ dξ=−233/2b = \sqrt{3/2}\int_{-1}^1(-\xi)\,\xi\,d\xi = -\tfrac23\sqrt{3/2}. The stiffness is 2/h=22/h = 2, so c=b/2=−133/2c = b/2 = -\tfrac13\sqrt{3/2}. Then uh(12)=c ψ2(0)=−133/2⋅(−326)=14=u(12)u_h(\tfrac12) = c\,\psi_2(0) = -\tfrac13\sqrt{3/2}\cdot(-\tfrac{3}{2\sqrt6}) = \tfrac14 = u(\tfrac12), and in fact uh=uu_h = u, because uu is a quadratic. The error identity gives ∣u∣12−bc=13−13=0|u|_1^2 - bc = \tfrac13 - \tfrac13 = 0.

Measured. For u=x0.7−xu = x^{0.7} - x, with ∣u∣12=0.225|u|_1^2 = 0.225, the reference code gives these relative energy errors.

Method NN Relative error
Uniform h, p=1p = 1 63 0.437
Uniform h, p=1p = 1 255 0.331
Uniform h, p=1p = 1 1023 0.251
One element, p=8p = 8 7 0.441
One element, p=16p = 16 15 0.334
One element, p=32p = 32 31 0.253
Geometric, σ=0.15\sigma = 0.15, μ=12\mu = \tfrac12, n=8n = 8 19 8.08×10−28.08 \times 10^{-2}
Geometric, n=12n = 12 41 1.79×10−21.79 \times 10^{-2}
Geometric, n=16n = 16 71 3.96×10−33.96 \times 10^{-3}
Geometric, n=20n = 20 109 8.71×10−48.71 \times 10^{-4}
Geometric, n=24n = 24 155 1.91×10−41.91 \times 10^{-4}

Uniform h refinement gives N−0.2N^{-0.2}, the rate allowed by u∈H1.2−ϵu \in H^{1.2 - \epsilon}. Higher degree on one element gives N−0.4N^{-0.4}, twice the rate, but still algebraic. With 109 unknowns the hp error is about 290 times smaller than the uniform h error with 1023 unknowns, and the slope of ln⁡(error)\ln(\text{error}) against N\sqrt{N} settles at −0.75-0.75. A geometric mesh with p=1p = 1 everywhere stalls at 0.343: the large elements far from the singularity need the higher degree.

Correctness

The full proof is in the correctness proof. The derivative of ψk\psi_k is (2k−1)/2 Pk−1\sqrt{(2k-1)/2}\,P_{k-1}, so the Legendre orthogonality makes the bubble stiffness diagonal and decouples it from the hats, and lines L4 and L5 solve the Galerkin system exactly. Galerkin orthogonality gives the error identity ∣u−uh∣12=∣u∣12−bTU|u - u_h|_1^2 = |u|_1^2 - b^{\mathsf T}U that the code uses. For the rate, the error is at most the error of any function in the space. On element [σk+1,σk][\sigma^{k+1}, \sigma^k] the ratio of distance to size is fixed, so u′u' is analytic in an ellipse of fixed shape around it, and polynomials of degree pp approximate it with error Cσk(α−1)r−pC\sigma^{k(\alpha - 1)}r^{-p}. The small element at 0 contributes Cσn(α−1/2)C\sigma^{n(\alpha - 1/2)}. Linear degrees balance the two, each term is at most CqnCq^n with q<1q < 1, and N≤Cn2N \le Cn^2 turns qnq^n into exp⁡(−bN)\exp(-b\sqrt N).

Proof: The 1D hp solver computes the Galerkin solution, and the geometric mesh with linear degrees converges like exp(-b sqrt N)full

Setting. The problem is −u′′=f-u'' = f on (0,1)(0, 1) with u(0)=u(1)=0u(0) = u(1) = 0, in the weak form: find u∈H01(0,1)u \in H^1_0(0, 1) with a(u,v)=∫01u′v′=∫01fva(u, v) = \int_0^1 u'v' = \int_0^1 fv for all v∈H01v \in H^1_0. The energy norm is ∣v∣1=a(v,v)1/2|v|_1 = a(v, v)^{1/2}. A mesh 0=x0<⋯<xn=10 = x_0 < \cdots < x_n = 1 has elements Ki=[xi−1,xi]K_i = [x_{i-1}, x_i] of length hih_i, each with a degree pi≥1p_i \ge 1. The space VhV_h is the set of continuous functions in H01H^1_0 that are polynomials of degree at most pip_i on KiK_i. On KiK_i the local coordinate is ξ∈[−1,1]\xi \in [-1, 1] with x=xi−1+hi(ξ+1)/2x = x_{i-1} + h_i(\xi + 1)/2. The basis is the hat functions ϕj\phi_j at the interior nodes and the bubbles ψik(ξ)=(Pk(ξ)−Pk−2(ξ))/2(2k−1)\psi_{ik}(\xi) = (P_k(\xi) - P_{k-2}(\xi))/\sqrt{2(2k-1)}, k=2,…,pik = 2, \ldots, p_i, which are 0 outside KiK_i. HP-GEOMETRIC is lines L1 to L6 of the main page.

We prove four claims.

  1. (The solver.) Lines L3 to L5 return the coefficients of the Galerkin solution uh∈Vhu_h \in V_h, a(uh,v)=a(u,v)a(u_h, v) = a(u, v) for all v∈Vhv \in V_h.
  2. (Error identity.) ∣u−uh∣12=∣u∣12−bTU|u - u_h|_1^2 = |u|_1^2 - b^{\mathsf T}U, where bb is the load vector and UU the coefficient vector.
  3. (Nodal exactness.) uh(xj)=u(xj)u_h(x_j) = u(x_j) at every node, for every choice of the degrees.
  4. (Exponential rate.) Let u=xα−xu = x^\alpha - x with 12<α<1\tfrac12 < \alpha < 1, so that u∉H2u \notin H^2. For the geometric mesh x0=0x_0 = 0, xi=σn−ix_i = \sigma^{n-i} with 0<σ<10 < \sigma < 1, and the degrees pi=max⁡(1,⌈μi⌉)p_i = \max(1, \lceil\mu i\rceil) with μ>0\mu > 0, there are constants C,b>0C, b > 0 that depend on α\alpha, σ\sigma and μ\mu but not on nn such that ∣u−uh∣1≤Cexp⁡(−bN)|u - u_h|_1 \le C\exp(-b\sqrt{N}), where N=dim⁡VhN = \dim V_h.

Proof of 1. The functions are a basis of VhV_h: on each element, the two linear functions (1∓ξ)/2(1 \mp \xi)/2 and the ψik\psi_{ik}, k=2,…,pik = 2, \ldots, p_i, span the polynomials of degree pip_i, because ψik\psi_{ik} has degree exactly kk. The bubbles are 0 at ξ=±1\xi = \pm 1, because Pk(±1)=Pk−2(±1)P_k(\pm 1) = P_{k-2}(\pm 1), so the functions are continuous. Now compute the stiffness matrix. The standard identity (2k−1)Pk−1=Pk′−Pk−2′(2k-1)P_{k-1} = P_k' - P_{k-2}' gives ψik′(ξ)=(2k−1)/2 Pk−1(ξ)\psi_{ik}'(\xi) = \sqrt{(2k-1)/2}\,P_{k-1}(\xi). With dx=(hi/2) dξdx = (h_i/2)\,d\xi and d/dx=(2/hi) d/dξd/dx = (2/h_i)\,d/d\xi,

a(ψik,ψil)=2hi∫−11ψik′ψil′ dξ=2hi⋅(2k−1)(2l−1)2∫−11Pk−1Pl−1 dξ=2hiδkl,a(\psi_{ik}, \psi_{il}) = \frac{2}{h_i}\int_{-1}^{1}\psi_{ik}'\psi_{il}'\,d\xi = \frac{2}{h_i}\cdot\frac{\sqrt{(2k-1)(2l-1)}}{2}\int_{-1}^{1}P_{k-1}P_{l-1}\,d\xi = \frac{2}{h_i}\delta_{kl},

by ∫−11Pm2=2/(2m+1)\int_{-1}^1 P_m^2 = 2/(2m+1) and the orthogonality of the Legendre polynomials. A hat function has a constant derivative on KiK_i, and ∫−11Pk−1=0\int_{-1}^{1}P_{k-1} = 0 for k≥2k \ge 2, so a(ϕj,ψik)=0a(\phi_j, \psi_{ik}) = 0. Bubbles of different elements have disjoint supports. So the Galerkin matrix is block diagonal: a tridiagonal block for the hats, the usual P1 stiffness matrix with 1/hi1/h_i entries, and the diagonal 2/hi2/h_i for the bubbles. The hat block is symmetric and strictly diagonally dominant in its first and last rows and weakly in the others, and it is irreducible, so it is positive definite and the Thomas algorithm at line L4 runs without pivoting and solves it. Line L5 solves the diagonal part, cik=(hi/2) bikc_{ik} = (h_i/2)\,b_{ik}. The loads are bj=a(u,ϕj)b_j = a(u, \phi_j), which the code computes exactly from the values of uu at the nodes, since ϕj′\phi_j' is ±1/h\pm 1/h, and bik=a(u,ψik)=(2k−1)/2∫−11u′(x(ξ))Pk−1(ξ) dξb_{ik} = a(u, \psi_{ik}) = \sqrt{(2k-1)/2}\int_{-1}^{1}u'(x(\xi))P_{k-1}(\xi)\,d\xi. □\square

Proof of 2. By claim 1, a(u−uh,uh)=0a(u - u_h, u_h) = 0. So ∣u−uh∣12=a(u−uh,u)=∣u∣12−a(uh,u)|u - u_h|_1^2 = a(u - u_h, u) = |u|_1^2 - a(u_h, u), and a(uh,u)=∑mUma(basism,u)=bTUa(u_h, u) = \sum_m U_m a(\text{basis}_m, u) = b^{\mathsf T}U. □\square

Proof of 3. Fix an interior node xjx_j. Let gg be the function in H01H^1_0 that is linear on [0,xj][0, x_j] and on [xj,1][x_j, 1], with g(xj)=1g(x_j) = 1. Then for every v∈H01v \in H^1_0, a(v,g)=∫0xjv′/xj−∫xj1v′/(1−xj)=v(xj)/xj+v(xj)/(1−xj)a(v, g) = \int_0^{x_j} v'/x_j - \int_{x_j}^1 v'/(1 - x_j) = v(x_j)/x_j + v(x_j)/(1 - x_j), so v(xj)=c a(v,g)v(x_j) = c\,a(v, g) with c=xj(1−xj)c = x_j(1 - x_j). The function gg is linear on each element, so g∈Vhg \in V_h. Galerkin orthogonality gives uh(xj)=c a(uh,g)=c a(u,g)=u(xj)u_h(x_j) = c\,a(u_h, g) = c\,a(u, g) = u(x_j). □\square

Proof of 4. By claim 1, uhu_h is the best approximation in the energy norm, ∣u−uh∣1≤∣u−v∣1|u - u_h|_1 \le |u - v|_1 for every v∈Vhv \in V_h. We build a good vv element by element, with v=uv = u at every node, so that the pieces join into a continuous function in H01H^1_0. On KK we take v′=Πp−1u′v' = \Pi_{p-1}u', the L2(K)L^2(K) projection of u′u' onto the polynomials of degree p−1p - 1, and v(x)=u(xleft)+∫xleftxv′v(x) = u(x_{\text{left}}) + \int_{x_{\text{left}}}^{x}v'. The projection keeps the mean of u′u', because constants are in the space, so v=uv = u at both ends. Then ∣u−v∣1,K=∥u′−Πp−1u′∥L2(K)≤h1/2inf⁡q∥u′−q∥L∞(K)|u - v|_{1, K} = \|u' - \Pi_{p-1}u'\|_{L^2(K)} \le h^{1/2}\inf_q\|u' - q\|_{L^\infty(K)}, with the infimum over the polynomials of degree p−1p - 1.

The first element K1=[0,σn−1]K_1 = [0, \sigma^{n-1}] has p1≥1p_1 \ge 1. Here vv is at least as good as the linear interpolant, and ∣u−v∣1,K12≤∣u∣1,K12≤2∫0x1(α2x2α−2+1) dx≤C σ(n−1)(2α−1)|u - v|_{1, K_1}^2 \le |u|_{1, K_1}^2 \le 2\int_0^{x_1}(\alpha^2x^{2\alpha - 2} + 1)\,dx \le C\,\sigma^{(n-1)(2\alpha - 1)}. This uses 2α−1>02\alpha - 1 > 0, and the linear interpolant error is at most ∣u∣1,K1|u|_{1,K_1} because it is the projection of u′u' onto constants.

Each other element Ki=[σk+1,σk]K_i = [\sigma^{k+1}, \sigma^k] with k=n−ik = n - i has h=σk(1−σ)h = \sigma^k(1 - \sigma) and left end a=σk+1a = \sigma^{k+1}, so a/h=σ/(1−σ)a/h = \sigma/(1 - \sigma) is the same for all of them. In the local coordinate, the only singularity of u′(x)=αxα−1−1u'(x) = \alpha x^{\alpha - 1} - 1 is at ξs=−1−2a/h=−(1+σ)/(1−σ)\xi_s = -1 - 2a/h = -(1 + \sigma)/(1 - \sigma), a fixed point left of −1-1. So u′(x(ξ))u'(x(\xi)) is analytic inside the Bernstein ellipse with foci ±1\pm 1 through ξs\xi_s, with parameter ρ=∣ξs∣+(ξs2−1)1/2>1\rho = |\xi_s| + (\xi_s^2 - 1)^{1/2} > 1. Fix 1<r<ρ1 < r < \rho. On the ellipse with parameter rr, ∣x∣≥c σk|x| \ge c\,\sigma^k with c>0c > 0 that depends only on σ\sigma and rr, so ∣u′∣≤Cσk(α−1)|u'| \le C\sigma^{k(\alpha - 1)} there. The classical estimate for analytic functions (Bernstein) gives a polynomial qq of degree p−1p - 1 with ∥u′−q∥L∞(K)≤Cσk(α−1)r−(p−1)\|u' - q\|_{L^\infty(K)} \le C\sigma^{k(\alpha - 1)}r^{-(p-1)}. With the factor h1/2≤σk/2h^{1/2} \le \sigma^{k/2},

∣u−v∣1,Ki≤C σ(n−i)(α−1/2) r−pi+1.|u - v|_{1, K_i} \le C\,\sigma^{(n - i)(\alpha - 1/2)}\,r^{-p_i + 1}.

Sum. Let q=max⁡(σα−1/2,r−μ)<1q = \max(\sigma^{\alpha - 1/2}, r^{-\mu}) < 1. With pi≥μip_i \ge \mu i, each term is at most Cr qn−iqi=Cr qnC r\,q^{n - i}q^{i} = Cr\,q^n, and the first element also gives at most Cqn−1Cq^{n-1}. So ∣u−uh∣12≤C n q2n|u - u_h|_1^2 \le C\,n\,q^{2n}, and ∣u−uh∣1≤Cn qn≤C′q~ n|u - u_h|_1 \le C\sqrt{n}\,q^n \le C'\tilde q^{\,n} for any q<q~<1q < \tilde q < 1. The dimension is N=(n−1)+∑i(pi−1)≤n+μn(n+1)/2≤Cn2N = (n - 1) + \sum_i(p_i - 1) \le n + \mu n(n + 1)/2 \le C n^2, so n≥N/Cn \ge \sqrt{N/C}, and ∣u−uh∣1≤C′exp⁡(−bN)|u - u_h|_1 \le C'\exp(-b\sqrt{N}) with b=∣ln⁡q~∣/Cb = |\ln\tilde q|/\sqrt{C}. □\square

Remarks. With α=0.7\alpha = 0.7 and σ=0.15\sigma = 0.15, the factor σα−1/2=0.684\sigma^{\alpha - 1/2} = 0.684 predicts that each new layer cuts the error by about this factor. The reference run with μ=12\mu = \tfrac12 measures a factor of 0.47≈0.68420.47 \approx 0.684^2 per two layers. The same proof with pi=1p_i = 1 on all elements shows why the geometric mesh alone stalls: the last element [σ,1][\sigma, 1] keeps an error that does not depend on nn. In 2D the same construction, with geometric layers toward each corner of a polygon, gives exp⁡(−bN1/3)\exp(-bN^{1/3}) for solutions that are piecewise analytic with corner singularities. That is the theorem of Babuska and Guo, and its proof needs weighted Sobolev spaces; this page does not reproduce it.

Complexity

In 1D the hat system is tridiagonal and the bubbles are decoupled, so the solve costs Θ(N)\Theta(N). The loads need quadrature with a number of points that grows with pp: with p+cp + c Gauss points per bubble on each element, the load costs O(∑ipi2)O(\sum_i p_i^2), which is O(Nmax⁡ipi)O(N\max_i p_i). In 2D and 3D the element matrices for degree pp have O(p2d)O(p^{2d}) entries, and static condensation of the interior bubbles costs O(p3d)O(p^{3d}) per element with dense algebra, which is why codes for high pp use sum factorization on tensor product elements. Memory is Θ(N)\Theta(N) in 1D.

Properties

  • Exponential convergence. For solutions that are piecewise analytic with point singularities, geometric meshes with linear degrees give exp⁡(−bN)\exp(-b\sqrt N) in 1D and exp⁡(−bN1/3)\exp(-bN^{1/3}) in 2D, with bb independent of NN.
  • Hierarchic basis. Raising pp on an element adds new bubbles and keeps the old ones, so the matrix for degree pp is a submatrix of the one for p+1p + 1.
  • Nodal exactness in 1D. For −u′′=f-u'' = f, the Galerkin solution equals uu at every node, whatever the degrees. The bubbles only add the interior detail.
  • Robust grading. The rate is exponential for every σ∈(0,1)\sigma \in (0, 1) and every μ>0\mu > 0. Only the constant bb depends on them. In this test, σ\sigma from 0.15 to 0.2 and μ\mu from 0.5 to 1 all worked.
  • Conforming. The space is a subspace of H01H^1_0, so Cea's lemma holds with the usual constant.

Variants and improvements

  • hp-adaptivity. When the singularities are not known, an adaptive loop marks elements by an error estimator and then decides per element whether to split it or raise its degree. A common test is the decay of the Legendre coefficients of uhu_h on the element: fast decay means the solution is smooth there, so raise pp.
  • Spectral elements. The spectral element method is the p refinement of quadrilaterals or hexahedra with a nodal basis at Gauss-Lobatto points, usually on a fixed mesh.
  • Nodal versus modal bases. The basis here is modal. A nodal basis at Gauss-Lobatto points spans the same space, with a different conditioning.
  • hp discontinuous Galerkin. Discontinuous Galerkin methods allow a different degree on each element without the conformity constraints, which makes hp-adaptivity simpler.
  • Anisotropic hp. For boundary layers, elements that are thin in one direction with a high degree along the layer give robust exponential rates.

When to use it

Use hp-FEM for elliptic problems with smooth data on domains with corners, edges or material interfaces, when high accuracy is needed: structural mechanics, electromagnetics and the computation of stress intensity factors are classical examples. It reaches an accuracy in a few hundred unknowns that h refinement would need millions for. It is less attractive for problems with low regularity everywhere, such as rough coefficients or shocks, where high degree gives no gain.

Pitfalls

  • Degree at the singularity. Use a low degree on the smallest elements. A high degree there wastes unknowns, because the solution is not smooth there.
  • Too few layers. If the mesh grading stops early, the error of the element at the singularity dominates and the rate becomes algebraic.
  • Quadrature. For high degree, the quadrature must grow with pp, or the loads and the matrices lose the accuracy that the high degree should give. Near the singularity a special rule or an exact formula is needed.
  • Roundoff in the error identity. ∣u∣12−bTU|u|_1^2 - b^{\mathsf T}U subtracts two numbers that are close, so it cannot measure errors below about 10−810^{-8} times ∣u∣1|u|_1 in double precision.
  • Conditioning. The condition number of the stiffness matrix grows like a power of pp, and the power depends on the basis and the dimension. Choose a basis with good conditioning, and use preconditioners made for high degree.
  • Not the same as pure p refinement. Raising the degree on a fixed mesh is only one part of the method. With a singularity it converges at an algebraic rate, as the table shows.

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.

hp_finite_element_method.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hp-finite-element-method/. The authors are listed in prov/9VWB60.jsonl.

"""hp finite element method in 1D with a geometric mesh and a linear degree vector.

Model problem: -u'' = f on (0, 1), u(0) = u(1) = 0. Element i is
[x_{i-1}, x_i] with length h_i and degree p_i >= 1. The basis is the hat
function at each interior node plus the integrated Legendre bubbles

    psi_k(xi) = (P_k(xi) - P_{k-2}(xi)) / sqrt(2 (2k - 1)),  k = 2..p_i,

on each element, with xi in [-1, 1] the local coordinate. Then
psi_k' = sqrt((2k - 1) / 2) P_{k-1}, the bubbles are orthogonal to each other
and to the hats in the energy product, and the bubble stiffness is the
diagonal 2 / h_i. Only the hats are coupled, by a tridiagonal matrix.

The load is given through the exact solution u: the right side of the
Galerkin system is a(u, v) = int u' v', which equals int f v. So the caller
gives u (for the hats) and the moments M_j = int_{-1}^{1} u'(x(xi)) P_j(xi) dxi
(for the bubbles). The energy error is then |u - u_h|_1^2 = |u|_1^2 - b^T U.

Cost: O(N) for N unknowns after the loads (Thomas algorithm for the hats).
"""

import math

import scisparse


def legendre(j, x):
    """Return P_j(x) by the three-term recurrence."""
    if j == 0:
        return 1.0
    p0, p1 = 1.0, x
    for k in range(2, j + 1):
        p0, p1 = p1, ((2 * k - 1) * x * p1 - (k - 1) * p0) / k
    return p1


def gauss_legendre(n):
    """Return the n Gauss-Legendre nodes and weights on [-1, 1] (Newton on P_n)."""
    nodes, weights = [], []
    for i in range(1, n + 1):
        x = math.cos(math.pi * (i - 0.25) / (n + 0.5))
        for _ in range(100):
            p0, p1 = 1.0, x
            for k in range(2, n + 1):
                p0, p1 = p1, ((2 * k - 1) * x * p1 - (k - 1) * p0) / k
            dp = n * (x * p1 - p0) / (x * x - 1)
            dx = p1 / dp
            x -= dx
            if abs(dx) < 1e-16:
                break
        p0, p1 = 1.0, x
        for k in range(2, n + 1):
            p0, p1 = p1, ((2 * k - 1) * x * p1 - (k - 1) * p0) / k
        dp = n * (x * p1 - p0) / (x * x - 1)
        nodes.append(x)
        weights.append(2 / ((1 - x * x) * dp * dp))
    return nodes, weights


def geometric_mesh(n, sigma):
    """Return the nodes 0, sigma^(n-1), ..., sigma, 1: n elements graded toward 0."""
    return [0.0] + [sigma ** (n - i) for i in range(1, n + 1)]


def linear_degrees(n, mu):
    """Return the degree vector p_i = max(1, ceil(mu * i)), i = 1..n, from the singular end."""
    return [max(1, math.ceil(mu * i - 1e-12)) for i in range(1, n + 1)]


def solve_hp(nodes, degrees, u, moment):
    """Solve the Galerkin system; return (V, C, bTU).

    V: values at the interior nodes; C[i]: the bubble coefficients of
    element i (k = 2..p_i); bTU: b^T U, so that |u - u_h|_1^2 = |u|_1^2 - bTU.
    moment(a, b, j) must return int_{-1}^{1} u'(x(xi)) P_j(xi) dxi on [a, b].
    """
    n = len(nodes) - 1
    h = [nodes[i + 1] - nodes[i] for i in range(n)]
    m = n - 1  # interior nodes 1..n-1
    sub, diag, sup, rhs = [0.0] * m, [0.0] * m, [0.0] * m, [0.0] * m
    for i in range(n):  # element i joins nodes i and i + 1  # @line L3
        s = (u(nodes[i + 1]) - u(nodes[i])) / h[i]  # int_K u' phi' for the two hats
        for r, node in ((0, i), (1, i + 1)):
            j = node - 1
            if 0 <= j < m:
                diag[j] += 1 / h[i]
                rhs[j] += -s if r == 0 else s
        if 1 <= i <= m - 1:  # both nodes of the element are interior
            sub[i] = -1 / h[i]
            sup[i - 1] = -1 / h[i]
    V = scisparse.thomas(sub, diag, sup, rhs) if m else []  # @line L4
    bTU = sum(r * v for r, v in zip(rhs, V))
    C = []
    for i in range(n):
        ci = []
        for k in range(2, degrees[i] + 1):
            bk = math.sqrt((2 * k - 1) / 2) * moment(nodes[i], nodes[i + 1], k - 1)
            ci.append(h[i] / 2 * bk)  # @line L5
            bTU += h[i] / 2 * bk * bk
        C.append(ci)
    return V, C, bTU  # @line L6


def evaluate(nodes, V, C, x):
    """Return u_h(x)."""
    n = len(nodes) - 1
    i = 0
    while i < n - 1 and x > nodes[i + 1]:
        i += 1
    a, b = nodes[i], nodes[i + 1]
    va = V[i - 1] if i >= 1 else 0.0
    vb = V[i] if i < n - 1 else 0.0
    xi = 2 * (x - a) / (b - a) - 1
    val = va * (1 - xi) / 2 + vb * (1 + xi) / 2
    for k, c in enumerate(C[i], start=2):
        val += c * (legendre(k, xi) - legendre(k - 2, xi)) / math.sqrt(2 * (2 * k - 1))
    return val


def quadrature_moment(du, npts=40):
    """Return a moment function for a smooth u' by Gauss-Legendre quadrature."""
    xs, ws = gauss_legendre(npts)

    def moment(a, b, j):
        return sum(w * du(a + (b - a) * (t + 1) / 2) * legendre(j, t) for t, w in zip(xs, ws))
    return moment


def corner_model(alpha):
    """Return (u, moment, energy) for u = x^alpha - x, singular at 0 for 1/2 < alpha < 1.

    On the element at 0, int_0^1 t^beta P_j(2t - 1) dt
    = beta (beta - 1) ... (beta - j + 1) / ((beta + 1) ... (beta + j + 1)) is used,
    which is exact. Elsewhere u' is analytic on the element and Gauss quadrature is used.
    """
    beta = alpha - 1

    def u(x):
        return x ** alpha - x

    def du(x):
        return alpha * x ** beta - 1

    smooth = quadrature_moment(du)

    def moment(a, b, j):
        if a > 0:
            return smooth(a, b, j)
        num, den = 1.0, beta + 1
        for k in range(j):
            num *= beta - k
            den *= beta + 2 + k
        exact = 2 * alpha * b ** beta * num / den  # x = b t, dxi = 2 dt
        return exact - (2.0 if j == 0 else 0.0)

    energy = alpha * alpha / (2 * alpha - 1) - 1  # |u|_1^2
    return u, moment, energy


def energy_error(energy, bTU):
    """Return |u - u_h|_1 from |u|_1^2 and b^T U (clipped at 0 against rounding)."""
    return math.sqrt(max(energy - bTU, 0.0))


def hp_geometric(n, sigma, mu, u, moment):
    """Geometric mesh with n layers toward 0 and linear degrees; return (N, V, C, bTU)."""
    nodes = geometric_mesh(n, sigma)  # @line L1
    degrees = linear_degrees(n, mu)  # @line L2
    V, C, bTU = solve_hp(nodes, degrees, u, moment)
    N = len(V) + sum(len(c) for c in C)
    return N, V, C, bTU
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_hp_finite_element_method.py 116 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hp-finite-element-method/. The authors are listed in prov/9VWB60.jsonl.

import math
import random

import hp_finite_element_method as H


def rel_error(nodes, degrees, model):
    u, moment, energy = model
    _, _, bTU = H.solve_hp(nodes, degrees, u, moment)
    return H.energy_error(energy, bTU) / math.sqrt(energy)


def test_hand_example_one_quadratic_element():
    u = lambda x: x - x * x
    moment = H.quadrature_moment(lambda x: 1 - 2 * x)
    V, C, bTU = H.solve_hp([0.0, 1.0], [2], u, moment)
    assert V == []
    assert abs(C[0][0] + math.sqrt(1.5) / 3) < 1e-14
    assert abs(bTU - 1.0 / 3.0) < 1e-14  # |u|_1^2 = 1/3, so the error is 0
    for x in (0.1, 0.5, 0.8):
        assert abs(H.evaluate([0.0, 1.0], V, C, x) - u(x)) < 1e-14


def test_bubbles_are_orthonormal_in_energy():
    xs, ws = H.gauss_legendre(20)
    for k in range(2, 9):
        for m in range(2, 9):
            val = sum(w * math.sqrt((2 * k - 1) / 2) * H.legendre(k - 1, t)
                      * math.sqrt((2 * m - 1) / 2) * H.legendre(m - 1, t) for t, w in zip(xs, ws))
            assert abs(val - (1.0 if k == m else 0.0)) < 1e-13
        # orthogonal to the hats, whose derivative is constant
        assert abs(sum(w * H.legendre(k - 1, t) for t, w in zip(xs, ws))) < 1e-14


def test_gauss_legendre_rule():
    xs, ws = H.gauss_legendre(7)
    assert abs(sum(ws) - 2) < 1e-14
    for d in range(14):
        exact = 0.0 if d % 2 else 2.0 / (d + 1)
        assert abs(sum(w * x ** d for x, w in zip(xs, ws)) - exact) < 1e-14


def test_singular_moments_are_exact():
    _, moment, _ = H.corner_model(0.7)
    xs, ws = H.gauss_legendre(200)
    b = 0.3
    for j in range(0, 6):
        total = 0.0
        for s, w in zip(xs, ws):  # t = r^10 removes the singularity at 0
            r = (s + 1) / 2
            t = r ** 10
            x = b * t
            total += w * 5 * r ** 9 * 2 * (0.7 * x ** -0.3 - 1) * H.legendre(j, 2 * t - 1)
        assert abs(total - moment(0.0, b, j)) < 1e-10


def test_nodal_values_are_exact_on_random_meshes():
    model = H.corner_model(0.7)
    u, moment, _ = model
    rng = random.Random(3)
    for _ in range(5):
        n = rng.randint(2, 12)
        nodes = sorted([0.0, 1.0] + [rng.uniform(0.01, 0.99) for _ in range(n - 1)])
        degrees = [rng.randint(1, 5) for _ in range(n)]
        V, C, _ = H.solve_hp(nodes, degrees, u, moment)
        for i, v in enumerate(V):
            assert abs(v - u(nodes[i + 1])) < 1e-12


def test_h_and_p_versions_are_algebraic():
    model = H.corner_model(0.7)
    e1 = rel_error([i / 64 for i in range(65)], [1] * 64, model)
    e2 = rel_error([i / 256 for i in range(257)], [1] * 256, model)
    slope_h = math.log(e2 / e1) / math.log(255 / 63)
    assert -0.22 < slope_h < -0.18  # N^(-0.2)
    e3 = rel_error([0.0, 1.0], [9], model)
    e4 = rel_error([0.0, 1.0], [17], model)
    slope_p = math.log(e4 / e3) / math.log(16 / 8)
    assert -0.44 < slope_p < -0.36  # N^(-0.4)


def test_geometric_hp_is_exponential_in_sqrt_n():
    u, moment, energy = H.corner_model(0.7)
    rows = []
    for n in (12, 20):
        N, _, _, bTU = H.hp_geometric(n, 0.15, 0.5, u, moment)
        rows.append((N, H.energy_error(energy, bTU) / math.sqrt(energy)))
    (n1, e1), (n2, e2) = rows
    assert (n1, n2) == (41, 109)
    assert e2 < 1e-3
    b = -math.log(e2 / e1) / (math.sqrt(n2) - math.sqrt(n1))
    assert 0.7 < b < 0.8
    e_uniform = rel_error([i / 1024 for i in range(1025)], [1] * 1024, (u, moment, energy))
    assert e_uniform > 100 * e2


def test_geometric_mesh_alone_stalls():
    model = H.corner_model(0.7)
    e1 = rel_error(H.geometric_mesh(16, 0.15), [1] * 16, model)
    e2 = rel_error(H.geometric_mesh(32, 0.15), [1] * 32, model)
    assert abs(e1 - e2) < 1e-3 * e1 + 1e-6  # the error of the last element with p = 1 stays


def test_smooth_solution_converges_exponentially_in_p():
    u = lambda x: math.sin(math.pi * x)
    moment = H.quadrature_moment(lambda x: math.pi * math.cos(math.pi * x))
    nodes = [0.0, 0.5, 1.0]
    errs = []
    for p in (2, 4, 6, 8):
        V, C, _ = H.solve_hp(nodes, [p, p], u, moment)
        errs.append(max(abs(H.evaluate(nodes, V, C, x) - u(x)) for x in (0.13, 0.3, 0.71)))
    assert errs[3] < 1e-8
    assert all(b < a / 50 for a, b in zip(errs, errs[1:]))

History

Engineers used elements of high degree in structural codes in the 1970s, and around 1980 Barna Szabo and Ivo Babuska studied the p refinement of fixed meshes. In 1986 Wen Gui and Babuska analyzed the h, p and hp versions in one dimension, and Benqi Guo and Babuska proved in two papers that geometric meshes with linearly increasing degrees give exponential convergence for piecewise analytic solutions on polygons. Christoph Schwab's 1998 book gave a full account of the theory. Later work extended the results to 3D, to hp-adaptivity with a posteriori estimators and to discontinuous Galerkin methods.

References

  1. B. Guo and I. Babuska, The h-p version of the finite element method. Part 1: The basic approximation results, Computational Mechanics 1(1) (1986) 21-41, geometric meshes, linear degree vectors and the exponential rate in 2D
  2. B. Guo and I. Babuska, The h-p version of the finite element method. Part 2: General results and applications, Computational Mechanics 1(3) (1986) 203-220, the rate exp(-b N^(1/3)) for piecewise analytic solutions on polygons
  3. Christoph Schwab, p- and hp-Finite Element Methods: Theory and Applications in Solid and Fluid Mechanics, Oxford University Press (1998), the 1D analysis on geometric meshes and the hierarchic Legendre basis
  4. George Em Karniadakis and Spencer J. Sherwin, Spectral/hp Element Methods for Computational Fluid Dynamics, 2nd edition, Oxford University Press (2005), the modal basis of integrated Legendre polynomials and its sparsity

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