Algorithmresearch
Hybridizable discontinuous Galerkin method
Also called HDG method.
A discontinuous Galerkin method that removes the cell unknowns by static condensation, so that the only global unknowns are the traces on the faces.
- Solves
- Poisson equation
- Time
- Θ(m k^3) worst
- Space
- Θ(m k + k^2) extra
- Where
- k = the polynomial degree; m = the number of cells
- Model
- Real RAM
- Properties
- consistentdeterministicexact nodal traces in 1d for k at least 1locally conservativesymmetric positive definite trace system
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Bernardo Cockburn, Jayadeep Gopalakrishnan, Raytcho Lazarov, 2009
The hybridizable discontinuous Galerkin method (HDG) solves elliptic problems such as with two fields, the solution and its flux , both discontinuous polynomials on the cells, plus a third field that lives only on the faces. On each cell the method solves a small problem for with as boundary data, and the flux through a face is with a stabilization parameter . The only global equation is that this flux is the same seen from both sides of each face. After the cell unknowns are removed by static condensation, the global system has only the face unknowns, and it is symmetric positive definite. Both and converge with the order .
In plain words
Picture a chain of rooms with a door between each pair. In each room you can solve the problem alone if somebody tells you the value at the doors. The method makes the door values the only shared unknowns. For a guess of the door values, every room computes its answer and the flow that it sends through its doors. The flow that leaves one room through a door must enter the next room, and this balance gives one equation per door. You solve these door equations first, which is a small system, and then each room finds its own answer from the door values. The rooms do not have to agree at the doors, and a parameter controls how strongly the room values are pulled toward the door values.
The problem
Input. A mesh of a domain , a source , Dirichlet data , a degree and a parameter . The reference code takes , , , , and cells of width .
Output. Polynomials of degree on each cell and the traces on the faces (in 1D, one value at each node), with on the boundary and, on every cell and for all polynomials of degree ,
and on every interior face the two values of add up to .
The algorithm
HDG(f, m, k, tau, g0, g1) ▷ -u'' = f on (0, 1), degree k, m cells, h = 1/m- 1
for each cell K_j do - 2
solve the local problem for (q, u) with three right sides: uhat_L = 1, uhat_R = 1, and f - 3
write the end fluxes qhat n as affine functions of (uhat_j, uhat_(j+1)) - 4
add minus the end fluxes to rows j and j + 1 of the tridiagonal trace system - 5
move the known values uhat_0 = g0 and uhat_m = g1 to the right side - 6
uhat <- THOMAS(trace system) ▷ symmetric positive definite - 7
for each cell K_j do (q, u) <- uhat_j s_L + uhat_(j+1) s_R + s_f - 8
return uhat and (q, u) on every cell
Lines L1 to L4 are static condensation. The local problem on line L2 has unknowns, and it has one solution for every . Since the problem is linear in the data, its solution for any traces is the combination of the three columns, and the cell stores them for line L7. A cell touches only two traces, so the global system is tridiagonal in 1D, and line L6 solves it with the Thomas algorithm. In several dimensions each face carries a polynomial of degree , and the global matrix couples the faces of each cell.
Example
Take with , so , with , , and . On each cell and with .
| step | result |
|---|---|
| L2, | , |
| L2, | , |
| L2, load | , |
| L3 | left flux , right flux |
| L4, node | row (the two cells give the same numbers) |
| L5, L6 | |
| L7, cell 0 | , |
| L7, cell 1 | , |
The trace is the exact value . The cell values are not exact, and differs from the trace. With and the same data the method gives , which is not exact.
Convergence (measurement). For and the reference code gives, at :
| errors of | order | errors of | order | |
|---|---|---|---|---|
| 0 | , , , | 0.99 | , , , | 1.01 |
| 1 | , , , | 2.00 | , , , | 2.01 |
| 2 | , , , | 3.00 | , , , | 3.00 |
| 3 | , , , | 4.00 | , , , | 4.00 |
The orders are those of the last refinement. For the largest nodal trace errors are , , and , the same for every and . They come only from the quadrature of the load, because the traces are exact when the load is exact.
Correctness
The full proof is in the correctness proof. Testing the local problem with and gives for zero data, so for the local problem has one solution, and lines L2 to L4 build the flux balance rows exactly. The same test with two sets of traces gives the energy identity
so the trace matrix is symmetric positive definite for every and . In 1D with , testing the second local equation with and shows that the end fluxes are at the left end and at the right end. So the trace system is exactly the system of linear finite elements, , for every and , and since linear elements are exact at the nodes in 1D, the traces are the exact values . If is a polynomial of degree at most , the method returns and exactly.
Proof: HDG local problems are uniquely solvable, the trace system is symmetric positive definite, and for k at least 1 the traces are exact at the nodesfull
Setting. The problem is on with and , written as and . The mesh has the nodes , , , and the cells . On each cell and are polynomials of degree at most , and there is one trace value at each node. On the boundary of a cell the outward normal is at the left end and at the right end, and means , with taken at the end where is evaluated. The numerical flux is with a constant . The local problem on is: given at the two ends of , find with
The global equation at an interior node is that the two values of at , one from and one from , add up to . The code writes it as the row , and it fixes and .
Claim 1 (local well-posedness). For every and the local problem has exactly one solution for any data and .
Proof. The problem is a square linear system, so it is enough to show that and give only . Take in (1) and in (2):
Integration by parts gives , so the second equation is . The sum of the two equations is . So and at both ends. Then (1) reads for all , that is, is orthogonal to . If , is a constant that is at an end, so . If , where is the Legendre polynomial of degree moved to , and at the ends, so .
Claim 2 (what the code computes). Lines L1 to L4 build the rows exactly, line L5 moves the boundary values to the right side, and lines L6 and L7 return the traces and the local solutions of the HDG equations.
Proof. In the basis , , the entries of the local matrix are and for , and at the right end and at the left end. These are the entries that local_matrix writes, with the and parts of on the left side and the parts on the right side, as local_rhs writes them. By Claim 1 the matrix is nonsingular, and since the problem is linear in , the local solution is with the three columns that line L2 computes. So at each end is affine in with the coefficients of line L3, in which is the part of the flux. Line L4 adds of the right end of to row and of its left end to row , so row is , in the tridiagonal arrays because on depends only on and . Line L5 is the usual elimination of known values, line L6 solves the interior rows, and line L7 forms the local solutions from the stored columns.
Claim 3 (the trace system is symmetric positive definite). Let and let , be trace vectors that are at and . Write for the local solutions with traces . Then
So the matrix of the rows is symmetric, and it is positive definite for all and .
Proof. Since at the boundary nodes, the left side is . Fix a cell . Test (1) for with : . Test (2) for with and integrate by parts as in Claim 1: . Eliminating gives
Now , and the sum over the two ends gives the cell term of the identity. The right side is symmetric in and , so is symmetric. With it is . If it is , then on every cell, and (1) with gives , so on every cell. Then is constant, and makes it .
Claim 4 (end fluxes for ). If , the end fluxes of the local solution on are
with and , for every .
Proof. Equation (1) with gives . Since , is allowed in (2). It is at the left end, at the right end, and , so (2) gives , which is the second formula. In the same way is at the left end, at the right end, and , which gives , the first formula.
Claim 5 (the trace system is the linear finite element system). If , the row at an interior node is
where is the piecewise linear hat function of node . So , independent of and .
Proof. Add the right-end flux of and the left-end flux of from Claim 4 and change the sign. The functions on and on are the two halves of .
Claim 6 (exact traces for ). If and is the exact solution, then for every , when the loads are integrated exactly.
Proof. For an interior node, , so the weak form gives . On , , and on , , so . By Claim 5 the nodal values of satisfy every row , and they take the boundary values and . By Claim 3 the system has only one solution.
The code integrates the loads with the five-point Boole rule, which is exact for polynomials of degree at most . The traces depend on only through , so they are exact when is a polynomial of degree at most . For other the traces are the nodal values of the piecewise linear solution with the quadrature load.
Claim 7 (polynomial reproduction). If the exact solution is a polynomial of degree at most and the loads are exact, then the method returns , on every cell and .
Proof. Take and at the nodes. Integration by parts gives (1), because and at the ends, and it gives (2), because at the ends makes and . The global equations hold because is continuous at every node, so the two values of have opposite signs. By Claim 3 the traces are unique, and by Claim 1 so are the local solutions.
Conclusion. By Claim 2 the code assembles the HDG trace equations, and by Claim 3 their matrix is symmetric positive definite for every and . It is tridiagonal, and the Thomas algorithm in line L6 needs no pivoting for a symmetric positive definite tridiagonal matrix, so it finds the unique traces. By Claim 1 line L7 then gives the unique local solutions, and line L8 returns them. For the traces are the exact nodal values (Claim 6), and polynomials of degree at most are reproduced exactly (Claim 7).
Complexity
Line L2 solves a dense system of size with three right sides, which costs per cell. Line L3 costs and line L4 costs , so the loop takes time. Line L6 costs and line L7 costs . The code keeps three columns of length for each cell and one local matrix, which is memory. Discontinuous Galerkin methods such as SIPG couple all cell unknowns. HDG couples only the interior traces in 1D, and in several dimensions only the face polynomials. For high degrees in 3D this is much smaller than the DG system, but the local solves then dominate the cost.
Properties
- Symmetric positive definite global system (theorem). For every and , by the energy identity above.
- Order for and (theorem). With of order one, the projection-based analysis of Cockburn, Gopalakrishnan and Sayas gives for both fields. Mixed methods also have this property, but most DG methods give the flux only with order .
- Exact traces in 1D (theorem). For the trace system does not depend on or and equals the linear element system, so the traces are exact at the nodes when the load is integrated exactly. For this is false: with and the trace errors are , and . In several dimensions the traces are not exact, but they superconverge.
- Effect of (measurement). With in place of the errors in the table become smaller and the errors larger, and for the observed orders of approach more slowly: , and at the last refinement. For and the order of is only at .
- Local conservation. Taking in the second local equation gives on every cell, with a single-valued flux.
- Local postprocessing. Because has order , a new local problem on each cell gives an approximation of degree with order for in several dimensions.
Variants and improvements
- Choice of . A constant of order one is common. A that is positive on only one face of each cell gives another member of the family, and the limit approaches a continuous Galerkin method. For convection-diffusion, includes an upwind part.
- Hybridized mixed methods. With Raviart-Thomas spaces for and no stabilization, the same local-solve and trace structure gives the hybridized mixed method of Arnold and Brezzi. Cockburn, Gopalakrishnan and Lazarov put mixed, HDG and continuous Galerkin methods into one framework with different local solvers.
- HDG+ and reduced trace spaces. Using degree for and degree for the traces, with a of order , keeps the order with fewer global unknowns.
- Other equations. HDG methods exist for Stokes, linear elasticity, Maxwell and compressible flow, where the face unknowns are the traces of velocity or of the tangential field.
When to use it
Use HDG for high polynomial degrees on unstructured meshes, where a standard discontinuous Galerkin method has too many globally coupled unknowns, and when an accurate flux and local conservation matter, as in porous media flow or convection-dominated transport. The local solves are independent, so they run in parallel. For low degrees on a conforming mesh, continuous Galerkin with static condensation often has a smaller global system, and the HDG trace system is then no advantage.
Pitfalls
- without a mixed space. With equal-degree polynomials for and , the local problem of line L2 is singular for . The energy argument then gives only , and , with the Legendre polynomial of degree on the cell, solves the local problem with zero data. Keep .
- Wrong sign of the normal. The flux in line L3 uses at the left end. With the wrong sign the local equations no longer follow from integration by parts, and the exact solution does not satisfy them.
- Forgetting the part of the flux. The flux of line L3 contains . If the term is dropped, the trace system is no longer the balance of the true fluxes, and the method is not consistent.
- Comparing with the trace. At a node from the left, from the right and are three different numbers. Use the trace for nodal values.
- Postprocessing with . The flux has only order for , so the postprocessed solution does not gain an order.
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/hybridizable-discontinuous-galerkin/. The authors are listed in prov/EC181T.jsonl.
"""HDG for -u'' = f on (0, 1) with u(0) = g0 and u(1) = g1.
The first-order form is q + u' = 0 and q' = f. The mesh is uniform with m
cells K_j = (x_j, x_j + h), h = 1/m. On each cell q and u are polynomials
of degree k in the local monomial basis xi^r, xi = (x - x_j) / h. The
global unknowns are the traces uhat_0, ..., uhat_m at the nodes. On the
boundary of a cell, with the outward normal n = -1 at the left end and
n = +1 at the right end, the numerical flux is
qhat n = q n + tau (u - uhat).
Local equations on K, for all polynomials r, w of degree k:
(q, r)_K - (u, r')_K + [uhat r n]_{boundary of K} = 0
-(q, w')_K + [qhat n w]_{boundary of K} = (f, w)_K
Global equation at an interior node: the two values of qhat n add up to 0.
With Fraction data (f, tau, g0, g1) every step is exact.
"""
from fractions import Fraction
import scimat
import scisparse
BOOLE = [(Fraction(0), Fraction(7, 90)), (Fraction(1, 4), Fraction(32, 90)),
(Fraction(1, 2), Fraction(12, 90)), (Fraction(3, 4), Fraction(32, 90)),
(Fraction(1), Fraction(7, 90))]
def local_matrix(k, h, tau):
"""Matrix of the local problem; unknowns (q_0..q_k, u_0..u_k), rows (r_0..r_k, w_0..w_k)."""
n = k + 1
L = scimat.zeros(2 * n)
for i in range(n):
for s in range(n):
L[i][s] = h / (i + s + 1) # (q, r_i)_K, mass matrix
if i >= 1:
d = Fraction(i, i + s) if isinstance(h, Fraction) else i / (i + s) # (xi^s, (xi^i)')_K
L[i][n + s] -= d # -(u, r_i')_K
L[n + i][s] -= d # -(q, w_i')_K
# right end: q n w = q(1) w_i(1), and tau u(1) w_i(1)
L[n + i][s] += 1
L[n + i][n + s] += tau
# left end: n = -1 and w_i(0) = 1 only for i = 0, so row w_0 gets -q(0) + tau u(0)
L[n][0] -= 1
L[n][n] += tau
return L
def local_rhs(f, k, h, x0, tau):
"""Three right sides of the local problem: for uhat_L = 1, for uhat_R = 1, and for f."""
n = k + 1
rL = [0] * (2 * n)
rR = [0] * (2 * n)
rf = [0] * (2 * n)
for i in range(n):
# first equation: -[uhat r n] moves to the right side; r_i(1) = 1, r_i(0) = [i = 0]
rR[i] = -1
rL[i] = 1 if i == 0 else 0
# second equation: -tau uhat w moves to the right side as +tau uhat w
rR[n + i] = tau
rL[n + i] = tau if i == 0 else 0
for xi, wq in BOOLE:
rf[n + i] += wq * h * f(x0 + xi * h) * xi ** i
return rL, rR, rf
def end_fluxes(sol, k, tau):
"""Return qhat n at the left and right end for a local solution with uhat = 0 there."""
n = k + 1
q, u = sol[:n], sol[n:]
left = -q[0] + tau * u[0]
right = sum(q) + tau * sum(u)
return left, right
def hdg(f, m, k, tau=1, g0=0, g1=0):
"""Solve the HDG problem. Return (uhat, cells) where cells[j] = (q coefficients, u coefficients).
Precondition: m >= 2, k >= 0, tau > 0. Cost: Theta(m k^3) for the local
solves and Theta(m) for the trace system.
"""
exact_data = isinstance(tau, Fraction)
h = Fraction(1, m) if exact_data else 1.0 / m
n = k + 1
L = local_matrix(k, h, tau)
lo = [0] * (m + 1)
di = [0] * (m + 1)
up = [0] * (m + 1)
rhs = [0] * (m + 1)
local = []
for j in range(m): # @line L1
rL, rR, rf = local_rhs(f, k, h, j * h, tau)
cols = scimat.solve(L, [[rL[i], rR[i], rf[i]] for i in range(2 * n)]) # @line L2
sL = [row[0] for row in cols]
sR = [row[1] for row in cols]
sf = [row[2] for row in cols]
local.append((sL, sR, sf))
# qhat n at each end is affine in (uhat_L, uhat_R): value(sL) uhat_L + value(sR) uhat_R
# + value(sf), minus tau uhat at that end
left_l, right_l = end_fluxes(sL, k, tau)
left_r, right_r = end_fluxes(sR, k, tau)
left_f, right_f = end_fluxes(sf, k, tau)
fl = (left_l - tau, left_r, left_f) # left end: coefficients of uhat_j, uhat_{j+1}, constant
fr = (right_l, right_r - tau, right_f) # right end # @line L3
# the global row of node e is -(sum of qhat n) = 0; cell j adds to rows j and j + 1
di[j] -= fl[0] # @line L4
up[j] -= fl[1]
rhs[j] += fl[2]
lo[j + 1] -= fr[0]
di[j + 1] -= fr[1]
rhs[j + 1] += fr[2]
rhs[1] -= lo[1] * g0 # @line L5
rhs[m - 1] -= up[m - 1] * g1
lo[1] = 0
up[m - 1] = 0
inner = scisparse.thomas(lo[1:m], di[1:m], up[1:m], rhs[1:m]) # @line L6
uhat = [g0] + inner + [g1]
cells = []
for j in range(m): # @line L7
sL, sR, sf = local[j]
sol = [sL[i] * uhat[j] + sR[i] * uhat[j + 1] + sf[i] for i in range(2 * n)]
cells.append((sol[:n], sol[n:]))
return uhat, cells # @line L8
def trace_matrix(m, k, tau):
"""Dense matrix of the trace system on the interior nodes (for tests), f = 0."""
exact_data = isinstance(tau, Fraction)
zero = (lambda x: Fraction(0)) if exact_data else (lambda x: 0.0)
size = m - 1
S = scimat.zeros(size)
for e in range(1, m):
g = [0] * (m + 1)
g[e] = 1
# the residual of the global rows for uhat = unit vector e, f = 0
res = residual(zero, m, k, tau, g)
for i in range(1, m):
S[i - 1][e - 1] = res[i]
return S
def residual(f, m, k, tau, uhat):
"""Return the global rows -(sum of qhat n) at every node for given traces (local problems solved exactly)."""
exact_data = isinstance(tau, Fraction)
h = Fraction(1, m) if exact_data else 1.0 / m
n = k + 1
L = local_matrix(k, h, tau)
res = [0] * (m + 1)
for j in range(m):
rL, rR, rf = local_rhs(f, k, h, j * h, tau)
b = [rL[i] * uhat[j] + rR[i] * uhat[j + 1] + rf[i] for i in range(2 * n)]
sol = scimat.solve(L, b)
q, u = sol[:n], sol[n:]
left = -q[0] + tau * (u[0] - uhat[j])
right = sum(q) + tau * (sum(u) - uhat[j + 1])
res[j] -= left
res[j + 1] -= right
return res
scimat.py 227 lines
# SPDX-License-Identifier: MIT
# Shared helper of the scientific-computing pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small dense linear algebra and error norms for the scientific-computing pages.
A matrix is a list of rows and a vector is a list. Entries may be int,
float or fractions.Fraction. The routines that do not take a square root
(solve, inv, det and the arithmetic) keep Fraction entries exact.
cholesky, cholesky_solve and norm2 take square roots and return floats.
API (fixed; other pages copy this file byte for byte):
zeros(m, n=None) m by n zero matrix (n = m if not given)
eye(n) n by n identity
add(A, B), sub(A, B) entrywise sum and difference (vectors or matrices)
scale(c, A) c times A (vector or matrix)
matmul(A, B) matrix product
matvec(A, x) matrix times vector
transpose(A) transpose
dot(x, y) inner product of two vectors
norm2(x) Euclidean norm of a vector, as a float
outer(x, y) outer product x y^T
solve(A, b) Gaussian elimination with partial pivoting;
b is a vector or a matrix of right sides
inv(A) inverse of A
det(A) determinant of A
cholesky(A) lower triangular L with A = L L^T (floats)
cholesky_solve(L, b) solve L L^T x = b for a vector b
err_l1(e, dx=1) sum |e_j| dx
err_l2(e, dx=1) sqrt(sum e_j^2 dx), as a float
err_linf(e, dx=1) max |e_j| (dx is not used)
observed_order(errors) [log2(E_i / E_(i+1)) for successive errors]
"""
import math
def zeros(m, n=None):
"""Return an m by n matrix of zeros (n = m if n is None)."""
if n is None:
n = m
return [[0] * n for _ in range(m)]
def eye(n):
"""Return the n by n identity matrix."""
out = zeros(n, n)
for i in range(n):
out[i][i] = 1
return out
def _is_matrix(a):
return len(a) > 0 and isinstance(a[0], list)
def add(a, b):
"""Return a + b for two vectors or two matrices of the same shape."""
if _is_matrix(a):
return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
return [x + y for x, y in zip(a, b)]
def sub(a, b):
"""Return a - b for two vectors or two matrices of the same shape."""
if _is_matrix(a):
return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
return [x - y for x, y in zip(a, b)]
def scale(c, a):
"""Return c times a, for a vector or a matrix a."""
if _is_matrix(a):
return [[c * x for x in row] for row in a]
return [c * x for x in a]
def transpose(a):
"""Return the transpose of the matrix a."""
return [list(col) for col in zip(*a)]
def matmul(a, b):
"""Return the matrix product a b."""
bt = transpose(b)
return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]
def matvec(a, x):
"""Return the product of the matrix a and the vector x."""
return [sum(aij * xj for aij, xj in zip(row, x)) for row in a]
def dot(x, y):
"""Return the inner product of the vectors x and y."""
return sum(a * b for a, b in zip(x, y))
def norm2(x):
"""Return the Euclidean norm of the vector x, as a float."""
return math.sqrt(float(dot(x, x)))
def outer(x, y):
"""Return the outer product x y^T as a matrix."""
return [[a * b for b in y] for a in x]
def _eliminate(a, rhs):
"""Reduce a to upper triangular form with partial pivoting.
a is a copy of the square matrix, rhs a list of right side rows (one
row per row of a) that receives the same row operations. Return the
number of row swaps. Raise ValueError if a pivot is zero.
"""
n = len(a)
swaps = 0
for k in range(n):
p = max(range(k, n), key=lambda i: abs(a[i][k]))
if a[p][k] == 0:
raise ValueError("matrix is singular")
if p != k:
a[k], a[p] = a[p], a[k]
rhs[k], rhs[p] = rhs[p], rhs[k]
swaps += 1
for i in range(k + 1, n):
f = a[i][k] / a[k][k]
if f == 0:
continue
for j in range(k, n):
a[i][j] -= f * a[k][j]
for j in range(len(rhs[i])):
rhs[i][j] -= f * rhs[k][j]
return swaps
def solve(a, b):
"""Solve a x = b by Gaussian elimination with partial pivoting.
b is a vector (the result is a vector) or a matrix with one column per
right side (the result is a matrix). Fraction entries stay exact.
Raise ValueError if a is singular.
"""
n = len(a)
work = [list(row) for row in a]
vector = not _is_matrix(b)
rhs = [[v] for v in b] if vector else [list(row) for row in b]
_eliminate(work, rhs)
m = len(rhs[0]) if n else 0
x = [[0] * m for _ in range(n)]
for i in range(n - 1, -1, -1):
for j in range(m):
s = rhs[i][j]
for k in range(i + 1, n):
s -= work[i][k] * x[k][j]
x[i][j] = s / work[i][i]
if vector:
return [row[0] for row in x]
return x
def inv(a):
"""Return the inverse of the square matrix a."""
return solve(a, eye(len(a)))
def det(a):
"""Return the determinant of the square matrix a (0 if singular)."""
work = [list(row) for row in a]
rhs = [[] for _ in a]
try:
swaps = _eliminate(work, rhs)
except ValueError:
return 0
d = -1 if swaps % 2 else 1
for i in range(len(a)):
d *= work[i][i]
return d
def cholesky(a):
"""Return the lower triangular L with a = L L^T, in floats.
Raise ValueError if a is not symmetric positive definite.
"""
n = len(a)
low = [[0.0] * n for _ in range(n)]
for j in range(n):
s = float(a[j][j]) - sum(low[j][k] ** 2 for k in range(j))
if s <= 0.0:
raise ValueError("matrix is not positive definite")
low[j][j] = math.sqrt(s)
for i in range(j + 1, n):
t = float(a[i][j]) - sum(low[i][k] * low[j][k] for k in range(j))
low[i][j] = t / low[j][j]
return low
def cholesky_solve(low, b):
"""Solve L L^T x = b, with L from cholesky, for a vector b."""
n = len(low)
y = [0.0] * n
for i in range(n):
y[i] = (float(b[i]) - sum(low[i][k] * y[k] for k in range(i))) / low[i][i]
x = [0.0] * n
for i in range(n - 1, -1, -1):
x[i] = (y[i] - sum(low[k][i] * x[k] for k in range(i + 1, n))) / low[i][i]
return x
def err_l1(e, dx=1):
"""Return the discrete L1 norm sum |e_j| dx."""
return sum(abs(v) for v in e) * dx
def err_l2(e, dx=1):
"""Return the discrete L2 norm sqrt(sum e_j^2 dx), as a float."""
return math.sqrt(float(sum(v * v for v in e) * dx))
def err_linf(e, dx=1):
"""Return the max norm max |e_j|. dx is accepted for a uniform call and not used."""
return max(abs(v) for v in e)
def observed_order(errors):
"""Return [log2(E_i / E_(i+1))] for a list of errors on meshes h, h/2, h/4, ..."""
return [math.log2(float(errors[i]) / float(errors[i + 1])) for i in range(len(errors) - 1)]
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_hybridizable_discontinuous_galerkin.py 139 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hybridizable-discontinuous-galerkin/. The authors are listed in prov/EC181T.jsonl.
import math
import random
from fractions import Fraction as F
import scimat
from hybridizable_discontinuous_galerkin import hdg, residual, trace_matrix
# 5-point Gauss-Legendre rule on [-1, 1], independent of the code under test
GX = [-0.9061798459386640, -0.5384693101056831, 0.0, 0.5384693101056831, 0.9061798459386640]
GW = [0.2369268850561891, 0.4786286704993665, 0.5688888888888889, 0.4786286704993665, 0.2369268850561891]
def errors(cells, m, u, q):
h = 1.0 / m
eu = eq = 0.0
for j, (qc, uc) in enumerate(cells):
for xg, wg in zip(GX, GW):
xi = (xg + 1) / 2
x = j * h + xi * h
uv = sum(float(c) * xi ** r for r, c in enumerate(uc))
qv = sum(float(c) * xi ** r for r, c in enumerate(qc))
eu += wg * h / 2 * (uv - u(x)) ** 2
eq += wg * h / 2 * (qv - q(x)) ** 2
return math.sqrt(eu), math.sqrt(eq)
def local_coefficients(p, x0, h, size):
"""Coefficients of p(x0 + xi h) in powers of xi, padded to size, for p in powers of x."""
out = [F(0)] * size
for n, pn in enumerate(p):
for r in range(n + 1):
out[r] += pn * math.comb(n, r) * x0 ** (n - r) * h ** r
return out
def test_page_example_two_cells() -> None:
uhat, cells = hdg(lambda x: F(2), 2, 1, F(1))
assert uhat == [0, F(1, 4), 0]
assert cells[0] == ([F(-25, 26), F(12, 13)], [F(1, 26), F(1, 4)])
assert cells[1] == ([F(1, 26), F(12, 13)], [F(15, 52), F(-1, 4)])
# the same data with k = 0 gives a trace that is not exact
uhat, cells = hdg(lambda x: F(2), 2, 0, F(1))
assert uhat == [0, F(1, 5), 0]
assert cells == [([F(-2, 5)], [F(3, 5)]), ([F(2, 5)], [F(3, 5)])]
def test_trace_system_is_the_p1_stiffness_matrix() -> None:
for m in (2, 4, 5):
want = [[0] * (m - 1) for _ in range(m - 1)]
for i in range(m - 1):
want[i][i] = 2 * m
if i > 0:
want[i][i - 1] = -m
if i < m - 2:
want[i][i + 1] = -m
for k in (1, 2, 3):
for tau in (F(1, 3), F(1), F(7)):
assert trace_matrix(m, k, tau) == want
# for k = 0 the matrix depends on tau and is not the P1 matrix
assert trace_matrix(4, 0, F(1))[0][:2] == [9, F(-9, 2)]
assert trace_matrix(4, 0, F(1)) != trace_matrix(4, 0, F(2))
def test_trace_matrix_is_symmetric_positive_definite() -> None:
for m in (2, 3, 6):
for k in (0, 1, 2, 3):
for tau in (F(1, 10), F(1), F(10)):
S = trace_matrix(m, k, tau)
n = len(S)
assert all(S[i][j] == S[j][i] for i in range(n) for j in range(n))
scimat.cholesky(S) # raises if not positive definite
def test_traces_exact_at_nodes_for_k_at_least_one() -> None:
# u = x^4 - x is not in P_1, but the traces are exact
uhat, _ = hdg(lambda x: -12 * x * x, 4, 1, F(1))
assert uhat == [F(e, 4) ** 4 - F(e, 4) for e in range(5)]
# u = x^5 with k = 2 and tau = 3, nonzero boundary value at x = 1
uhat, _ = hdg(lambda x: -20 * x ** 3, 3, 2, F(3), F(0), F(1))
assert uhat == [F(e, 3) ** 5 for e in range(4)]
def test_traces_not_exact_for_k_zero() -> None:
uhat, _ = hdg(lambda x: -12 * x * x, 4, 0, F(2))
exact = [F(e, 4) ** 4 - F(e, 4) for e in range(5)]
assert uhat[0] == exact[0] and uhat[4] == exact[4]
assert all(uhat[e] != exact[e] for e in range(1, 4))
def test_global_rows_vanish_at_the_computed_traces() -> None:
f = lambda x: F(1) + x - 3 * x * x
for m, k, tau in ((3, 1, F(1)), (4, 2, F(1, 2)), (5, 3, F(4))):
uhat, _ = hdg(f, m, k, tau)
res = residual(f, m, k, tau, uhat)
assert all(r == 0 for r in res[1:m])
def test_random_polynomials_against_closed_form() -> None:
# oracle: the exact pair u = p, q = -p' for a random polynomial p of degree <= k
rng = random.Random(13)
for _ in range(500):
k = rng.randint(1, 3)
m = rng.randint(2, 4)
p = [rng.randint(-5, 5) for _ in range(k + 1)]
f2 = [-(n + 2) * (n + 1) * p[n + 2] for n in range(k - 1)]
dp = [-(n + 1) * p[n + 1] for n in range(k)]
def f(x, f2=f2):
return sum(cn * x ** n for n, cn in enumerate(f2))
def u(x, p=p):
return sum(cn * x ** n for n, cn in enumerate(p))
tau = rng.uniform(0.1, 10.0)
uhat, cells = hdg(f, m, k, tau, u(0.0), u(1.0))
h = F(1, m)
for e in range(m + 1):
assert abs(uhat[e] - u(e / m)) < 1e-9
for j in range(m):
wu = local_coefficients([F(v) for v in p], j * h, h, k + 1)
wq = local_coefficients([F(v) for v in dp], j * h, h, k + 1)
assert all(abs(float(a) - float(b)) < 1e-8 for a, b in zip(cells[j][1], wu))
assert all(abs(float(a) - float(b)) < 1e-8 for a, b in zip(cells[j][0], wq))
def test_convergence_rates_of_u_and_q() -> None:
u = lambda x: math.sin(math.pi * x)
q = lambda x: -math.pi * math.cos(math.pi * x)
f = lambda x: math.pi ** 2 * math.sin(math.pi * x)
for k in (1, 2, 3):
e = [errors(hdg(f, m, k, 1.0)[1], m, u, q) for m in (8, 16)]
assert abs(math.log2(e[0][0] / e[1][0]) - (k + 1)) < 0.15
assert abs(math.log2(e[0][1] / e[1][1]) - (k + 1)) < 0.15
# k = 0: first order only
e = [errors(hdg(f, m, 0, 1.0)[1], m, u, q) for m in (16, 32)]
assert abs(math.log2(e[0][0] / e[1][0]) - 1) < 0.2
History
Fraeijs de Veubeke introduced hybridization for finite element models in 1965, with Lagrange multipliers on the faces that remove the continuity constraints between cells. Arnold and Brezzi showed in 1985 that the multipliers of the hybridized mixed method carry information that allows a local postprocessing of higher order. Celiker and Cockburn proved in 2007 the superconvergence of the numerical traces of DG and hybridized methods in one space dimension. In 2009 Cockburn, Gopalakrishnan and Lazarov defined the hybridizable DG methods with the flux , and in 2010 Cockburn, Gopalakrishnan and Sayas proved the order for both fields with a projection designed for the method.
References
- Bernardo Cockburn, Jayadeep Gopalakrishnan and Raytcho Lazarov, Unified hybridization of discontinuous Galerkin, mixed, and continuous Galerkin methods for second order elliptic problems, SIAM Journal on Numerical Analysis 47(2) (2009) 1319-1365, the definition of the HDG methods with the numerical flux q n + tau (u - uhat), the local solvers and the global trace system
- Bernardo Cockburn, Jayadeep Gopalakrishnan and Francisco-Javier Sayas, A projection-based error analysis of HDG methods, Mathematics of Computation 79(271) (2010) 1351-1367, the HDG projection and the order k + 1 for both the scalar and the flux variable
- Fatih Celiker and Bernardo Cockburn, Superconvergence of the numerical traces of discontinuous Galerkin and hybridized methods for convection-diffusion problems in one space dimension, Mathematics of Computation 76(257) (2007) 67-96, the superconvergence of the numerical traces in one space dimension
- Douglas N. Arnold and Franco Brezzi, Mixed and nonconforming finite element methods, implementation, postprocessing and error estimates, ESAIM Mathematical Modelling and Numerical Analysis 19(1) (1985) 7-32, the hybridization of mixed methods with Lagrange multipliers on the faces
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 EC181T Edit this page History Report an error Markdown