Algorithm Search⌘K

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.

Time
Θ(m k^3) worst
Space
Θ(m k + k^2) extra
Where
k = the polynomial degree; m = the number of cells
Properties
consistentdeterministicexact nodal traces in 1d for k at least 1locally conservativesymmetric positive definite trace system
Origin
Bernardo Cockburn, Jayadeep Gopalakrishnan, Raytcho Lazarov, 2009

The hybridizable discontinuous Galerkin method (HDG) solves elliptic problems such as −Δu=f-\Delta u = f with two fields, the solution uu and its flux q=−∇uq = -\nabla u, both discontinuous polynomials on the cells, plus a third field u^\hat u that lives only on the faces. On each cell the method solves a small problem for (q,u)(q, u) with u^\hat u as boundary data, and the flux through a face is q^⋅n=q⋅n+τ(u−u^)\hat q\cdot n = q\cdot n + \tau(u - \hat u) with a stabilization parameter τ>0\tau > 0. 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 uu and qq converge with the order hk+1h^{k+1}.

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 Ω\Omega, a source ff, Dirichlet data gg, a degree k≥0k \ge 0 and a parameter τ>0\tau > 0. The reference code takes Ω=(0,1)\Omega = (0, 1), −u′′=f-u'' = f, u(0)=g0u(0) = g_0, u(1)=g1u(1) = g_1, and mm cells Kj=(xj,xj+1)K_j = (x_j, x_{j+1}) of width h=1/mh = 1/m.

Output. Polynomials qh,uhq_h, u_h of degree kk on each cell and the traces u^h\hat u_h on the faces (in 1D, one value u^e\hat u_e at each node), with u^h=g\hat u_h = g on the boundary and, on every cell KK and for all polynomials r,wr, w of degree kk,

(qh,r)K−(uh,∇⋅r)K+⟨u^h,r⋅n⟩∂K=0,(q_h, r)_K - (u_h, \nabla\cdot r)_K + \langle\hat u_h, r\cdot n\rangle_{\partial K} = 0,
−(qh,∇w)K+⟨q^h⋅n,w⟩∂K=(f,w)K,q^h⋅n=qh⋅n+τ(uh−u^h),-(q_h, \nabla w)_K + \langle\hat q_h\cdot n, w\rangle_{\partial K} = (f, w)_K, \qquad \hat q_h\cdot n = q_h\cdot n + \tau(u_h - \hat u_h),

and on every interior face the two values of q^h⋅n\hat q_h\cdot n add up to 00.

The algorithm

  1. HDG(f, m, k, tau, g0, g1) ▷ -u'' = f on (0, 1), degree k, m cells, h = 1/m
  2. 1for each cell K_j do
  3. 2solve the local problem for (q, u) with three right sides: uhat_L = 1, uhat_R = 1, and f
  4. 3write the end fluxes qhat n as affine functions of (uhat_j, uhat_(j+1))
  5. 4add minus the end fluxes to rows j and j + 1 of the tridiagonal trace system
  6. 5move the known values uhat_0 = g0 and uhat_m = g1 to the right side
  7. 6uhat <- THOMAS(trace system) ▷ symmetric positive definite
  8. 7for each cell K_j do (q, u) <- uhat_j s_L + uhat_(j+1) s_R + s_f
  9. 8return uhat and (q, u) on every cell

Lines L1 to L4 are static condensation. The local problem on line L2 has 2(k+1)2(k+1) unknowns, and it has one solution for every τ>0\tau > 0. Since the problem is linear in the data, its solution for any traces is the combination u^jsL+u^j+1sR+sf\hat u_j s_L + \hat u_{j+1}s_R + s_f 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 kk, and the global matrix couples the faces of each cell.

Example

