Algorithm Search⌘K

Algorithmcore

Streamline upwind Petrov-Galerkin method

Also called SUPG.

Adds test functions shifted along the flow direction, which stabilizes convection-dominated problems without losing consistency.

Time
Θ(m) worst
Space
Θ(m) extra
Where
m = the number of cells of the one-dimensional mesh
Properties
consistentdeterministicnodally exact in 1d with optimal taunot symmetric matrix
Origin
Alexander N. Brooks, Thomas J. R. Hughes, 1982

The streamline upwind Petrov-Galerkin method (SUPG) solves convection-diffusion problems such as −εΔu+a⋅∇u=f-\varepsilon\Delta u + a\cdot\nabla u = f with continuous finite elements when the convection aa is much stronger than the diffusion ε\varepsilon. On each cell it tests the equation with v+τ a⋅∇vv + \tau\,a\cdot\nabla v in place of vv, which adds diffusion only along the streamlines, and because the added term multiplies the residual of the equation, the exact solution still satisfies the discrete equations. On coarse meshes the plain Galerkin method gives node-to-node oscillations, and SUPG removes most of them while it keeps the order of accuracy that plain upwinding loses.

In plain words

Smoke carried by a strong wind spreads only a little. A computer model that treats upwind and downwind points the same way can produce a pattern of high and low values that alternate along the wind, which is not in the real flow. The old fix is to look only upwind, but that smears the smoke as if the air were thick. SUPG gives each test point a small lean into the wind. The lean is large where the wind is strong compared to the spreading and almost zero where it is weak. Because the lean is applied to how badly the equation fails, and not to the solution itself, a correct answer still passes the test. So the method stays accurate where the solution is smooth and stays calm near steep fronts.

The problem

Input. A domain Ω\Omega, a diffusion coefficient ε>0\varepsilon > 0, a velocity field aa, a source ff, boundary values gg, and a mesh Th\mathcal{T}_h with a continuous finite element space VhV_h of degree kk. The reference code takes Ω=(0,1)\Omega = (0, 1), constant ε\varepsilon and a≠0a \ne 0, mm cells of width h=1/mh = 1/m, P1 elements, and u(0)=g0u(0) = g_0, u(1)=g1u(1) = g_1.

Output. uh∈Vhu_h \in V_h with the boundary values and

ε(∇uh,∇v)+(a⋅∇uh,v)+∑KτK(−εΔuh+a⋅∇uh−f, a⋅∇v)K=(f,v)\varepsilon(\nabla u_h, \nabla v) + (a\cdot\nabla u_h, v) + \sum_{K}\tau_K\bigl(-\varepsilon\Delta u_h + a\cdot\nabla u_h - f,\ a\cdot\nabla v\bigr)_K = (f, v)

for all v∈Vhv \in V_h that vanish on the boundary. The cell Péclet number is PeK=∣a∣hK/(2ε)\mathrm{Pe}_K = |a|h_K/(2\varepsilon). Some sources omit the factor 2 and write ∣a∣hK/ε|a|h_K/\varepsilon. The problem is convection dominated when PeK>1\mathrm{Pe}_K > 1.

The algorithm

The standard parameter is

τK=hK2∣a∣(coth⁡PeK−1PeK).\tau_K = \frac{h_K}{2|a|}\Bigl(\coth\mathrm{Pe}_K - \frac{1}{\mathrm{Pe}_K}\Bigr).

