Algorithm Search⌘K

Algorithmadvanced

Spectral element method

Also called SEM.

Uses high degree tensor product polynomials on quadrilaterals or hexahedra with Gauss-Lobatto nodes, giving a diagonal mass matrix and spectral accuracy.

Time
Θ(E N^3) average
Space
Θ(E N^2) extra
Where
E = the number of elements; N = the polynomial degree
Properties
conformingdeterministicdiagonal mass matrixspectral accuracy
Origin
Anthony T. Patera, Yvon Maday, 1984

The spectral element method (SEM) is a finite element method of high degree. The domain is cut into a few large quadrilaterals or hexahedra, and on each one the solution is a tensor product polynomial of degree NN in each direction, stored by its values at the Gauss-Lobatto-Legendre (GLL) nodes. All integrals use the GLL quadrature on the same nodes. This one choice has three effects. The mass matrix is diagonal, so explicit time stepping needs no linear solve. The stiffness matrix is exact in 1D and the operators factor into small 1D matrices on tensor product elements. And for smooth solutions the error falls exponentially in NN, which is called spectral accuracy. The method was made for fluid dynamics, and codes such as Nek5000 use it for turbulent flow, acoustics and seismic waves.

In plain words

Cut the domain into a few big pieces. On each piece, use one polynomial of high degree, and store it by its values at special points that crowd toward the ends of the piece. The same points are used to compute all the integrals. Because the points and the integration rule match, the mass matrix has only diagonal entries, which makes time steps cheap. Because the degree is high, a smooth solution is very accurate with few unknowns: each extra degree removes a fixed fraction of the error. In 2D and 3D the polynomial on a square or a cube is a product of 1D ones, so all the work reduces to small 1D matrix operations.

The problem

Input. The 1D model problem −u′′+cu=f-u'' + cu = f on (a,b)(a, b) with u(a)=u(b)=0u(a) = u(b) = 0 and c≥0c \ge 0, a mesh a=x0<x1<⋯<xE=ba = x_0 < x_1 < \cdots < x_E = b of EE elements, and a degree N≥1N \ge 1.

Output. The values of the discrete solution uNu_N at all GLL nodes of all elements. Between the nodes, uNu_N is the Lagrange interpolant on each element.

The algorithm

  1. SEM-1D(mesh, N, f, c)
  2. 1(xi, w) <- GLL nodes and weights of degree N on [-1, 1]; D <- the derivative matrix, D_ij = l_j'(xi_i)
  3. 2for each element e of length h do
  4. 3K_e <- (2 / h) D^T diag(w) D; M_e <- (h / 2) diag(w); F_e <- (h / 2) w * f(x_e) ▷ the mass is diagonal
  5. 4add K_e + c M_e to A and F_e to F, sharing the end node with the neighbor
  6. 5solve A U = F on the interior nodes ▷ U = 0 at a and b
  7. 6return U

The GLL nodes are −1-1, 11 and the roots of PN′P_N', where PNP_N is the Legendre polynomial of degree NN. The weights are wj=2/(N(N+1)PN(ξj)2)w_j = 2/(N(N+1)P_N(\xi_j)^2). The code finds the nodes with a Newton type iteration started at the Chebyshev-Lobatto points, and it builds DD from the barycentric weights.

Tensor products. On a square element of degree NN, the nodes are the pairs (ξi,ξj)(\xi_i, \xi_j), the mass is diag⁡(w)⊗diag⁡(w)\operatorname{diag}(w)\otimes\operatorname{diag}(w), and the stiffness for −Δ-\Delta on the reference square is K^⊗M^+M^⊗K^\hat K\otimes\hat M + \hat M\otimes\hat K with the 1D matrices K^=DTdiag⁡(w)D\hat K = D^{\mathsf T}\operatorname{diag}(w)D and M^=diag⁡(w)\hat M = \operatorname{diag}(w). Applying such an operator to a vector by 1D matrix products, called sum factorization, costs O(Nd+1)O(N^{d+1}) per element in dd dimensions, not the O(N2d)O(N^{2d}) of a stored element matrix. So large SEM codes never form the global matrix. They use the conjugate gradient method with matrix-free products.

Example

By hand. Take one element [0,1][0, 1], N=2N = 2, c=0c = 0 and f=1f = 1, so u=x(1−x)/2u = x(1 - x)/2. The GLL nodes are −1,0,1-1, 0, 1 with weights 13,43,13\tfrac13, \tfrac43, \tfrac13, and

