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.
- Solves
- Advection equation
- Time
- Θ(m) worst
- Space
- Θ(m) extra
- Where
- m = the number of cells of the one-dimensional mesh
- Model
- Real RAM
- Properties
- consistentdeterministicnodally exact in 1d with optimal taunot symmetric matrix
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Alexander N. Brooks, Thomas J. R. Hughes, 1982
The streamline upwind Petrov-Galerkin method (SUPG) solves convection-diffusion problems such as with continuous finite elements when the convection is much stronger than the diffusion . On each cell it tests the equation with in place of , 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 , a diffusion coefficient , a velocity field , a source , boundary values , and a mesh with a continuous finite element space of degree . The reference code takes , constant and , cells of width , P1 elements, and , .
Output. with the boundary values and
for all that vanish on the boundary. The cell Péclet number is . Some sources omit the factor 2 and write . The problem is convection dominated when .
The algorithm
The standard parameter is
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 behave about the same. The steps for the one-dimensional P1 case are:
SUPG(eps, a, f, m, g0, g1) ▷ -eps u'' + a u' = f on (0, 1), P1 on m cells- 1
h <- 1/m; Pe <- |a| h / (2 eps) - 2
tau <- (h / (2 |a|)) (coth(Pe) - 1/Pe) ▷ use a series when Pe is small - 3
for j <- 0 to m - 1 do ▷ cell [x_j, x_{j+1}] with local hats phi_0, phi_1 - 4
A_K[r, s] <- (eps + tau a^2) (phi_s', phi_r')_K + a (phi_s', phi_r)_K for r, s in {0, 1} - 5
b_K[r] <- (f, phi_r + tau a phi_r')_K by quadrature - 6
add A_K into rows and columns j, j + 1 of the tridiagonal arrays, and b_K into the right side - 7
move the known values U_0 = g0 and U_m = g1 to the right side of rows 1 and m - 1 - 8
(U_1, ..., U_{m-1}) <- THOMAS(sub, diag, super, rhs) on rows 1 to m - 1 - 9
return (g0, U_1, ..., U_{m-1}, g1)
Line L4 uses the fact that a P1 function has inside a cell, so the SUPG term becomes on the matrix side and on the load side. In 1D with P1 elements, SUPG therefore equals the Galerkin method with the diffusion 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 , since it is not zero inside the cell.
Example
Take , , , , and , so and . The exact solution is almost up to a boundary layer of width about at .
For the Galerkin method (), each interior row reads . The characteristic equation has the roots and . In general the second root is , which is negative exactly when . So with , and the sign alternates from node to node.
For SUPG, line L2 gives , so the diffusion in line L4 is . The second root becomes , which is the ratio of the exact solution from one node to the next.
| 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 and on the same mesh, the Galerkin values at are , , , , , , , , , while the exact solution is close to there. SUPG reproduces the exact nodal values up to rounding (a difference of ).
Smooth data (measurement). For with , the maximum nodal error of SUPG at is , , , for , an observed order of 4.0. The Galerkin errors are , , , , order 2. For the SUPG errors are , , , , 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 in the SUPG form. Second, for P1 elements the SUPG matrix is the Galerkin matrix with diffusion . Third, the form is coercive with on functions that vanish at the ends, so the solution exists and is unique, and when the matrix is diagonally dominant and the Thomas algorithm meets no zero pivot. Fourth, with the of line L2, , and the discrete equations hold exactly for , and , so the nodal values are exact for a constant .
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 on with and , where and are constants. The mesh has the nodes , , , and is the space of continuous piecewise linear functions. is the subspace of functions that vanish at and . For , the SUPG problem is: find with , and
where is the product on the cell and is the product on . Lines L3 to L6 of the algorithm compute the matrix of and the vector of in the hat basis, cell by cell. The proof of finite element assembly shows that this gives and when the quadrature of line L5 is exact, and Boole's rule is exact when 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 is in , then for all , so .
Proof. Integration by parts on , with , gives . So . On each cell , so . Adding the two identities gives . Subtract .
Claim 2 (the extra diffusion). For , . For a constant and an interior hat function , , .
Proof. On each cell is linear, so there and . Summing over gives the first identity. For the second, , and because the hat function has area .
Claim 3 (unique solution). For every the SUPG problem has exactly one solution. If satisfies , the Thomas algorithm of line L8 meets no zero pivot.
Proof. Write with the function with nodal values and . The problem becomes for all , a square linear system of size . It has a unique solution if implies on . By Claim 2, . If this is , then , so is constant, and gives .
For the pivots: by Claim 2, row of the inner system () has the entries
for , and , except that line L7 removes from the first row and from the last. If , both and are , so . The Thomas algorithm uses the pivots and for , with .
- If , then and . We show by induction that , so and . For , . For the step, the hypothesis and give .
- If , one of and is , so the matrix is bidiagonal. If , every is and every pivot is . If , again every pivot is .
In both cases no pivot is zero.
Claim 4 (nodal exactness). Let and , the value of line L2. If is constant, then for , where is the exact solution.
Proof. First, , because . Since is odd, this is also , and because for .
By Claim 2 and the entries in the proof of Claim 3, row of the system, divided by , reads
The exact solution is with , , and , fixed by the boundary values. is linear, so we check each term on the nodal values :
- For : .
- For : the second difference is and the centered difference is , so . Times this gives .
- For : write . Then . With and , this is . It is because , and .
So for every interior , and the nodal values of take the right boundary values. By Claim 3 the discrete system has exactly one solution, so it is the vector of nodal values of .
Conclusion. Lines L3 to L6 assemble and , line L7 imposes the boundary values, and line L8 solves the system without a zero pivot whenever , which holds for the 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 , and by Claim 4 the result is exact at the nodes when is constant.
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 , and the Thomas algorithm in line L8 does one forward and one backward pass, also . So the total is time in the worst case on the real-RAM model, with 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 is not consistent and is only first order.
- Error bound (theorem). For degree , and , the error in the streamline diffusion norm is with a constant that does not depend on (Johnson, Nävert and Pitkäranta).
- Nodal exactness in 1D (theorem). With the coth formula, P1 elements and constant , and , the nodal values are exact for every . 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 and the matching load term for P1, and it is often the same method under another name.
- Galerkin least squares (GLS). Tests with for the whole operator , 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 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 include the time step, for example . 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 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 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 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 with . If it tests with only, the method is the inconsistent "artificial diffusion" scheme, and the observed order falls to 1 when is not constant.
- Mixing Péclet conventions. A formula for written for and evaluated with gives the wrong amount of diffusion. Check which definition the source uses.
- Cancellation in the coth formula. For small , loses all digits in floating point. Use the series 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.
# 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 error bound in 1984. Hughes, Franca and Hulbert generalized the method to Galerkin least squares in 1989.
References
- 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
- 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
- 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)
- 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.
| 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 CZJ24B Edit this page History Report an error Markdown