Take −u′′=2-u'' = 2 with u(0)=u(1)=0u(0) = u(1) = 0, so u=x(1−x)u = x(1 - x), with m=2m = 2, k=1k = 1, τ=1\tau = 1 and h=12h = \frac12. On each cell q=q0+q1ξq = q_0 + q_1\xi and u=u0+u1ξu = u_0 + u_1\xi with ξ=(x−xj)/h\xi = (x - x_j)/h.

step result
L2, u^L=1\hat u_L = 1 q=2q = 2, u=1−ξu = 1 - \xi
L2, u^R=1\hat u_R = 1 q=−2q = -2, u=ξu = \xi
L2, load f=2f = 2 q=−613+1213ξq = -\frac{6}{13} + \frac{12}{13}\xi, u=126u = \frac1{26}
L3 left flux −2u^L+2u^R+12-2\hat u_L + 2\hat u_R + \frac12, right flux 2u^L−2u^R+122\hat u_L - 2\hat u_R + \frac12
L4, node x=12x = \frac12 row 4u^1−1=04\hat u_1 - 1 = 0 (the two cells give the same numbers)
L5, L6 u^=(0,14,0)\hat u = (0, \frac14, 0)
L7, cell 0 q=−2526+1213ξq = -\frac{25}{26} + \frac{12}{13}\xi, u=126+14ξu = \frac1{26} + \frac14\xi
L7, cell 1 q=126+1213ξq = \frac1{26} + \frac{12}{13}\xi, u=1552−14ξu = \frac{15}{52} - \frac14\xi

The trace u^1=14\hat u_1 = \frac14 is the exact value u(12)u(\frac12). The cell values are not exact, and uh(12−)=1552u_h(\frac12^-) = \frac{15}{52} differs from the trace. With k=0k = 0 and the same data the method gives u^1=15\hat u_1 = \frac15, which is not exact.

Convergence (measurement). For u=sin⁡(πx)u = \sin(\pi x) and τ=1\tau = 1 the reference code gives, at m=4,8,16,32m = 4, 8, 16, 32:

kk L2L^2 errors of uu order L2L^2 errors of qq order
0 0.7290.729, 0.3840.384, 0.1960.196, 0.09910.0991 0.99 0.6040.604, 0.2960.296, 0.1460.146, 0.07250.0725 1.01
1 6.53×10−26.53 \times 10^{-2}, 1.67×10−21.67 \times 10^{-2}, 4.22×10−34.22 \times 10^{-3}, 1.06×10−31.06 \times 10^{-3} 2.00 5.64×10−25.64 \times 10^{-2}, 1.40×10−21.40 \times 10^{-2}, 3.47×10−33.47 \times 10^{-3}, 8.66×10−48.66 \times 10^{-4} 2.01
2 4.03×10−34.03 \times 10^{-3}, 5.13×10−45.13 \times 10^{-4}, 6.46×10−56.46 \times 10^{-5}, 8.09×10−68.09 \times 10^{-6} 3.00 3.66×10−33.66 \times 10^{-3}, 4.56×10−44.56 \times 10^{-4}, 5.68×10−55.68 \times 10^{-5}, 7.09×10−67.09 \times 10^{-6} 3.00
3 3.91×10−43.91 \times 10^{-4}, 2.45×10−52.45 \times 10^{-5}, 1.53×10−61.53 \times 10^{-6}, 9.57×10−89.57 \times 10^{-8} 4.00 2.97×10−42.97 \times 10^{-4}, 1.85×10−51.85 \times 10^{-5}, 1.15×10−61.15 \times 10^{-6}, 7.20×10−87.20 \times 10^{-8} 4.00

The orders are those of the last refinement. For k≥1k \ge 1 the largest nodal trace errors are 6.2×10−76.2 \times 10^{-7}, 9.5×10−99.5 \times 10^{-9}, 1.5×10−101.5 \times 10^{-10} and 2.3×10−122.3 \times 10^{-12}, the same for every kk and τ\tau. 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 r=qr = q and w=uw = u gives ∥q∥K2+τ∑∂Ku2=0\|q\|_K^2 + \tau\sum_{\partial K}u^2 = 0 for zero data, so for τ>0\tau > 0 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