D=(−322−12−1201212−232).D = \begin{pmatrix} -\tfrac32 & 2 & -\tfrac12 \\ -\tfrac12 & 0 & \tfrac12 \\ \tfrac12 & -2 & \tfrac32 \end{pmatrix}.

With h=1h = 1, the only interior node is x=12x = \tfrac12. Its stiffness entry is 2∑qwqDq12=2(13⋅4+43⋅0+13⋅4)=1632\sum_q w_qD_{q1}^2 = 2(\tfrac13\cdot4 + \tfrac43\cdot0 + \tfrac13\cdot4) = \tfrac{16}{3}, and its load is 12⋅43⋅1=23\tfrac12\cdot\tfrac43\cdot1 = \tfrac23. So U=2/316/3=18=u(12)U = \tfrac{2/3}{16/3} = \tfrac18 = u(\tfrac12). The answer is exact, because uu is a quadratic. The diagonal mass entry at that node would be 12⋅43=23\tfrac12\cdot\tfrac43 = \tfrac23.

Measured. For −u′′+u=f-u'' + u = f on (0,1)(0, 1) with u=exsin⁡(πx)u = e^x\sin(\pi x), the reference code gives these maximum errors over 98 points.

Elements EE Degree NN Unknowns Max error
1 4 3 1.6×10−21.6 \times 10^{-2}
1 8 7 1.1×10−61.1 \times 10^{-6}
1 12 11 4.5×10−114.5 \times 10^{-11}
1 14 13 2.0×10−132.0 \times 10^{-13}
2 8 15 5.4×10−95.4 \times 10^{-9}
4 2 7 6.3×10−36.3 \times 10^{-3}
8 2 15 8.0×10−48.0 \times 10^{-4}
16 2 31 1.0×10−41.0 \times 10^{-4}
32 2 63 1.2×10−51.2 \times 10^{-5}

At a fixed degree N=2N = 2 the error falls like h3=hN+1h^3 = h^{N+1}, a factor of 8 per halving. At a fixed mesh, each increase of NN by 4 removes 4 to 5 digits. With 13 unknowns the error is near roundoff, while N=2N = 2 needs 63 unknowns for 10−510^{-5}.

Correctness

The full proof is in the correctness proof. The GLL rule with N+1N + 1 nodes is exact for polynomials of degree 2N−12N - 1: split a polynomial as a multiple of (1−x2)PN′(1 - x^2)P_N' plus a remainder of degree NN, and the first part integrates to 0 by the orthogonality of PNP_N. The stiffness integrand ℓi′ℓj′\ell_i'\ell_j' has degree 2N−22N - 2, so line L3 gives the exact stiffness. The mass integrand ℓiℓj\ell_i\ell_j has degree 2N2N, one too many, and the rule gives wiδijw_i\delta_{ij}, which is the row sum of the exact mass matrix. The assembled matrix is symmetric positive definite, so line L5 has one solution, and it is the Galerkin solution with the mass and the load integrated by the GLL rule. Strang's lemma then bounds the error by the best approximation and the quadrature errors, which decay exponentially in NN for analytic data.

Proof: The GLL rule is exact to degree 2N-1, so the stiffness is exact and the mass is diagonal, and the assembled system has a unique solutionfull

Setting. The problem is −u′′+cu=f-u'' + cu = f on (a,b)(a, b) with u(a)=u(b)=0u(a) = u(b) = 0 and a constant c≥0c \ge 0. The interval is cut into elements KeK_e of length heh_e. On [−1,1][-1, 1], the GLL nodes of degree N≥1N \ge 1 are ξ0=−1<ξ1<⋯<ξN=1\xi_0 = -1 < \xi_1 < \cdots < \xi_N = 1, where ξ1,…,ξN−1\xi_1, \ldots, \xi_{N-1} are the roots of PN′P_N', and ℓ0,…,ℓN\ell_0, \ldots, \ell_N are the Lagrange polynomials of degree NN on these nodes. The weights are wj=∫−11ℓjw_j = \int_{-1}^{1}\ell_j. The discrete space VNV_N is the set of continuous functions that are 0 at aa and bb and are polynomials of degree at most NN on each element, stored by their values at the mapped nodes. SEM-1D is lines L1 to L6 of the main page.