In one dimension with P1 elements and constant data this choice is proved to give the exact solution at the nodes (Claim 4 of the proof). In several dimensions and for higher degree it is a heuristic choice, and other formulas such as τK=min⁡(hK/(2∣a∣), hK2/(12ε))\tau_K = \min\bigl(h_K/(2|a|),\ h_K^2/(12\varepsilon)\bigr) behave about the same. The steps for the one-dimensional P1 case are:

  1. SUPG(eps, a, f, m, g0, g1) ▷ -eps u'' + a u' = f on (0, 1), P1 on m cells
  2. 1h <- 1/m; Pe <- |a| h / (2 eps)
  3. 2tau <- (h / (2 |a|)) (coth(Pe) - 1/Pe) ▷ use a series when Pe is small
  4. 3for j <- 0 to m - 1 do ▷ cell [x_j, x_{j+1}] with local hats phi_0, phi_1
  5. 4A_K[r, s] <- (eps + tau a^2) (phi_s', phi_r')_K + a (phi_s', phi_r)_K for r, s in {0, 1}
  6. 5b_K[r] <- (f, phi_r + tau a phi_r')_K by quadrature
  7. 6add A_K into rows and columns j, j + 1 of the tridiagonal arrays, and b_K into the right side
  8. 7move the known values U_0 = g0 and U_m = g1 to the right side of rows 1 and m - 1
  9. 8(U_1, ..., U_{m-1}) <- THOMAS(sub, diag, super, rhs) on rows 1 to m - 1
  10. 9return (g0, U_1, ..., U_{m-1}, g1)

Line L4 uses the fact that a P1 function has uh′′=0u_h'' = 0 inside a cell, so the SUPG term τ(−εuh′′+auh′−f,av′)\tau(-\varepsilon u_h'' + a u_h' - f, a v') becomes τa2(uh′,v′)\tau a^2(u_h', v') on the matrix side and τ(f,av′)\tau(f, a v') on the load side. In 1D with P1 elements, SUPG therefore equals the Galerkin method with the diffusion ε+τa2\varepsilon + \tau a^2 and a corrected load. Lines L6 to L8 are the assembly loop and the Thomas algorithm, because the matrix is tridiagonal. For elements of degree 2 or more, line L4 must keep the term −εΔuh-\varepsilon\Delta u_h, since it is not zero inside the cell.

Example

Take ε=0.01\varepsilon = 0.01, a=1a = 1, f=0f = 0, u(0)=0u(0) = 0, u(1)=1u(1) = 1 and m=10m = 10, so h=0.1h = 0.1 and Pe=5\mathrm{Pe} = 5. The exact solution u=(e100x−1)/(e100−1)u = (e^{100x} - 1)/(e^{100} - 1) is almost 00 up to a boundary layer of width about 0.010.01 at x=1x = 1.

For the Galerkin method (τ=0\tau = 0), each interior row reads −0.6 Ui−1+0.2 Ui+0.4 Ui+1=0-0.6\,U_{i-1} + 0.2\,U_i + 0.4\,U_{i+1} = 0. The characteristic equation 0.4ρ2+0.2ρ−0.6=00.4\rho^2 + 0.2\rho - 0.6 = 0 has the roots ρ=1\rho = 1 and ρ=−3/2\rho = -3/2. In general the second root is (1+Pe)/(1−Pe)(1 + \mathrm{Pe})/(1 - \mathrm{Pe}), which is negative exactly when Pe>1\mathrm{Pe} > 1. So Ui=C((−3/2)i−1)U_i = C\bigl((-3/2)^i - 1\bigr) with C=1/((3/2)10−1)=0.017648C = 1/\bigl((3/2)^{10} - 1\bigr) = 0.017648, and the sign alternates from node to node.

For SUPG, line L2 gives τ=0.05 (coth⁡5−0.2)=0.0400045\tau = 0.05\,(\coth 5 - 0.2) = 0.0400045, so the diffusion in line L4 is ε+τ=0.05coth⁡5=0.0500454\varepsilon + \tau = 0.05\coth 5 = 0.0500454. The second root becomes (1+tanh⁡5)/(1−tanh⁡5)=e10(1 + \tanh 5)/(1 - \tanh 5) = e^{10}, which is the ratio eah/εe^{ah/\varepsilon} of the exact solution from one node to the next.

xx 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9
Galerkin -0.0441 0.0221 -0.0772 0.0717 -0.1517 0.1834 -0.3192 0.4346 -0.6961
SUPG 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000454
exact 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000454

With f=1f = 1 and u(0)=u(1)=0u(0) = u(1) = 0 on the same mesh, the Galerkin values at x=0.1,…,0.9x = 0.1, \ldots, 0.9 are 0.14410.1441, 0.17790.1779, 0.37720.3772, 0.32830.3283, 0.65170.6517, 0.41660.4166, 1.01921.0192, 0.36540.3654, 1.59611.5961, while the exact solution is close to xx there. SUPG reproduces the exact nodal values up to rounding (a difference of 2.2×10−162.2 \times 10^{-16}).

Smooth data (measurement). For u=sin⁡(πx)u = \sin(\pi x) with a=1a = 1, the maximum nodal error of SUPG at m=8,16,32,64m = 8, 16, 32, 64 is 2.75×10−62.75 \times 10^{-6}, 1.72×10−71.72 \times 10^{-7}, 1.08×10−81.08 \times 10^{-8}, 6.74×10−106.74 \times 10^{-10} for ε=1\varepsilon = 1, an observed order of 4.0. The Galerkin errors are 9.69×10−49.69 \times 10^{-4}, 2.44×10−42.44 \times 10^{-4}, 6.10×10−56.10 \times 10^{-5}, 1.52×10−51.52 \times 10^{-5}, order 2. For ε=0.01\varepsilon = 0.01 the SUPG errors are 6.01×10−36.01 \times 10^{-3}, 9.90×10−49.90 \times 10^{-4}, 1.01×10−41.01 \times 10^{-4}, 7.44×10−67.44 \times 10^{-6}, with observed orders 2.6, 3.3 and 3.8 before the asymptotic range.

Correctness

The full proof is in the correctness proof. It shows four facts. First, the method is consistent: the exact solution makes the residual zero on every cell, so it satisfies the SUPG equations, and the error is orthogonal to VhV_h in the SUPG form. Second, for P1 elements the SUPG matrix is the Galerkin matrix with diffusion ε′=ε+τa2\varepsilon' = \varepsilon + \tau a^2. Third, the form is coercive with B(z,z)=ε′∥z′∥2B(z, z) = \varepsilon'\|z'\|^2 on functions that vanish at the ends, so the solution exists and is unique, and when ε′≥∣a∣h/2\varepsilon' \ge |a|h/2 the matrix is diagonally dominant and the Thomas algorithm meets no zero pivot. Fourth, with the τ\tau of line L2, ε′=∣a∣h2coth⁡Pe\varepsilon' = \frac{|a|h}{2}\coth\mathrm{Pe}, and the discrete equations hold exactly for 11, xx and eax/εe^{ax/\varepsilon}, so the nodal values are exact for a constant ff.

Proof: SUPG is consistent, has a unique solution, and with the optimal tau is exact at the nodes in one dimensionfull

Setting. The problem is −εu′′+au′=f-\varepsilon u'' + a u' = f on (0,1)(0, 1) with u(0)=g0u(0) = g_0 and u(1)=g1u(1) = g_1, where ε>0\varepsilon > 0 and a≠0a \ne 0 are constants. The mesh has the nodes xj=jhx_j = jh, h=1/mh = 1/m, m≥2m \ge 2, and VhV_h is the space of continuous piecewise linear functions. Vh,0V_{h,0} is the subspace of functions that vanish at 00 and 11. For τ≥0\tau \ge 0, the SUPG problem is: find uh∈Vhu_h \in V_h with uh(0)=g0u_h(0) = g_0, uh(1)=g1u_h(1) = g_1 and

B(uh,v)=L(v)for all v∈Vh,0,B(u_h, v) = L(v) \quad\text{for all } v \in V_{h,0},
B(w,v)=ε(w′,v′)+(aw′,v)+τ∑K(−εw′′+aw′, av′)K,L(v)=(f,v)+τ∑K(f,av′)K,B(w, v) = \varepsilon(w', v') + (a w', v) + \tau\sum_K (-\varepsilon w'' + a w',\ a v')_K, \qquad L(v) = (f, v) + \tau\sum_K (f, a v')_K,

where (⋅,⋅)K(\cdot,\cdot)_K is the L2L^2 product on the cell KK and (⋅,⋅)(\cdot,\cdot) is the product on (0,1)(0, 1). Lines L3 to L6 of the algorithm compute the matrix of BB and the vector of LL in the hat basis, cell by cell. The proof of finite element assembly shows that this gives B(ϕs,ϕr)B(\phi_s, \phi_r) and L(ϕr)L(\phi_r) when the quadrature of line L5 is exact, and Boole's rule is exact when ff is a polynomial of degree at most 4. Line L7 fixes the two boundary values, so lines L8 and L9 return the solution of the SUPG problem if it exists. We prove four claims.

Claim 1 (consistency). If the exact solution uu is in H2(0,1)H^2(0, 1), then B(u,v)=L(v)B(u, v) = L(v) for all v∈Vh,0v \in V_{h,0}, so B(u−uh,v)=0B(u - u_h, v) = 0.

Proof. Integration by parts on (0,1)(0, 1), with v(0)=v(1)=0v(0) = v(1) = 0, gives ε(u′,v′)=(−εu′′,v)\varepsilon(u', v') = (-\varepsilon u'', v). So ε(u′,v′)+(au′,v)=(−εu′′+au′,v)=(f,v)\varepsilon(u', v') + (a u', v) = (-\varepsilon u'' + a u', v) = (f, v). On each cell −εu′′+au′−f=0-\varepsilon u'' + a u' - f = 0, so τ∑K(−εu′′+au′−f,av′)K=0\tau\sum_K(-\varepsilon u'' + a u' - f, a v')_K = 0. Adding the two identities gives B(u,v)=L(v)B(u, v) = L(v). Subtract B(uh,v)=L(v)B(u_h, v) = L(v). □\square

Claim 2 (the extra diffusion). For w,v∈Vhw, v \in V_h, B(w,v)=(ε+τa2)(w′,v′)+(aw′,v)B(w, v) = (\varepsilon + \tau a^2)(w', v') + (a w', v). For a constant f=cf = c and an interior hat function ϕi\phi_i, 1≤i≤m−11 \le i \le m - 1, L(ϕi)=(c,ϕi)=chL(\phi_i) = (c, \phi_i) = ch.

Proof. On each cell ww is linear, so w′′=0w'' = 0 there and (−εw′′+aw′,av′)K=a2(w′,v′)K(-\varepsilon w'' + a w', a v')_K = a^2(w', v')_K. Summing over KK gives the first identity. For the second, τ∑K(c,aϕi′)K=τac∫01ϕi′ dx=τac (ϕi(1)−ϕi(0))=0\tau\sum_K(c, a\phi_i')_K = \tau a c\int_0^1\phi_i'\,dx = \tau a c\,(\phi_i(1) - \phi_i(0)) = 0, and (c,ϕi)=ch(c, \phi_i) = ch because the hat function has area hh. □\square

Claim 3 (unique solution). For every τ≥0\tau \ge 0 the SUPG problem has exactly one solution. If ε′=ε+τa2\varepsilon' = \varepsilon + \tau a^2 satisfies ε′≥∣a∣h/2\varepsilon' \ge |a|h/2, the Thomas algorithm of line L8 meets no zero pivot.

Proof. Write uh=wg+zu_h = w_g + z with wg∈Vhw_g \in V_h the function with nodal values (g0,0,…,0,g1)(g_0, 0, \ldots, 0, g_1) and z∈Vh,0z \in V_{h,0}. The problem becomes B(z,v)=L(v)−B(wg,v)B(z, v) = L(v) - B(w_g, v) for all v∈Vh,0v \in V_{h,0}, a square linear system of size m−1m - 1. It has a unique solution if B(z,z)=0B(z, z) = 0 implies z=0z = 0 on Vh,0V_{h,0}. By Claim 2, B(z,z)=ε′∥z′∥2+a∫01z′z dx=ε′∥z′∥2+a2(z(1)2−z(0)2)=ε′∥z′∥2B(z, z) = \varepsilon'\|z'\|^2 + a\int_0^1 z' z\,dx = \varepsilon'\|z'\|^2 + \tfrac{a}{2}(z(1)^2 - z(0)^2) = \varepsilon'\|z'\|^2. If this is 00, then z′=0z' = 0, so zz is constant, and z(0)=0z(0) = 0 gives z=0z = 0.

For the pivots: by Claim 2, row ii of the inner system (1≤i≤m−11 \le i \le m - 1) has the entries

ℓ=−ε′h−a2,d=2ε′h,μ=−ε′h+a2\ell = -\frac{\varepsilon'}{h} - \frac{a}{2}, \qquad d = \frac{2\varepsilon'}{h}, \qquad \mu = -\frac{\varepsilon'}{h} + \frac{a}{2}

for Ui−1U_{i-1}, UiU_i and Ui+1U_{i+1}, except that line L7 removes ℓ\ell from the first row and μ\mu from the last. If ε′≥∣a∣h/2\varepsilon' \ge |a|h/2, both ℓ\ell and μ\mu are ≤0\le 0, so ∣ℓ∣+∣μ∣=2ε′/h=d>0|\ell| + |\mu| = 2\varepsilon'/h = d > 0. The Thomas algorithm uses the pivots p1=dp_1 = d and pi=d−ℓci−1′p_i = d - \ell c'_{i-1} for i≥2i \ge 2, with ci′=μ/pic'_i = \mu/p_i.

  • If ε′>∣a∣h/2\varepsilon' > |a|h/2, then ℓ<0\ell < 0 and μ<0\mu < 0. We show by induction that pi>∣μ∣p_i > |\mu|, so pi>0p_i > 0 and ∣ci′∣<1|c'_i| < 1. For i=1i = 1, p1=d=∣ℓ∣+∣μ∣>∣μ∣p_1 = d = |\ell| + |\mu| > |\mu|. For the step, the hypothesis ∣ci−1′∣<1|c'_{i-1}| < 1 and ℓ≠0\ell \ne 0 give pi≥d−∣ℓ∣ ∣ci−1′∣>d−∣ℓ∣=∣μ∣p_i \ge d - |\ell|\,|c'_{i-1}| > d - |\ell| = |\mu|.
  • If ε′=∣a∣h/2\varepsilon' = |a|h/2, one of ℓ\ell and μ\mu is 00, so the matrix is bidiagonal. If μ=0\mu = 0, every ci′c'_i is 00 and every pivot is dd. If ℓ=0\ell = 0, again every pivot is d−0=dd - 0 = d.

In both cases no pivot is zero. □\square

Claim 4 (nodal exactness). Let Pe=∣a∣h/(2ε)\mathrm{Pe} = |a|h/(2\varepsilon) and τ=h2∣a∣(coth⁡Pe−1Pe)\tau = \frac{h}{2|a|}\bigl(\coth\mathrm{Pe} - \frac{1}{\mathrm{Pe}}\bigr), the value of line L2. If f=cf = c is constant, then Uj=u(xj)U_j = u(x_j) for j=0,…,mj = 0, \ldots, m, where uu is the exact solution.

Proof. First, ε′=ε+τa2=ε+∣a∣h2coth⁡Pe−∣a∣h2Pe=∣a∣h2coth⁡Pe\varepsilon' = \varepsilon + \tau a^2 = \varepsilon + \frac{|a|h}{2}\coth\mathrm{Pe} - \frac{|a|h}{2\mathrm{Pe}} = \frac{|a|h}{2}\coth\mathrm{Pe}, because ∣a∣h2Pe=ε\frac{|a|h}{2\mathrm{Pe}} = \varepsilon. Since coth⁡\coth is odd, this is also ah2coth⁡ah2ε\frac{ah}{2}\coth\frac{ah}{2\varepsilon}, and ε′>∣a∣h/2\varepsilon' > |a|h/2 because coth⁡x>1\coth x > 1 for x>0x > 0.

By Claim 2 and the entries in the proof of Claim 3, row ii of the system, divided by hh, reads

Ri(U)=−ε′ Ui+1−2Ui+Ui−1h2+a Ui+1−Ui−12h=c,1≤i≤m−1.R_i(U) = -\varepsilon'\,\frac{U_{i+1} - 2U_i + U_{i-1}}{h^2} + a\,\frac{U_{i+1} - U_{i-1}}{2h} = c, \qquad 1 \le i \le m - 1.

The exact solution is u(x)=A+Bx+Cerxu(x) = A + Bx + Ce^{rx} with r=a/εr = a/\varepsilon, B=c/aB = c/a, and AA, CC fixed by the boundary values. RiR_i is linear, so we check each term on the nodal values Uj=u(xj)U_j = u(x_j):

  1. For Uj=1U_j = 1: Ri=0R_i = 0.
  2. For Uj=xjU_j = x_j: the second difference is 00 and the centered difference is 11, so Ri=aR_i = a. Times B=c/aB = c/a this gives cc.
  3. For Uj=erxjU_j = e^{rx_j}: write Ui±1=Uie±rhU_{i\pm1} = U_i e^{\pm rh}. Then Ri=Ui(−ε′2cosh⁡(rh)−2h2+asinh⁡(rh)h)R_i = U_i\bigl(-\varepsilon'\frac{2\cosh(rh) - 2}{h^2} + a\frac{\sinh(rh)}{h}\bigr). With cosh⁡(rh)−1=2sinh⁡2(rh/2)\cosh(rh) - 1 = 2\sinh^2(rh/2) and sinh⁡(rh)=2sinh⁡(rh/2)cosh⁡(rh/2)\sinh(rh) = 2\sinh(rh/2)\cosh(rh/2), this is 2Uisinh⁡(rh/2)h(−2ε′hsinh⁡(rh/2)+acosh⁡(rh/2))\frac{2U_i\sinh(rh/2)}{h}\bigl(-\frac{2\varepsilon'}{h}\sinh(rh/2) + a\cosh(rh/2)\bigr). It is 00 because ε′=ah2coth⁡rh2\varepsilon' = \frac{ah}{2}\coth\frac{rh}{2}, and rh2=ah2ε\frac{rh}{2} = \frac{ah}{2\varepsilon}.

So Ri(u(x0),…,u(xm))=0+c+0=cR_i(u(x_0), \ldots, u(x_m)) = 0 + c + 0 = c for every interior ii, and the nodal values of uu take the right boundary values. By Claim 3 the discrete system has exactly one solution, so it is the vector of nodal values of uu. □\square

Conclusion. Lines L3 to L6 assemble BB and LL, line L7 imposes the boundary values, and line L8 solves the system without a zero pivot whenever ε+τa2≥∣a∣h/2\varepsilon + \tau a^2 \ge |a|h/2, which holds for the τ\tau of line L2. By Claim 3 the returned vector is the unique SUPG solution, by Claim 1 the method is consistent, so the error satisfies Galerkin orthogonality for the form BB, and by Claim 4 the result is exact at the nodes when ff is constant. ■\blacksquare

Complexity

In the 1D code each cell costs a constant amount of work: four matrix entries and five quadrature points for the load. The loop of lines L3 to L6 costs Θ(m)\Theta(m), and the Thomas algorithm in line L8 does one forward and one backward pass, also Θ(m)\Theta(m). So the total is Θ(m)\Theta(m) time in the worst case on the real-RAM model, with Θ(m)\Theta(m) extra memory for the four arrays. In several dimensions, SUPG has the same cost per cell as the Galerkin assembly, up to a constant, and the same sparsity pattern. The matrix is not symmetric, so the solve uses a sparse direct method or GMRES in place of conjugate gradients.

Properties

  • Consistency (theorem). The exact solution satisfies the discrete equations, so the error obeys Galerkin orthogonality for the SUPG form. Plain upwinding with diffusion ε+∣a∣h/2\varepsilon + |a|h/2 is not consistent and is only first order.
  • Error bound (theorem). For degree kk, ε≤h\varepsilon \le h and τK∼hK/∣a∣\tau_K \sim h_K/|a|, the error in the streamline diffusion norm (ε∣v∣12+∑KτK∥a⋅∇v∥K2)1/2\bigl(\varepsilon|v|_1^2 + \sum_K\tau_K\|a\cdot\nabla v\|_K^2\bigr)^{1/2} is O(hk+1/2)O(h^{k+1/2}) with a constant that does not depend on ε\varepsilon (Johnson, Nävert and Pitkäranta).
  • Nodal exactness in 1D (theorem). With the coth formula, P1 elements and constant ε\varepsilon, aa and ff, the nodal values are exact for every hh. This is the Il'in-Allen-Southwell scheme written as a finite element method.
  • No maximum principle in general. In two and three dimensions SUPG still shows small overshoots and undershoots near sharp layers, in particular across the flow.
  • Nonsymmetric matrix. The convection term makes the matrix nonsymmetric even without the stabilization.

Variants and improvements

  • Streamline diffusion. The method of Johnson and Nävert drops the residual and keeps only τ(a⋅∇uh,a⋅∇v)\tau(a\cdot\nabla u_h, a\cdot\nabla v) and the matching load term for P1, and it is often the same method under another name.
  • Galerkin least squares (GLS). Tests with τLv\tau L v for the whole operator LL, including the diffusion part. For Stokes flow with equal-order velocity and pressure, the same idea (PSPG) gives a stable method although the pair fails the inf-sup condition.
  • Shock capturing. Adds a nonlinear crosswind diffusion that depends on the residual and reduces the overshoots near layers. These methods are called SOLD methods (spurious oscillations at layers diminishing).
  • Residual-free bubbles and variational multiscale. Derive τ\tau from a local solve with bubble functions, which explains the coth formula.
  • Continuous interior penalty and local projection. Penalize jumps of the gradient across faces or fluctuations of a projection in place of the residual. They have a symmetric stabilization term and are easier to use in time-dependent problems.
  • Time-dependent problems. Common choices of τ\tau include the time step, for example τ=((2/Δt)2+(2∣a∣/h)2+(4ε/h2)2)−1/2\tau = \bigl((2/\Delta t)^2 + (2|a|/h)^2 + (4\varepsilon/h^2)^2\bigr)^{-1/2}. This is a heuristic.
  • Discontinuous Galerkin. Puts the upwinding into the numerical flux on faces in place of the test function.

When to use it

Use SUPG when a continuous finite element code must solve a transport problem with PeK>1\mathrm{Pe}_K > 1 on part of the mesh, for example the momentum equation of the Navier-Stokes equations at high Reynolds number or a temperature carried by a fast flow. It keeps the mesh, the element and the order of the Galerkin method and adds a small amount of code per cell. When strict bounds such as 0≤u≤10 \le u \le 1 matter more than accuracy, a monotone scheme such as a first-order upwind scheme, a finite volume method with limiters, or algebraic flux correction is safer. When the problem has steep fronts and needs local conservation, discontinuous Galerkin methods are the usual choice.

Pitfalls

  • Dropping the second-order term. For elements of degree 2 or more, a code that copies line L4 and leaves out −εΔuh-\varepsilon\Delta u_h in the residual is no longer consistent, and the convergence order drops. Keep the full residual on each cell.
  • Stabilizing the load wrongly. Line L5 must test ff with ϕr+τaϕr′\phi_r + \tau a\phi_r'. If it tests with ϕr\phi_r only, the method is the inconsistent "artificial diffusion" scheme, and the observed order falls to 1 when ff is not constant.
  • Mixing Péclet conventions. A formula for τ\tau written for Pe=∣a∣h/ε\mathrm{Pe} = |a|h/\varepsilon and evaluated with Pe=∣a∣h/(2ε)\mathrm{Pe} = |a|h/(2\varepsilon) gives the wrong amount of diffusion. Check which definition the source uses.
  • Cancellation in the coth formula. For small Pe\mathrm{Pe}, coth⁡Pe−1/Pe\coth\mathrm{Pe} - 1/\mathrm{Pe} loses all digits in floating point. Use the series Pe/3−Pe3/45\mathrm{Pe}/3 - \mathrm{Pe}^3/45 there, as line L2 says.
  • Using conjugate gradients. The matrix is not symmetric, so conjugate gradients can fail or converge to a wrong vector. Use GMRES, BiCGSTAB or a direct solver.
  • Expecting monotone results in 2D. The 1D nodal exactness does not carry over. Small oscillations near layers remain, and if they are not acceptable a shock-capturing term is needed.

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.

scisparse.pyI0RawGitHub
# 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
streamline_upwind_petrov_galerkin.py 93 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/streamline-upwind-petrov-galerkin/. The authors are listed in prov/CZJ24B.jsonl.

"""SUPG with P1 elements for -eps u'' + a u' = f on (0, 1), u(0) = g0, u(1) = g1.

The mesh is uniform with m cells of width h = 1/m. eps > 0 and a != 0 are
constants. The test function of the SUPG method is v + tau a v' on each
cell. With P1 elements u'' = 0 inside a cell, so the SUPG term is
tau (a v', a u' - f) on each cell. The global matrix is tridiagonal and is
solved by the Thomas algorithm, so one solve costs Theta(m) operations.
With Fraction data and a Fraction tau the result is exact.
"""

import math
from fractions import Fraction

import scisparse

# Boole's rule on [0, 1]: exact for polynomials of degree <= 5, rational weights.
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 cell_peclet(eps, a, h):
    """Return the cell Peclet number Pe_h = |a| h / (2 eps)."""
    return abs(a) * h / (2 * eps)


def optimal_tau(eps, a, h):
    """Return tau = h / (2 |a|) (coth(Pe_h) - 1 / Pe_h), the nodally exact choice in 1D."""
    pe = float(cell_peclet(eps, a, h))
    if pe < 1e-4:
        xi = pe / 3.0 - pe ** 3 / 45.0  # series of coth(pe) - 1/pe, avoids cancellation
    else:
        xi = 1.0 / math.tanh(pe) - 1.0 / pe
    return float(h) / (2.0 * abs(float(a))) * xi


def supg(eps, a, f, m, g0=0, g1=0, tau=None):
    """Solve the SUPG problem and return the nodal values U_0, ..., U_m.

    f is a function of x. tau=None takes optimal_tau; tau=0 gives the plain
    Galerkin method. Precondition: m >= 2, eps > 0, a != 0, and tau >= 0.
    Cost: Theta(m) operations and Theta(m) memory.
    """
    h = Fraction(1, m) if isinstance(eps, Fraction) else 1.0 / m  # @line L1
    if tau is None:
        tau = optimal_tau(eps, a, h)  # @line L2
    n = m + 1
    lo = [0] * n  # sub-diagonal: lo[i] multiplies U[i-1] in row i
    di = [0] * n  # diagonal
    up = [0] * n  # super-diagonal: up[i] multiplies U[i+1] in row i
    rhs = [0] * n
    dphi = (-1 / h, 1 / h)  # derivatives of the two local hat functions
    for j in range(m):  # @line L3
        x0 = j * h
        ak = [[0, 0], [0, 0]]
        bk = [0, 0]
        for r in range(2):
            for s in range(2):
                # eps (phi_s', phi_r') + a (phi_s', phi_r) + tau a^2 (phi_s', phi_r')
                ak[r][s] = (eps + tau * a * a) * dphi[s] * dphi[r] * h + a * dphi[s] * h / 2  # @line L4
            for xi, w in BOOLE:
                phi = (1 - xi, xi)[r]
                bk[r] += w * h * f(x0 + xi * h) * (phi + tau * a * dphi[r])  # @line L5
        # add the 2 by 2 block into the tridiagonal arrays
        di[j] += ak[0][0]  # @line L6
        up[j] += ak[0][1]
        lo[j + 1] += ak[1][0]
        di[j + 1] += ak[1][1]
        rhs[j] += bk[0]
        rhs[j + 1] += bk[1]
    # Dirichlet rows: U_0 = g0 and U_m = g1; move the known values to the right side
    rhs[1] -= lo[1] * g0  # @line L7
    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 L8
    return [g0] + inner + [g1]  # @line L9


def exact(eps, a, c, g0, g1, x):
    """Exact solution of -eps u'' + a u' = c (a constant c) with u(0) = g0, u(1) = g1."""
    r = a / eps
    if r > 0:
        # w(x) = (e^(r x) - 1) / (e^r - 1), written as e^(r (x - 1)) forms to avoid overflow
        w = (math.exp(r * (x - 1)) - math.exp(-r)) / (1 - math.exp(-r))
    else:
        w = (math.exp(r * x) - 1) / (math.exp(r) - 1)
    lin = c * x / a
    # u = lin + g0 + (g1 - g0 - c / a) w satisfies both boundary values
    return lin + g0 + (g1 - g0 - c / a) * w
test_streamline_upwind_petrov_galerkin.py 103 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/streamline-upwind-petrov-galerkin/. The authors are listed in prov/CZJ24B.jsonl.

import math
import random
from fractions import Fraction as F

import scisparse
from streamline_upwind_petrov_galerkin import cell_peclet, exact, optimal_tau, supg


def max_nodal_error(U, u, m):
    return max(abs(U[j] - u(j / m)) for j in range(m + 1))


def test_cell_peclet_and_tau() -> None:
    assert cell_peclet(0.01, 1.0, 0.1) == 5.0
    h, eps = 0.1, 0.01
    pe = cell_peclet(eps, 1.0, h)
    expected = h / 2 * (1 / math.tanh(pe) - 1 / pe)
    assert abs(optimal_tau(eps, 1.0, h) - expected) < 1e-15
    # the sign of a does not change tau
    assert optimal_tau(eps, -1.0, h) == optimal_tau(eps, 1.0, h)
    # small Pe: tau = h^2 / (12 eps) to first order
    t = optimal_tau(1.0, 1.0, 1e-6)
    assert abs(t / (1e-12 / 12) - 1) < 1e-6
    # large Pe: tau tends to h / (2 |a|)
    assert abs(optimal_tau(1e-8, 2.0, 0.1) - 0.1 / 4) < 1e-8


def test_nodally_exact_for_constant_source() -> None:
    rng = random.Random(7)
    # oracle: the closed-form solution, sampled at the nodes
    for _ in range(500):
        eps = 10 ** rng.uniform(-3, 0)
        a = rng.choice([-1, 1]) * rng.uniform(0.5, 2.0)
        c = rng.uniform(-2, 2)
        g0, g1 = rng.uniform(-1, 1), rng.uniform(-1, 1)
        m = rng.randint(2, 20)
        U = supg(eps, a, lambda x: c, m, g0, g1)
        err = max_nodal_error(U, lambda x: exact(eps, a, c, g0, g1, x), m)
        assert err < 1e-9, (eps, a, m, err)


def test_galerkin_oscillates_supg_does_not() -> None:
    eps, a, m = 0.01, 1.0, 10  # Pe_h = 5
    gal = supg(eps, a, lambda x: 0.0, m, 0.0, 1.0, tau=0)
    st = supg(eps, a, lambda x: 0.0, m, 0.0, 1.0)
    assert min(gal) < -0.5  # negative values although 0 <= u <= 1
    assert any(gal[j + 1] < gal[j] for j in range(m))
    assert all(st[j] <= st[j + 1] for j in range(m))
    assert all(-1e-12 <= v <= 1 + 1e-12 for v in st)


def test_exact_fraction_equivalence_with_extra_diffusion() -> None:
    # P1, constant data: SUPG with tau equals Galerkin with eps + tau a^2
    for eps, a, tau, c, m in [(F(1, 50), F(1), F(1, 25), F(1), 10),
                              (F(1, 3), F(-2), F(1, 7), F(-3, 2), 7)]:
        s = supg(eps, a, lambda x: c, m, F(0), F(1), tau=tau)
        g = supg(eps + tau * a * a, a, lambda x: c, m, F(0), F(1), tau=F(0))
        assert s == g
        assert all(isinstance(v, F) for v in s)


def test_linear_solution_reproduced_for_any_tau() -> None:
    # u = 2 x + 1 solves -eps u'' + a u' = 2 a; the residual is zero on every cell
    for tau in (F(0), F(1, 9), F(3)):
        U = supg(F(1, 10), F(3), lambda x: F(6), 9, F(1), F(3), tau=tau)
        assert U == [1 + 2 * F(j, 9) for j in range(10)]


def test_thomas_solves_the_assembled_rows() -> None:
    # residual check of the helper on a diagonally dominant system
    rng = random.Random(3)
    n = 12
    a = [rng.uniform(-1, 0) for _ in range(n)]
    c = [rng.uniform(-1, 0) for _ in range(n)]
    b = [abs(a[i]) + abs(c[i]) + rng.uniform(0.1, 1) for i in range(n)]
    d = [rng.uniform(-1, 1) for _ in range(n)]
    x = scisparse.thomas(a, b, c, d)
    for i in range(n):
        r = b[i] * x[i] - d[i]
        if i > 0:
            r += a[i] * x[i - 1]
        if i < n - 1:
            r += c[i] * x[i + 1]
        assert abs(r) < 1e-12


def test_refinement_rates() -> None:
    a = 1.0
    for eps, lo in ((1.0, 3.8), (0.01, 3.0)):
        def f(x, eps=eps):
            return eps * math.pi ** 2 * math.sin(math.pi * x) + a * math.pi * math.cos(math.pi * x)

        def u(x):
            return math.sin(math.pi * x)

        e = [max_nodal_error(supg(eps, a, f, m), u, m) for m in (16, 32, 64)]
        assert math.log2(e[1] / e[2]) > lo, (eps, e)
        g = [max_nodal_error(supg(eps, a, f, m, tau=0), u, m) for m in (16, 32, 64)]
        assert abs(math.log2(g[1] / g[2]) - 2) < 0.1
        assert e[2] < g[2]

History

D. N. de G. Allen and Richard Southwell used an exponentially fitted difference scheme for viscous flow past a cylinder in 1955, and A. M. Il'in analyzed such schemes in 1969. In 1976 Christie, Griffiths, Mitchell and Zienkiewicz showed that asymmetric linear and quadratic test functions remove the Galerkin oscillations of the two-point problem. Hughes and Brooks proposed streamline upwinding without crosswind diffusion in 1979, and their 1982 paper gave SUPG in its consistent Petrov-Galerkin form, with applications to the incompressible Navier-Stokes equations. Johnson, Nävert and Pitkäranta proved the hk+1/2h^{k+1/2} error bound in 1984. Hughes, Franca and Hulbert generalized the method to Galerkin least squares in 1989.

References

  1. Alexander N. Brooks and Thomas J. R. Hughes, Streamline upwind/Petrov-Galerkin formulations for convection dominated flows with particular emphasis on the incompressible Navier-Stokes equations, Computer Methods in Applied Mechanics and Engineering 32 (1982) 199-259, the SUPG weighting functions, the one-dimensional optimal parameter and the advection-diffusion examples
  2. I. Christie, D. F. Griffiths, A. R. Mitchell and O. C. Zienkiewicz, Finite element methods for second order differential equations with significant first derivatives, International Journal for Numerical Methods in Engineering 10(6) (1976) 1389-1396, asymmetric linear and quadratic weighting functions for the two-point convection-diffusion problem
  3. Claes Johnson, Uno Nävert and Juhani Pitkäranta, Finite element methods for linear hyperbolic problems, Computer Methods in Applied Mechanics and Engineering 45 (1984) 285-312, the streamline diffusion method and its error estimate of order h^(k+1/2)
  4. Hans-Görg Roos, Martin Stynes and Lutz Tobiska, Robust Numerical Methods for Singularly Perturbed Differential Equations, second edition, Springer Series in Computational Mathematics 24, 2008, Part III (convection-diffusion problems in several dimensions), the streamline diffusion finite element method

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

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