v^TSu^=∑K((qu^,qv^)K+τ∑∂K(uu^−u^)(uv^−v^)),\hat v^{\mathsf T} S\hat u = \sum_K\Bigl((q_{\hat u}, q_{\hat v})_K + \tau\sum_{\partial K}(u_{\hat u} - \hat u)(u_{\hat v} - \hat v)\Bigr),

so the trace matrix SS is symmetric positive definite for every k≥0k \ge 0 and τ>0\tau > 0. In 1D with k≥1k \ge 1, testing the second local equation with 1−ξ1 - \xi and ξ\xi shows that the end fluxes are (f,1−ξ)K+(u^R−u^L)/h(f, 1 - \xi)_K + (\hat u_R - \hat u_L)/h at the left end and (f,ξ)K−(u^R−u^L)/h(f, \xi)_K - (\hat u_R - \hat u_L)/h at the right end. So the trace system is exactly the system of linear finite elements, 1h(2u^e−u^e−1−u^e+1)=(f,ϕe)\frac1h(2\hat u_e - \hat u_{e-1} - \hat u_{e+1}) = (f, \phi_e), for every τ\tau and kk, and since linear elements are exact at the nodes in 1D, the traces are the exact values u(xe)u(x_e). If uu is a polynomial of degree at most kk, the method returns uu and q=−u′q = -u' 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 −u′′=f-u'' = f on (0,1)(0, 1) with u(0)=g0u(0) = g_0 and u(1)=g1u(1) = g_1, written as q+u′=0q + u' = 0 and q′=fq' = f. The mesh has the nodes xe=ehx_e = eh, e=0,…,me = 0, \ldots, m, h=1/mh = 1/m, and the cells Kj=(xj,xj+1)K_j = (x_j, x_{j+1}). On each cell qq and uu are polynomials of degree at most k≥0k \ge 0, and there is one trace value u^e\hat u_e at each node. On the boundary of a cell the outward normal is n=−1n = -1 at the left end and n=+1n = +1 at the right end, and ∑∂Kz\sum_{\partial K} z means z(xj)+z(xj+1)z(x_j) + z(x_{j+1}), with nn taken at the end where zz is evaluated. The numerical flux is q^n=qn+τ(u−u^)\hat q n = qn + \tau(u - \hat u) with a constant τ>0\tau > 0. The local problem on KK is: given u^\hat u at the two ends of KK, find (q,u)∈Pk(K)2(q, u) \in \mathcal{P}_k(K)^2 with