We prove four claims.

  1. (Exactness of the rule.) ∑jwjq(ξj)=∫−11q\sum_j w_j q(\xi_j) = \int_{-1}^1 q for every polynomial qq of degree at most 2N−12N - 1.
  2. (Stiffness and mass.) The matrix (2/h)DTdiag⁡(w)D(2/h)D^{\mathsf T}\operatorname{diag}(w)D at line L3 equals the exact element stiffness ∫Kϕi′ϕj′ dx\int_{K}\phi_i'\phi_j'\,dx, and the GLL mass (h/2)diag⁡(w)(h/2)\operatorname{diag}(w) is the exact mass matrix with each row summed onto the diagonal.
  3. (The derivative matrix.) Dij=ℓj′(ξi)D_{ij} = \ell_j'(\xi_i), so DvDv is the exact derivative at the nodes of the polynomial with node values vv.
  4. (Unique solution.) The assembled system at line L5 is symmetric positive definite, so it has exactly one solution, and this solution is the uN∈VNu_N \in V_N with ∫uN′v′+c(uN,v)N=(f,v)N\int u_N'v' + c(u_N, v)_N = (f, v)_N for all v∈VNv \in V_N, where (⋅,⋅)N(\cdot, \cdot)_N is the GLL rule applied element by element.

Proof of 1. First, the rule is exact for degree at most NN: such a qq equals its interpolant ∑jq(ξj)ℓj\sum_j q(\xi_j)\ell_j, and integrating gives ∑jq(ξj)wj\sum_j q(\xi_j)w_j. Now let qq have degree at most 2N−12N - 1, and let ω(x)=(1−x2)PN′(x)\omega(x) = (1 - x^2)P_N'(x), of degree N+1N + 1, which is 0 at all N+1N + 1 nodes. Divide: q=ωs+rq = \omega s + r with deg⁡s≤N−2\deg s \le N - 2 and deg⁡r≤N\deg r \le N. The rule gives ∑jwjr(ξj)=∫r\sum_j w_j r(\xi_j) = \int r. For the other part, integrate by parts; the boundary term is 0 because 1−x21 - x^2 is 0 at ±1\pm 1:

∫−11(1−x2)PN′ s=−∫−11PN ((1−x2)s)′.\int_{-1}^{1}(1 - x^2)P_N'\,s = -\int_{-1}^{1}P_N\,\big((1 - x^2)s\big)'.

The polynomial ((1−x2)s)′((1 - x^2)s)' has degree at most N−1N - 1, and PNP_N is orthogonal to all such polynomials, so the integral is 0. The rule also gives 0 for ωs\omega s. So the rule is exact for qq. (If N=1N = 1 there is no ss and the claim is the trapezoid rule for linear qq.) □\square

The code computes wjw_j by the classical formula wj=2/(N(N+1)PN(ξj)2)w_j = 2/(N(N+1)P_N(\xi_j)^2), which equals ∫ℓj\int\ell_j. The test file checks this for N=2,4N = 2, 4 against the known values and checks the exactness of claim 1 for N=3,6,9N = 3, 6, 9.

Proof of 3. For i≠ji \ne j, write ℓj(x)=λj∏k≠j(x−ξk)\ell_j(x) = \lambda_j\prod_{k \ne j}(x - \xi_k) with the barycentric weight λj=1/∏k≠j(ξj−ξk)\lambda_j = 1/\prod_{k \ne j}(\xi_j - \xi_k). The product rule at x=ξix = \xi_i leaves only the term in which the factor (x−ξi)(x - \xi_i) is differentiated: ℓj′(ξi)=λj∏k≠i,j(ξi−ξk)=(λj/λi)/(ξi−ξj)\ell_j'(\xi_i) = \lambda_j\prod_{k \ne i, j}(\xi_i - \xi_k) = (\lambda_j/\lambda_i)/(\xi_i - \xi_j), which is the formula in the code. For i=ji = j, the polynomials ℓj\ell_j sum to 1, so their derivatives sum to 0 and ℓi′(ξi)=−∑j≠iℓj′(ξi)\ell_i'(\xi_i) = -\sum_{j \ne i}\ell_j'(\xi_i), which is the diagonal in the code. □\square

