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
- Model
- Real RAM
- Properties
- conformingdeterministicexponential convergencehierarchic basis
- Evidence
- Proof sketchCode in 1 languages
- 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 . 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 toward the singularity, combined with degrees that grow linearly away from it, gives exponential convergence: in 1D and in 2D for solutions that are piecewise analytic with corner singularities. Uniform h refinement with a fixed degree can only reach an algebraic rate , with 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 on with and a solution like with , singular at 0. Also a number of layers , a grading factor and a slope for the degrees.
Output. The Galerkin solution in the space of continuous piecewise polynomials on the geometric mesh with degree on element , and its energy error .
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 , , in the local coordinate . In 1D their derivatives are scaled Legendre polynomials, so the bubbles are orthogonal to each other and to the hats in the energy product.
HP-GEOMETRIC(n, sigma, mu, u)- 1
x_0 <- 0; x_i <- sigma^(n - i) for i = 1..n ▷ n layers toward the singularity at 0 - 2
p_i <- max(1, ceil(mu * i)) for i = 1..n ▷ the degree grows away from the singularity - 3
for each element K_i: add (1 / h_i) [[1, -1], [-1, 1]] to the hat system and its loads to b - 4
V <- solve the tridiagonal hat system ▷ the Thomas algorithm - 5
c_ik <- (h_i / 2) * b_ik for k = 2..p_i ▷ the bubble stiffness is the diagonal 2 / h_i - 6
return V and c
The loads are and , which equal and for the exact solution . 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 with and . There are no interior nodes, so the only unknown is the coefficient of . With , , so . The stiffness is , so . Then , and in fact , because is a quadratic. The error identity gives .
Measured. For , with , the reference code gives these relative energy errors.
| Method | Relative error | |
|---|---|---|
| Uniform h, | 63 | 0.437 |
| Uniform h, | 255 | 0.331 |
| Uniform h, | 1023 | 0.251 |
| One element, | 7 | 0.441 |
| One element, | 15 | 0.334 |
| One element, | 31 | 0.253 |
| Geometric, , , | 19 | |
| Geometric, | 41 | |
| Geometric, | 71 | |
| Geometric, | 109 | |
| Geometric, | 155 |
Uniform h refinement gives , the rate allowed by . Higher degree on one element gives , 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 against settles at . A geometric mesh with 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 is , 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 that the code uses. For the rate, the error is at most the error of any function in the space. On element the ratio of distance to size is fixed, so is analytic in an ellipse of fixed shape around it, and polynomials of degree approximate it with error . The small element at 0 contributes . Linear degrees balance the two, each term is at most with , and turns into .
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 on with , in the weak form: find with for all . The energy norm is . A mesh has elements of length , each with a degree . The space is the set of continuous functions in that are polynomials of degree at most on . On the local coordinate is with . The basis is the hat functions at the interior nodes and the bubbles , , which are 0 outside . HP-GEOMETRIC is lines L1 to L6 of the main page.
We prove four claims.
- (The solver.) Lines L3 to L5 return the coefficients of the Galerkin solution , for all .
- (Error identity.) , where is the load vector and the coefficient vector.
- (Nodal exactness.) at every node, for every choice of the degrees.
- (Exponential rate.) Let with , so that . For the geometric mesh , with , and the degrees with , there are constants that depend on , and but not on such that , where .
Proof of 1. The functions are a basis of : on each element, the two linear functions and the , , span the polynomials of degree , because has degree exactly . The bubbles are 0 at , because , so the functions are continuous. Now compute the stiffness matrix. The standard identity gives . With and ,
by and the orthogonality of the Legendre polynomials. A hat function has a constant derivative on , and for , so . 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 entries, and the diagonal 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, . The loads are , which the code computes exactly from the values of at the nodes, since is , and .
Proof of 2. By claim 1, . So , and .
Proof of 3. Fix an interior node . Let be the function in that is linear on and on , with . Then for every , , so with . The function is linear on each element, so . Galerkin orthogonality gives .
Proof of 4. By claim 1, is the best approximation in the energy norm, for every . We build a good element by element, with at every node, so that the pieces join into a continuous function in . On we take , the projection of onto the polynomials of degree , and . The projection keeps the mean of , because constants are in the space, so at both ends. Then , with the infimum over the polynomials of degree .
The first element has . Here is at least as good as the linear interpolant, and . This uses , and the linear interpolant error is at most because it is the projection of onto constants.
Each other element with has and left end , so is the same for all of them. In the local coordinate, the only singularity of is at , a fixed point left of . So is analytic inside the Bernstein ellipse with foci through , with parameter . Fix . On the ellipse with parameter , with that depends only on and , so there. The classical estimate for analytic functions (Bernstein) gives a polynomial of degree with . With the factor ,
Sum. Let . With , each term is at most , and the first element also gives at most . So , and for any . The dimension is , so , and with .
Remarks. With and , the factor predicts that each new layer cuts the error by about this factor. The reference run with measures a factor of per two layers. The same proof with on all elements shows why the geometric mesh alone stalls: the last element keeps an error that does not depend on . In 2D the same construction, with geometric layers toward each corner of a polygon, gives 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 . The loads need quadrature with a number of points that grows with : with Gauss points per bubble on each element, the load costs , which is . In 2D and 3D the element matrices for degree have entries, and static condensation of the interior bubbles costs per element with dense algebra, which is why codes for high use sum factorization on tensor product elements. Memory is in 1D.
Properties
- Exponential convergence. For solutions that are piecewise analytic with point singularities, geometric meshes with linear degrees give in 1D and in 2D, with independent of .
- Hierarchic basis. Raising on an element adds new bubbles and keeps the old ones, so the matrix for degree is a submatrix of the one for .
- Nodal exactness in 1D. For , the Galerkin solution equals at every node, whatever the degrees. The bubbles only add the interior detail.
- Robust grading. The rate is exponential for every and every . Only the constant depends on them. In this test, from 0.15 to 0.2 and from 0.5 to 1 all worked.
- Conforming. The space is a subspace of , 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 on the element: fast decay means the solution is smooth there, so raise .
- 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 , 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. subtracts two numbers that are close, so it cannot measure errors below about times in double precision.
- Conditioning. The condition number of the stiffness matrix grows like a power of , 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.
# 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
- 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
- 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
- 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
- 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.
| 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 9VWB60 Edit this page History Report an error Markdown