(q,r)K−(u,r′)K+∑∂Ku^ r n=0for all r∈Pk(K),(1)(q, r)_K - (u, r')_K + \textstyle\sum_{\partial K} \hat u\, r\, n = 0 \quad \text{for all } r \in \mathcal{P}_k(K), \tag{1}
−(q,w′)K+∑∂Kq^n w=(f,w)Kfor all w∈Pk(K).(2)-(q, w')_K + \textstyle\sum_{\partial K} \hat q n\, w = (f, w)_K \quad \text{for all } w \in \mathcal{P}_k(K). \tag{2}

The global equation at an interior node xex_e is that the two values of q^n\hat q n at xex_e, one from Ke−1K_{e-1} and one from KeK_e, add up to 00. The code writes it as the row Ge(u^)=−(q^n∣Ke−1+q^n∣Ke)=0G_e(\hat u) = -(\hat q n|_{K_{e-1}} + \hat q n|_{K_e}) = 0, and it fixes u^0=g0\hat u_0 = g_0 and u^m=g1\hat u_m = g_1.

Claim 1 (local well-posedness). For every k≥0k \ge 0 and τ>0\tau > 0 the local problem has exactly one solution for any data u^\hat u and ff.

Proof. The problem is a square linear system, so it is enough to show that u^=0\hat u = 0 and f=0f = 0 give only q=u=0q = u = 0. Take r=qr = q in (1) and w=uw = u in (2):

∥q∥K2−(u,q′)K=0,−(q,u′)K+∑∂K(qn+τu)u=0.\|q\|_K^2 - (u, q')_K = 0, \qquad -(q, u')_K + \textstyle\sum_{\partial K}(qn + \tau u)u = 0.

Integration by parts gives −(q,u′)K=(q′,u)K−∑∂Kqun-(q, u')_K = (q', u)_K - \sum_{\partial K} q u n, so the second equation is (q′,u)K+τ∑∂Ku2=0(q', u)_K + \tau\sum_{\partial K} u^2 = 0. The sum of the two equations is ∥q∥K2+τ∑∂Ku2=0\|q\|_K^2 + \tau\sum_{\partial K} u^2 = 0. So q=0q = 0 and u=0u = 0 at both ends. Then (1) reads (u,r′)K=0(u, r')_K = 0 for all r∈Pkr \in \mathcal{P}_k, that is, uu is orthogonal to Pk−1\mathcal{P}_{k-1}. If k=0k = 0, uu is a constant that is 00 at an end, so u=0u = 0. If k≥1k \ge 1, u=cLku = cL_k where LkL_k is the Legendre polynomial of degree kk moved to KK, and Lk=±1L_k = \pm 1 at the ends, so c=0c = 0. □\square

Claim 2 (what the code computes). Lines L1 to L4 build the rows GeG_e 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 ξs\xi^s, ξ=(x−xj)/h\xi = (x - x_j)/h, the entries of the local matrix are (ξs,ξi)K=h/(i+s+1)(\xi^s, \xi^i)_K = h/(i + s + 1) and (ξs,(ξi)′)K=i/(i+s)(\xi^s, (\xi^i)')_K = i/(i + s) for i≥1i \ge 1, and ξi=1\xi^i = 1 at the right end and [i=0][i = 0] at the left end. These are the entries that local_matrix writes, with the qnqn and τu\tau u parts of q^n\hat q n on the left side and the u^\hat u parts on the right side, as local_rhs writes them. By Claim 1 the matrix is nonsingular, and since the problem is linear in (u^L,u^R,f)(\hat u_L, \hat u_R, f), the local solution is u^LsL+u^RsR+sf\hat u_L s_L + \hat u_R s_R + s_f with the three columns that line L2 computes. So at each end q^n\hat q n is affine in (u^L,u^R)(\hat u_L, \hat u_R) with the coefficients of line L3, in which −τ-\tau is the −τu^-\tau\hat u part of the flux. Line L4 adds −q^n-\hat q n of the right end of KjK_j to row j+1j + 1 and −q^n-\hat q n of its left end to row jj, so row ee is GeG_e, in the tridiagonal arrays because q^n\hat q n on KjK_j depends only on u^j\hat u_j and u^j+1\hat u_{j+1}. 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. □\square

Claim 3 (the trace system is symmetric positive definite). Let f=0f = 0 and let u^\hat u, v^\hat v be trace vectors that are 00 at x0x_0 and xmx_m. Write (qu^,uu^)(q_{\hat u}, u_{\hat u}) for the local solutions with traces u^\hat u. Then

∑e=1m−1v^eGe(u^)=∑j((qu^,qv^)Kj+τ∑∂Kj(uu^−u^)(uv^−v^)).\sum_{e=1}^{m-1}\hat v_e G_e(\hat u) = \sum_j\Bigl((q_{\hat u}, q_{\hat v})_{K_j} + \tau\textstyle\sum_{\partial K_j}(u_{\hat u} - \hat u)(u_{\hat v} - \hat v)\Bigr).

So the matrix SS of the rows G1,…,Gm−1G_1, \ldots, G_{m-1} is symmetric, and it is positive definite for all k≥0k \ge 0 and τ>0\tau > 0.

Proof. Since v^=0\hat v = 0 at the boundary nodes, the left side is −∑j∑∂Kjq^n(u^) v^-\sum_j\sum_{\partial K_j}\hat q n(\hat u)\,\hat v. Fix a cell KK. Test (1) for v^\hat v with r=qu^r = q_{\hat u}: (qv^,qu^)K−(uv^,qu^′)K+∑∂Kv^qu^n=0(q_{\hat v}, q_{\hat u})_K - (u_{\hat v}, q_{\hat u}')_K + \sum_{\partial K}\hat v q_{\hat u} n = 0. Test (2) for u^\hat u with w=uv^w = u_{\hat v} and integrate by parts as in Claim 1: (qu^′,uv^)K+τ∑∂K(uu^−u^)uv^=0(q_{\hat u}', u_{\hat v})_K + \tau\sum_{\partial K}(u_{\hat u} - \hat u)u_{\hat v} = 0. Eliminating (qu^′,uv^)K(q_{\hat u}', u_{\hat v})_K gives

−∑∂Kqu^n v^=(qu^,qv^)K+τ∑∂K(uu^−u^)uv^.-\textstyle\sum_{\partial K} q_{\hat u} n\,\hat v = (q_{\hat u}, q_{\hat v})_K + \tau\sum_{\partial K}(u_{\hat u} - \hat u)u_{\hat v}.

Now −q^n(u^)v^=−qu^nv^−τ(uu^−u^)v^-\hat q n(\hat u)\hat v = -q_{\hat u}n\hat v - \tau(u_{\hat u} - \hat u)\hat v, and the sum over the two ends gives the cell term of the identity. The right side is symmetric in u^\hat u and v^\hat v, so SS is symmetric. With v^=u^\hat v = \hat u it is ∑j(∥qu^∥Kj2+τ∑∂Kj(uu^−u^)2)≥0\sum_j\bigl(\|q_{\hat u}\|_{K_j}^2 + \tau\sum_{\partial K_j}(u_{\hat u} - \hat u)^2\bigr) \ge 0. If it is 00, then qu^=0q_{\hat u} = 0 on every cell, and (1) with r=1r = 1 gives (qu^,1)K+u^R−u^L=0(q_{\hat u}, 1)_K + \hat u_R - \hat u_L = 0, so u^R=u^L\hat u_R = \hat u_L on every cell. Then u^\hat u is constant, and u^0=0\hat u_0 = 0 makes it 00. □\square

Claim 4 (end fluxes for k≥1k \ge 1). If k≥1k \ge 1, the end fluxes of the local solution on KjK_j are

q^n∣xj=(f,ψL)Kj−u^j−u^j+1h,q^n∣xj+1=(f,ψR)Kj−u^j+1−u^jh,\hat q n\big|_{x_j} = (f, \psi_L)_{K_j} - \frac{\hat u_j - \hat u_{j+1}}{h}, \qquad \hat q n\big|_{x_{j+1}} = (f, \psi_R)_{K_j} - \frac{\hat u_{j+1} - \hat u_j}{h},

with ψL=1−ξ\psi_L = 1 - \xi and ψR=ξ\psi_R = \xi, for every τ>0\tau > 0.

Proof. Equation (1) with r=1r = 1 gives (q,1)K=u^L−u^R(q, 1)_K = \hat u_L - \hat u_R. Since k≥1k \ge 1, ψR∈Pk\psi_R \in \mathcal{P}_k is allowed in (2). It is 00 at the left end, 11 at the right end, and ψR′=1/h\psi_R' = 1/h, so (2) gives −(q,1)K/h+q^n∣R=(f,ψR)K-(q, 1)_K/h + \hat q n|_R = (f, \psi_R)_K, which is the second formula. In the same way ψL\psi_L is 11 at the left end, 00 at the right end, and ψL′=−1/h\psi_L' = -1/h, which gives (q,1)K/h+q^n∣L=(f,ψL)K(q, 1)_K/h + \hat q n|_L = (f, \psi_L)_K, the first formula. □\square

Claim 5 (the trace system is the linear finite element system). If k≥1k \ge 1, the row at an interior node is

Ge(u^)=2u^e−u^e−1−u^e+1h−(f,ϕe),G_e(\hat u) = \frac{2\hat u_e - \hat u_{e-1} - \hat u_{e+1}}{h} - (f, \phi_e),

where ϕe\phi_e is the piecewise linear hat function of node xex_e. So S=1htridiag⁡(−1,2,−1)S = \frac1h\operatorname{tridiag}(-1, 2, -1), independent of kk and τ\tau.

Proof. Add the right-end flux of Ke−1K_{e-1} and the left-end flux of KeK_e from Claim 4 and change the sign. The functions ψR\psi_R on Ke−1K_{e-1} and ψL\psi_L on KeK_e are the two halves of ϕe\phi_e. □\square

Claim 6 (exact traces for k≥1k \ge 1). If k≥1k \ge 1 and u∈H2(0,1)u \in H^2(0, 1) is the exact solution, then u^e=u(xe)\hat u_e = u(x_e) for every ee, when the loads (f,ξi)K(f, \xi^i)_K are integrated exactly.

Proof. For an interior node, ϕe∈H01(0,1)\phi_e \in H^1_0(0, 1), so the weak form gives (u′,ϕe′)=(f,ϕe)(u', \phi_e') = (f, \phi_e). On Ke−1K_{e-1}, ϕe′=1/h\phi_e' = 1/h, and on KeK_e, ϕe′=−1/h\phi_e' = -1/h, so (u′,ϕe′)=1h(u(xe)−u(xe−1))−1h(u(xe+1)−u(xe))(u', \phi_e') = \frac1h\bigl(u(x_e) - u(x_{e-1})\bigr) - \frac1h\bigl(u(x_{e+1}) - u(x_e)\bigr). By Claim 5 the nodal values of uu satisfy every row Ge=0G_e = 0, and they take the boundary values g0g_0 and g1g_1. By Claim 3 the system has only one solution. □\square

The code integrates the loads with the five-point Boole rule, which is exact for polynomials of degree at most 55. The traces depend on ff only through (f,ϕe)(f, \phi_e), so they are exact when ff is a polynomial of degree at most 44. For other ff the traces are the nodal values of the piecewise linear solution with the quadrature load.

Claim 7 (polynomial reproduction). If the exact solution uu is a polynomial of degree at most kk and the loads are exact, then the method returns q=−u′q = -u', uu on every cell and u^e=u(xe)\hat u_e = u(x_e).

Proof. Take q=−u′q = -u' and u^=u\hat u = u at the nodes. Integration by parts gives (1), because (q,r)K=(u,r′)K−∑∂Kurn(q, r)_K = (u, r')_K - \sum_{\partial K} u r n and u^=u\hat u = u at the ends, and it gives (2), because u=u^u = \hat u at the ends makes q^n=qn\hat q n = qn and −(q,w′)K+∑∂Kqnw=(q′,w)K=(f,w)K-(q, w')_K + \sum_{\partial K} q n w = (q', w)_K = (f, w)_K. The global equations hold because qq is continuous at every node, so the two values of q^n=qn\hat q n = qn have opposite signs. By Claim 3 the traces are unique, and by Claim 1 so are the local solutions. □\square

Conclusion. By Claim 2 the code assembles the HDG trace equations, and by Claim 3 their matrix is symmetric positive definite for every k≥0k \ge 0 and τ>0\tau > 0. 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 k≥1k \ge 1 the traces are the exact nodal values (Claim 6), and polynomials of degree at most kk are reproduced exactly (Claim 7). ■\blacksquare

Complexity

Line L2 solves a dense system of size 2(k+1)2(k+1) with three right sides, which costs Θ(k3)\Theta(k^3) per cell. Line L3 costs Θ(k)\Theta(k) and line L4 costs O(1)O(1), so the loop takes Θ(mk3)\Theta(mk^3) time. Line L6 costs Θ(m)\Theta(m) and line L7 costs Θ(mk)\Theta(mk). The code keeps three columns of length 2(k+1)2(k+1) for each cell and one local matrix, which is Θ(mk+k2)\Theta(mk + k^2) memory. Discontinuous Galerkin methods such as SIPG couple all m(k+1)m(k+1) cell unknowns. HDG couples only the m−1m - 1 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 k≥0k \ge 0 and τ>0\tau > 0, by the energy identity above.
  • Order hk+1h^{k+1} for uu and qq (theorem). With τ\tau of order one, the projection-based analysis of Cockburn, Gopalakrishnan and Sayas gives hk+1h^{k+1} for both fields. Mixed methods also have this property, but most DG methods give the flux only with order hkh^k.
  • Exact traces in 1D (theorem). For k≥1k \ge 1 the trace system does not depend on τ\tau or kk and equals the linear element system, so the traces are exact at the nodes when the load is integrated exactly. For k=0k = 0 this is false: with u=x4−xu = x^4 - x and m=4m = 4 the trace errors are 511280\frac{51}{1280}, 340\frac{3}{40} and 991280\frac{99}{1280}. In several dimensions the traces are not exact, but they superconverge.
  • Effect of τ\tau (measurement). With τ=10\tau = 10 in place of 11 the uu errors in the table become smaller and the qq errors larger, and for k≥1k \ge 1 the observed orders of qq approach k+1k + 1 more slowly: 1.941.94, 2.962.96 and 3.983.98 at the last refinement. For k=0k = 0 and τ=10\tau = 10 the order of uu is only 0.820.82 at m=32m = 32.
  • Local conservation. Taking w=1w = 1 in the second local equation gives ⟨q^h⋅n,1⟩∂K=(f,1)K\langle\hat q_h\cdot n, 1\rangle_{\partial K} = (f, 1)_K on every cell, with a single-valued flux.
  • Local postprocessing. Because qhq_h has order hk+1h^{k+1}, a new local problem on each cell gives an approximation uh∗u_h^* of degree k+1k + 1 with order hk+2h^{k+2} for k≥1k \ge 1 in several dimensions.

Variants and improvements

  • Choice of τ\tau. A constant τ\tau of order one is common. A τ\tau that is positive on only one face of each cell gives another member of the family, and the limit τ→∞\tau \to \infty approaches a continuous Galerkin method. For convection-diffusion, τ\tau includes an upwind part.
  • Hybridized mixed methods. With Raviart-Thomas spaces for qq 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 k+1k + 1 for uu and degree kk for the traces, with a τ\tau of order 1/h1/h, 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

  • τ=0\tau = 0 without a mixed space. With equal-degree polynomials for qq and uu, the local problem of line L2 is singular for τ=0\tau = 0. The energy argument then gives only q=0q = 0, and u=cLku = cL_k, with LkL_k the Legendre polynomial of degree kk on the cell, solves the local problem with zero data. Keep τ>0\tau > 0.
  • Wrong sign of the normal. The flux in line L3 uses n=−1n = -1 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 −τu^-\tau\hat u part of the flux. The flux of line L3 contains τ(u−u^)\tau(u - \hat u). If the −τu^-\tau\hat u term is dropped, the trace system is no longer the balance of the true fluxes, and the method is not consistent.
  • Comparing uhu_h with the trace. At a node uhu_h from the left, uhu_h from the right and u^h\hat u_h are three different numbers. Use the trace for nodal values.
  • Postprocessing with k=0k = 0. The flux has only order hh for k=0k = 0, 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.

hybridizable_discontinuous_galerkin.pyI0RawGitHub
# 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 q⋅n+τ(u−u^)q\cdot n + \tau(u - \hat u), and in 2010 Cockburn, Gopalakrishnan and Sayas proved the order hk+1h^{k+1} for both fields with a projection designed for the method.

References

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

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • 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