Proof of 2. On KK with x=xK+h(ξ+1)/2x = x_K + h(\xi + 1)/2, the basis is ϕi(x)=ℓi(ξ)\phi_i(x) = \ell_i(\xi), and ϕi′=(2/h)ℓi′\phi_i' = (2/h)\ell_i'. So the exact stiffness is (2/h)∫−11ℓi′ℓj′ dξ(2/h)\int_{-1}^{1}\ell_i'\ell_j'\,d\xi. The integrand has degree 2N−2≤2N−12N - 2 \le 2N - 1, so by claim 1 it equals (2/h)∑qwqℓi′(ξq)ℓj′(ξq)=(2/h)∑qwqDqiDqj(2/h)\sum_q w_q\ell_i'(\xi_q)\ell_j'(\xi_q) = (2/h)\sum_q w_qD_{qi}D_{qj} by claim 3, which is line L3. For the mass, the GLL rule gives (h/2)∑qwqℓi(ξq)ℓj(ξq)=(h/2)wiδij(h/2)\sum_q w_q\ell_i(\xi_q)\ell_j(\xi_q) = (h/2)w_i\delta_{ij}, because ℓi(ξq)=δiq\ell_i(\xi_q) = \delta_{iq}. The exact mass has row sums (h/2)∑j∫ℓiℓj=(h/2)∫ℓi=(h/2)wi(h/2)\sum_j\int\ell_i\ell_j = (h/2)\int\ell_i = (h/2)w_i, because ∑jℓj=1\sum_j\ell_j = 1. So the GLL mass is the row sum lumping of the exact mass. The exact mass itself is not diagonal, because ℓiℓj\ell_i\ell_j has degree 2N2N, one more than claim 1 covers. □\square

Proof of 4. Line L4 adds the element matrices into the rows and columns of the global node numbers, and neighbor elements share their end node, so the assembled matrix AA satisfies vTAv=∫v′2+c (v,v)Nv^{\mathsf T}Av = \int v'^2 + c\,(v, v)_N for the function v∈VNv \in V_N with node values vv, by claim 2. Both terms are at least 0, because the weights wj=2/(N(N+1)PN(ξj)2)w_j = 2/(N(N+1)P_N(\xi_j)^2) are positive. If vTAv=0v^{\mathsf T}Av = 0 then v′=0v' = 0, so vv is constant, and v(a)=0v(a) = 0 gives v=0v = 0. So AA restricted to the interior nodes at line L5 is symmetric positive definite, the solve has a unique solution, and the equations are the stated discrete weak form, with the load (f,ϕi)N=(h/2)wif(xi)(f, \phi_i)_N = (h/2)w_if(x_i) on each element. □\square

Remark on the rate. The method is a Galerkin method with the integrals of the mass and the load replaced by the GLL rule. Strang's first lemma bounds the error by the best approximation error in VNV_N plus the quadrature errors in the load and the mass, and for analytic uu and ff both decay like ρ−N\rho^{-N} for some ρ>1\rho > 1 on a fixed mesh. Maday and Patera gave this analysis; the reference run shows maximum errors from 1.6×10−21.6 \times 10^{-2} at N=4N = 4 to 2×10−132 \times 10^{-13} at N=14N = 14 on one element.

Complexity

The 1D code forms the element matrices in O(N3)O(N^3) each and solves the global system densely, which is fine for the small sizes in the tests. A banded solve of the global 1D system costs Θ(EN3)\Theta(EN^3), since the bandwidth is NN, and that is the bound in the front matter. The memory for the element matrices is Θ(EN2)\Theta(EN^2). In dd dimensions, one matrix-free operator application costs Θ(ENd+1)\Theta(EN^{d+1}) by sum factorization, and the diagonal mass makes an explicit time step cost the same.

Properties

  • Diagonal mass. The GLL mass matrix is diagonal with positive entries, and it equals the row sum mass lumping of the exact mass matrix.
  • Spectral accuracy. For analytic solutions on a fixed mesh, the error decays like ρ−N\rho^{-N} with ρ>1\rho > 1. For a solution in HsH^s, the error in H1H^1 decays like N1−sN^{1-s}, with no upper limit on the rate.
  • Exact 1D stiffness. The rule integrates ℓi′ℓj′\ell_i'\ell_j' exactly. In 2D the factor M^\hat M in K^⊗M^\hat K\otimes\hat M is the diagonal GLL mass, so the 2D stiffness is not exact, but the error is of the same size as the quadrature error in the mass.
  • Low dissipation and dispersion. For wave problems, the phase error of high degree elements is much smaller than for low order elements at the same number of unknowns per wavelength.
  • Conforming. The basis is continuous across elements, so the method is a conforming Galerkin method up to the quadrature.

Variants and improvements

  • Chebyshev spectral elements. Patera's original method used Chebyshev points and expansions on each element. The Legendre form is now standard because the GLL rule gives the diagonal mass and a symmetric system.
  • Modal bases. The hp finite element method often uses integrated Legendre polynomials instead of nodal values. They span the same space and allow a different degree on each element.
  • Static condensation. The interior nodes of each element can be removed by static condensation, which leaves a system on the element boundaries only.
  • Spectral element in time domain for waves. In seismology the method with explicit time stepping is the standard for global wave propagation, because the diagonal mass makes each step cheap.
  • Discontinuous variants. Discontinuous Galerkin spectral element methods use the same nodes but allow jumps between elements, with fluxes at the faces.
  • Triangles and tetrahedra. Tensor product structure is lost on simplices. Special node sets and collapsed coordinate bases extend the method, at a higher cost.

When to use it

Use the spectral element method for problems with smooth solutions where high accuracy matters per unknown: incompressible and turbulent flow, acoustics, and seismic waves. The diagonal mass makes it a natural choice for explicit time stepping, and the tensor product structure makes it fast on modern hardware. Use global spectral methods instead on simple periodic or box domains, and use low order finite elements or hp refinement when the solution has singularities or the geometry needs many small elements.

Pitfalls

  • Under integration of the mass. The diagonal mass comes from a rule that is not exact for ℓiℓj\ell_i\ell_j. This is part of the method and does not reduce the spectral rate, but it means the mass is not the exact L2L^2 product.
  • Aliasing in nonlinear terms. Products like u ∂xuu\,\partial_xu integrated on the GLL nodes create aliasing errors that can make a flow simulation unstable. Codes use over-integration or filtering.
  • Conditioning. The condition number of the stiffness matrix grows like N3N^3 in 1D on a fixed mesh for this nodal basis. Iterative solvers need preconditioners made for high degree.
  • Singularities. A corner singularity limits the rate to algebraic, as for every polynomial method. Grade the mesh toward the singularity, as in hp-FEM.
  • Node computation. For large NN, compute the GLL nodes and weights with a stable iteration, not by finding the roots of a polynomial given by its coefficients.
  • Curved elements. On a curved element the Jacobian is not constant, the integrands are not polynomials, and the GLL rule is no longer exact for the stiffness. The method still converges, but the exactness claims do not hold.

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.

scimat.pyI0RawGitHub
# 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)]
spectral_element_method.py 122 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/spectral-element-method/. The authors are listed in prov/6Q7T79.jsonl.

"""Spectral element method in 1D with Gauss-Lobatto-Legendre (GLL) nodes.

Model problem: -u'' + c u = f on (a, b), u(a) = u(b) = 0, c >= 0.
The interval is cut into elements; on each element u_h is a polynomial of
degree N, stored by its values at the N + 1 GLL nodes. All integrals use
the GLL rule on the same nodes, so the mass matrix is diagonal:
M_e = (h_e / 2) diag(w). The stiffness is K_e = (2 / h_e) D^T diag(w) D,
with D the derivative matrix at the nodes.

The global system is solved densely with scimat.solve. This is fine for the
small sizes here; real codes use a matrix-free conjugate gradient method.
"""

import math

import scimat


def _legendre_pair(n, x):
    """Return (P_{n-1}(x), P_n(x))."""
    p0, p1 = 1.0, x
    if n == 0:
        return 0.0, 1.0
    for k in range(2, n + 1):
        p0, p1 = p1, ((2 * k - 1) * x * p1 - (k - 1) * p0) / k
    return p0, p1


def gll(n):
    """Return the n + 1 GLL nodes on [-1, 1] (increasing) and their weights.

    The nodes are -1, 1 and the roots of P_n'. The iteration
    x <- x - (x P_n - P_{n-1}) / ((n + 1) P_n) starts at the Chebyshev-Lobatto points.
    """
    if n < 1:
        raise ValueError("gll needs n >= 1")
    xs = []
    for j in range(n + 1):
        x = -math.cos(math.pi * j / n)
        for _ in range(100):
            pm, p = _legendre_pair(n, x)
            dx = (x * p - pm) / ((n + 1) * p)
            x -= dx
            if abs(dx) < 1e-16:
                break
        xs.append(x)
    xs[0], xs[-1] = -1.0, 1.0
    ws = []
    for x in xs:
        _, p = _legendre_pair(n, x)
        ws.append(2.0 / (n * (n + 1) * p * p))
    return xs, ws


def derivative_matrix(xs):
    """Return D with D[i][j] = l_j'(x_i) for the Lagrange basis on the nodes xs."""
    n = len(xs)
    # barycentric weights
    lam = [1.0 / math.prod(xs[j] - xs[k] for k in range(n) if k != j) for j in range(n)]
    D = [[0.0] * n for _ in range(n)]
    for i in range(n):
        for j in range(n):
            if i != j:
                D[i][j] = lam[j] / lam[i] / (xs[i] - xs[j])
        D[i][i] = -sum(D[i][j] for j in range(n) if j != i)  # rows sum to 0
    return D


def lagrange_eval(xs, values, x):
    """Return the interpolating polynomial through (xs, values) at x (barycentric form)."""
    n = len(xs)
    lam = [1.0 / math.prod(xs[j] - xs[k] for k in range(n) if k != j) for j in range(n)]
    num = den = 0.0
    for j in range(n):
        if x == xs[j]:
            return values[j]
        t = lam[j] / (x - xs[j])
        num += t * values[j]
        den += t
    return num / den


def sem_solve(breaks, n, f, c=0.0):
    """Solve -u'' + c u = f with zero end values; return (points, U) at all nodes."""
    xs, ws = gll(n)  # @line L1
    D = derivative_matrix(xs)
    E = len(breaks) - 1
    size = E * n + 1
    A = scimat.zeros(size)
    F = [0.0] * size
    points = [0.0] * size
    for e in range(E):  # @line L2
        a, b = breaks[e], breaks[e + 1]
        h = b - a
        for i in range(n + 1):  # @line L3
            gi = e * n + i
            x = a + h * (xs[i] + 1) / 2
            points[gi] = x
            for j in range(n + 1):
                kij = 2 / h * sum(ws[q] * D[q][i] * D[q][j] for q in range(n + 1))
                A[gi][e * n + j] += kij  # @line L4
            A[gi][gi] += c * h / 2 * ws[i]  # the diagonal mass
            F[gi] += h / 2 * ws[i] * f(x)
    inner = list(range(1, size - 1))
    Ai = [[A[i][j] for j in inner] for i in inner]
    Ui = scimat.solve(Ai, [F[i] for i in inner]) if inner else []  # @line L5
    U = [0.0] + list(Ui) + [0.0]
    return points, U  # @line L6


def evaluate(breaks, n, U, x):
    """Return u_h(x) from the nodal values U of sem_solve."""
    xs, _ = gll(n)
    E = len(breaks) - 1
    e = 0
    while e < E - 1 and x > breaks[e + 1]:
        e += 1
    a, b = breaks[e], breaks[e + 1]
    return lagrange_eval(xs, U[e * n: e * n + n + 1], 2 * (x - a) / (b - a) - 1)
test_spectral_element_method.py 92 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/spectral-element-method/. The authors are listed in prov/6Q7T79.jsonl.

import math
import random

import spectral_element_method as S

PI = math.pi


def u(x):
    return math.sin(PI * x) * math.exp(x)


def f(x):  # -u'' + u
    d2 = math.exp(x) * ((1 - PI * PI) * math.sin(PI * x) + 2 * PI * math.cos(PI * x))
    return -d2 + u(x)


PROBE = [i / 97 for i in range(98)]


def max_error(E, n):
    breaks = [i / E for i in range(E + 1)]
    _, U = S.sem_solve(breaks, n, f, 1.0)
    return max(abs(S.evaluate(breaks, n, U, x) - u(x)) for x in PROBE)


def test_hand_example_one_quadratic_element():
    xs, ws = S.gll(2)
    assert xs == [-1.0, 0.0, 1.0]
    assert max(abs(a - b) for a, b in zip(ws, (1 / 3, 4 / 3, 1 / 3))) < 1e-15
    D = S.derivative_matrix(xs)
    want = [[-1.5, 2.0, -0.5], [-0.5, 0.0, 0.5], [0.5, -2.0, 1.5]]
    assert max(abs(D[i][j] - want[i][j]) for i in range(3) for j in range(3)) < 1e-15
    points, U = S.sem_solve([0.0, 1.0], 2, lambda x: 1.0)
    assert points == [0.0, 0.5, 1.0]
    assert abs(U[1] - 0.125) < 1e-15  # u = x (1 - x) / 2


def test_gll_rule():
    xs, ws = S.gll(4)
    r = math.sqrt(3 / 7)
    assert max(abs(a - b) for a, b in zip(xs, (-1, -r, 0, r, 1))) < 1e-15
    assert max(abs(a - b) for a, b in zip(ws, (0.1, 49 / 90, 32 / 45, 49 / 90, 0.1))) < 1e-15
    for n in (3, 6, 9):
        xs, ws = S.gll(n)
        assert abs(sum(ws) - 2) < 1e-14
        for d in range(2 * n):  # exact up to degree 2n - 1
            exact = 0.0 if d % 2 else 2 / (d + 1)
            assert abs(sum(w * x ** d for x, w in zip(xs, ws)) - exact) < 1e-13
        d = 2 * n  # not exact at degree 2n
        assert abs(sum(w * x ** d for x, w in zip(xs, ws)) - 2 / (d + 1)) > 1e-6


def test_derivative_matrix_is_exact_for_degree_n():
    rng = random.Random(4)
    for n in (3, 7, 12):
        xs, _ = S.gll(n)
        D = S.derivative_matrix(xs)
        coef = [rng.uniform(-1, 1) for _ in range(n + 1)]
        p = [sum(c * x ** k for k, c in enumerate(coef)) for x in xs]
        dp = [sum(k * c * x ** (k - 1) for k, c in enumerate(coef) if k) for x in xs]
        got = [sum(D[i][j] * p[j] for j in range(n + 1)) for i in range(n + 1)]
        assert max(abs(a - b) for a, b in zip(got, dp)) < 1e-10


def test_diagonal_mass_is_the_row_sum_of_the_exact_mass():
    n = 5
    xs, ws = S.gll(n)
    fine_x, fine_w = S.gll(n + 1)  # exact for degree 2n + 1 >= 2n
    basis = [[S.lagrange_eval(xs, [1.0 if k == j else 0.0 for k in range(n + 1)], t) for t in fine_x]
             for j in range(n + 1)]
    exact = [[sum(w * a * b for w, a, b in zip(fine_w, basis[i], basis[j])) for j in range(n + 1)]
             for i in range(n + 1)]
    for i in range(n + 1):
        assert abs(sum(exact[i]) - ws[i]) < 1e-14  # the GLL mass lumps the exact mass
    assert max(abs(exact[i][j]) for i in range(n + 1) for j in range(n + 1) if i != j) > 1e-3


def test_exponential_convergence_in_the_degree():
    errs = [max_error(1, n) for n in (4, 8, 12)]
    assert errs[0] > 1e-3
    assert errs[1] < 1e-5
    assert errs[2] < 1e-9
    assert max_error(2, 10) < 1e-10


def test_algebraic_order_in_h_at_fixed_degree():
    e1, e2 = max_error(8, 2), max_error(16, 2)
    assert 2.7 < math.log2(e1 / e2) < 3.3  # h^(N+1) with N = 2

History

Anthony Patera introduced the spectral element method in 1984 for the incompressible Navier-Stokes equations, combining the geometric flexibility of finite elements with the accuracy of spectral methods. His first version used Chebyshev expansions. With Yvon Maday he developed the Legendre version with GLL nodes and its error analysis in the late 1980s, and Paul Fischer and others built the parallel code that became Nek5000. In the 1990s Dimitri Komatitsch and Jean-Pierre Vilotte brought the method to seismology, where it is now the standard for global wave propagation.

References

  1. Anthony T. Patera, A spectral element method for fluid dynamics: Laminar flow in a channel expansion, Journal of Computational Physics 54(3) (1984) 468-488, the method, with Chebyshev expansions on each element
  2. Michel O. Deville, Paul F. Fischer and Ernest H. Mund, High-Order Methods for Incompressible Fluid Flow, Cambridge University Press (2002), the Legendre spectral element method, the GLL quadrature, the diagonal mass and the tensor product operators
  3. George Em Karniadakis and Spencer J. Sherwin, Spectral/hp Element Methods for Computational Fluid Dynamics, 2nd edition, Oxford University Press (2005), nodal and modal bases, sum factorization and the cost of high order operators

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.average
  • 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