Algorithm Search⌘K

Techniqueadvanced

Quadrature for isogeometric analysis

Also called half-point rule, weighted quadrature.

How to integrate the Galerkin matrices of isogeometric analysis. Gauss rules with p + 1 points per element, and rules that use the spline smoothness to need fewer points.

In isogeometric analysis the Galerkin method needs integrals such as the mass entries Mij=∫ΩRiRj dxM_{ij} = \int_\Omega R_i R_j\,dx and the stiffness entries Kij=∫Ω∇Ri⋅∇Rj dxK_{ij} = \int_\Omega \nabla R_i \cdot \nabla R_j\,dx, where RiR_i are the B-spline or NURBS basis functions mapped to the physical domain by the geometry. They are computed with quadrature. The default, inherited from finite elements, is the tensor Gauss-Legendre rule with p+1p + 1 points per direction on each element. This page shows when that rule is exact and when it is not, and then two methods that use the smoothness of splines to need fewer points: the rule of Hughes, Reali and Sangalli (2010) with one point every two elements, which they call the half-point rule, and the row by row weighted quadrature of Calabrò, Sangalli and Tani (2017). The two are different methods with different aims.

Notation: degree pp in each direction, dd the dimension, elements are the nonempty knot spans, ξ\xi the parametric and x=F(ξ)x = F(\xi) the physical point, J=∂x/∂ξJ = \partial x / \partial \xi the Jacobian matrix. An nn-point Gauss rule has degree of precision 2n−12n - 1 (Gauss quadrature theorem).

In plain words

To build the system of equations, the program must add up products of basis functions over the whole shape. It does this by sampling the products at a few points and adding the samples with weights. The usual way, taken from the finite element method, takes a fixed set of points inside each small piece of the domain. For splines of degree two or three that are smooth across the pieces, this uses more samples than needed, because the samples do not know that the pieces are glued smoothly. Better rules place points across several pieces at once. One rule uses only one point for every two pieces. Another rule changes the weights for each row of the matrix and uses about two points per piece in each direction, whatever the degree.

When it applies

  • You compute Galerkin matrices or load vectors for a spline basis: mass, stiffness, advection or a right-hand side.
  • Element-wise Gauss is the safe default for any basis, any geometry and any coefficient, but it is exact only in the setting given below.
  • The faster rules of this page need extra structure: high smoothness (Cp−1C^{p-1} is the case studied in both papers), often a uniform or tensor product mesh, and a code that can loop over macro-elements or over matrix rows instead of over elements.
  • For trimmed or immersed domains, the integration over cut elements is a separate problem (see trimmed isogeometric analysis and the finite cell method). For collocation no integrals are needed (see isogeometric collocation).

The template

The standard element loop in one parametric dimension, for the mass and stiffness matrices. In dd dimensions the loop over Gauss points runs over the tensor grid of (p+1)d(p + 1)^d points.

  1. ASSEMBLE(knots t, degree p, geometry control points X, weights w)
  2. 1for each element e = [t_k, t_{k+1}] with t_k < t_{k+1}:
  3. 2for each point s_q with weight ω_q of the (p+1)-point Gauss rule on [0, 1]:
  4. 3u ← t_k + (t_{k+1} − t_k) s_q; evaluate N_{k−p..k}(u) and their derivatives, then R = wN/W
  5. 4J ← Σ X_i R_i'(u); dx ← ω_q (t_{k+1} − t_k) J
  6. 5for local a, b: M_ab += R_a R_b dx and K_ab += (R_a'/J)(R_b'/J) dx
  7. 6return M, K (assembled with the global numbers k − p, ..., k of the local functions)

Line L3 can use the Cox-de Boor recursion or Bezier extraction. Line L4 is the derivative of the geometry map x(u)x(u).

When p+1p + 1 Gauss points are exact. Suppose (a) the basis is a B-spline basis, with no rational weights (or with equal weights), (b) the geometry map is affine on each element, x=Aξ+bx = A \xi + b, and (c) the coefficients of the equation are constant. Then the tensor Gauss rule with p+1p + 1 points per direction computes MM and KK exactly.

Proof. On one element each NaN_a is a product of univariate polynomials of degree at most pp in each variable. With an affine map, ∇xNa=A−T∇ξNa\nabla_x N_a = A^{-T} \nabla_\xi N_a and dx=∣det⁡A∣ dξdx = |\det A|\,d\xi with constant AA. So NaNb∣det⁡A∣N_a N_b |\det A| has degree at most 2p2p in each variable, and ∇Na⋅∇Nb∣det⁡A∣\nabla N_a \cdot \nabla N_b |\det A| is a sum of products ∂ξrNa ∂ξsNb\partial_{\xi_r} N_a\, \partial_{\xi_s} N_b times constants, each of degree at most 2p2p in each variable, since a partial derivative lowers the degree in its own variable and keeps the others. The univariate rule with n=p+1n = p + 1 points is exact up to degree 2n−1=2p+12n - 1 = 2p + 1 by the Gauss quadrature theorem. The tensor rule integrates a product x1a1⋯xdadx_1^{a_1} \cdots x_d^{a_d} as the product of the univariate rules, so it is exact for all polynomials of degree at most 2p+12p + 1 in each variable separately. By linearity it is exact for both integrands. □\square

When exactness fails. Each of the three conditions can fail in practice, and then no rule with a fixed number of points per element is exact, or a larger number is needed.

  • Polynomial but not affine geometry. In one dimension with a B-spline map of degree pp, x′(ξ)x'(\xi) has degree p−1p - 1, so the mass integrand NaNbx′N_a N_b x' has degree 3p−13p - 1 and needs ⌈3p/2⌉\lceil 3p/2 \rceil Gauss points. For p=2p = 2 that is still 3 points, but for p=3p = 3 it is 5. In two dimensions det⁡J\det J has degree 2p−12p - 1 in each variable, and the mass integrand degree 4p−14p - 1, which needs 2p2p points per direction. The stiffness integrand contains J−1J^{-1}, a ratio with det⁡J\det J in the denominator, so it is not a polynomial and no Gauss rule is exact.
  • Rational weights. A NURBS function Ra=waNa/WR_a = w_a N_a / W is a ratio of polynomials on each element, unless the weight function WW is constant there. Then no rule of the form ∑ωqf(ξq)\sum \omega_q f(\xi_q) is exact for all the entries.
  • Variable coefficients. ∫c(x)RaRb\int c(x) R_a R_b is exact only if c∘Fc \circ F is a polynomial of low enough degree.

In these cases the p+1p + 1 rule is not exact. It is used because the quadrature error is of higher order than the discretization error for smooth geometry, which is the usual finite element argument with the Strang lemma. This is the standard practice of Hughes, Cottrell and Bazilevs (2005). Hughes, Reali and Sangalli (2010), Appendix, report that on a one-dimensional eigenvalue problem even reduced Gauss rules lose neither stability nor accuracy for the smooth NURBS basis. That is a numerical observation, not a proof.

Hughes, Reali and Sangalli: one point every two elements. Take the uniform mesh of the whole real line with knots jhjh, and the space SS of splines of degree p≥1p \ge 1 with Cp−1C^{p-1} smoothness at every knot (finite sums of the B-splines Nj,pN_{j,p}, with support (jh,(j+p+1)h)(jh, (j + p + 1)h)). Put the points

ξihalf=2ih for p even,ξihalf=(2i+12)h for p odd,i∈Z,\xi^{\mathrm{half}}_i = 2ih \text{ for } p \text{ even}, \qquad \xi^{\mathrm{half}}_i = \big(2i + \tfrac12\big)h \text{ for } p \text{ odd}, \qquad i \in \mathbb{Z},

all with weight 2h2h. Then ∑i2h f(ξihalf)=∫Rf\sum_i 2h\, f(\xi^{\mathrm{half}}_i) = \int_{\mathbb{R}} f for every f∈Sf \in S. This is Section 2 of their paper.

Proof. By linearity it is enough to take f=Nj,pf = N_{j,p}. Its integral is hh: the integral of a B-spline is (tj+p+1−tj)/(p+1)=(p+1)h/(p+1)(t_{j+p+1} - t_j)/(p + 1) = (p + 1)h/(p + 1). Let XX be the set of points and Y=X+hY = X + h. Then X∪Y={x0+kh:k∈Z}X \cup Y = \{x_0 + kh : k \in \mathbb{Z}\} with x0=0x_0 = 0 or h/2h/2, and

∑x∈X∪YNj,p(x)=∑kNj,p(x0+kh)=∑kNj−k,p(x0)=1,\sum_{x \in X \cup Y} N_{j,p}(x) = \sum_k N_{j,p}(x_0 + kh) = \sum_k N_{j-k,p}(x_0) = 1,

by translation of the uniform B-splines and the partition of unity. Now Nj,pN_{j,p} is symmetric about the middle of its support: Nj,p(jh+y)=Nj,p((j+p+1)h−y)N_{j,p}(jh + y) = N_{j,p}((j + p + 1)h - y). The reflection x↦(2j+p+1)h−xx \mapsto (2j + p + 1)h - x maps XX onto YY: for pp even it maps the even multiples of hh to (2j+p+1−2i)h(2j + p + 1 - 2i)h, odd multiples since p+1p + 1 is odd; for pp odd it maps (2i+12)h(2i + \tfrac12)h to (2j+p+12−2i)h(2j + p + \tfrac12 - 2i)h, and p−2ip - 2i is odd, so the image is in X+hX + h. So the sums over XX and over YY are equal, each is 12\tfrac12, and the rule gives 2h⋅12=h2h \cdot \tfrac12 = h. All sums are finite because the support is bounded. □\square

The rule has one point per two elements, while element-wise Gauss needs ⌈(p+1)/2⌉\lceil (p + 1)/2 \rceil points per element for the same functions, which have degree pp on each element. The space has one degree of freedom per element, and the rule uses half of that, which is why the authors call it the half-point rule and state the rule of thumb that optimal rules use about half as many points as the space has functions. The rule is exact for the space SS of degree pp only. A mass integrand NaNbN_a N_b has degree 2p2p and only Cp−1C^{p-1} smoothness, so it is outside SS, and the rule is not exact for it (see the example below). For such integrands Section 3 of the paper computes rules numerically on macro-elements, in two dimensions, for C0C^0 bilinear and C1C^1 biquadratic splines and for mass, stiffness and advection matrices. These rules also use about half as many points as the space has functions.

Calabrò, Sangalli and Tani: weighted quadrature. Write the mass entry as Mij=∫c Bj (Bi dξ)M_{ij} = \int c\, B_j \,(B_i\, d\xi) and treat Bi dξB_i\,d\xi, the test function times the measure, as the weight of the integral. For each row ii, choose a rule Qi(g)=∑qωi,q g(ξq)Q_i(g) = \sum_q \omega_{i,q}\, g(\xi_q) with points shared by all rows and weights for row ii only, and ask that Qi(Bj)=∫BiBj dξQ_i(B_j) = \int B_i B_j\,d\xi for all jj. These conditions are linear in the weights, and only the 2p+12p + 1 functions BjB_j that meet the support of BiB_i matter. In the Cp−1C^{p-1} case the points are the knots and the midpoints of the elements, plus p+1p + 1 points on each boundary element, so there are about 2d2^d points per element in dd dimensions, whatever pp (their Remark 4.1). Then Mij≈Qi(c Bj)M_{ij} \approx Q_i(c\, B_j), exact when cc is constant on a parametric domain. The authors count O(NDOF pd+1)O(N_{\mathrm{DOF}}\, p^{d+1}) floating point operations for the matrix formation, with sum factorization, against O(NDOF p3d)O(N_{\mathrm{DOF}}\, p^{3d}) for element-wise Gauss (Section 1). In their MATLAB tests the time grows at most like NDOF pdN_{\mathrm{DOF}}\, p^d because memory operations dominate, and the convergence rates stay optimal. Both are measured, not proved.

Classic examples

Gauss, exact case. For B-splines of degree p=1,…,4p = 1, \ldots, 4 on 5 uniform elements of [0,1][0, 1], and the map x=3ξx = 3\xi (geometry control points at 3 times the Greville abscissae, which reproduces a linear map), the (p+1)(p + 1)-point rule gives the mass and stiffness matrices to rounding. The pp-point rule gives a mass matrix that is wrong by more than 10−610^{-6}.

Gauss, curved map. Take p=3p = 3, knots (0,0,0,0,14,12,34,1,1,1,1)(0, 0, 0, 0, \tfrac14, \tfrac12, \tfrac34, 1, 1, 1, 1) and a cubic map x(ξ)x(\xi) whose control points are the Greville abscissae moved by small multiples of 1/1001/100. The largest entry error against a 40-point reference is:

Gauss points per element mass error stiffness error
4 (p+1p + 1) 1.0×10−51.0 \times 10^{-5} 3.8×10−43.8 \times 10^{-4}
5 (⌈3p/2⌉\lceil 3p/2 \rceil) rounding (10−1610^{-16}) 2.0×10−52.0 \times 10^{-5}
6 rounding 7.4×10−77.4 \times 10^{-7}
8 rounding 5.1×10−105.1 \times 10^{-10}

The mass integrand has degree 3p−1=83p - 1 = 8, so 5 points are exact. The stiffness integrand Na′Nb′/x′N_a' N_b' / x' is rational, and its error only goes down as points are added.

One point every two elements. For p=2p = 2 the points are 0,±2h,±4h,…0, \pm 2h, \pm 4h, \ldots For the quadratic B-spline on (0,3h)(0, 3h), which has values 0,12,12,00, \tfrac12, \tfrac12, 0 at the knots, the rule picks the point 2h2h and gives 2h⋅12=h2h \cdot \tfrac12 = h, the exact integral. For the shifted B-spline on (h,4h)(h, 4h) it picks 2h2h again, with value 12\tfrac12. For p=1p = 1 the points are 12h,52h,…\tfrac12 h, \tfrac52 h, \ldots, and the hat function on (0,2h)(0, 2h) has the value 12\tfrac12 at 12h\tfrac12 h and 00 at 52h\tfrac52 h, so again hh. Outside the space the rule fails: the p=2p = 2 rule applied to the cubic B-spline on (0,4h)(0, 4h) gives 2h⋅23=43h2h \cdot \tfrac23 = \tfrac43 h instead of hh, and applied to N2N^2 for the quadratic B-spline with h=1h = 1 it gives 12\tfrac12 instead of ∫N2=1120\int N^2 = \tfrac{11}{20}.

Weighted quadrature weights. On a periodic uniform mesh with h=1h = 1 and the test function BiB_i with support (i,i+p+1)(i, i + p + 1), the points are i+12,i+1,…,i+p+12i + \tfrac12, i + 1, \ldots, i + p + \tfrac12 and the exact weights are:

pp weights
1 13,13,13\tfrac13, \tfrac13, \tfrac13
2 115,730,25,730,115\tfrac1{15}, \tfrac7{30}, \tfrac25, \tfrac7{30}, \tfrac1{15}
3 1105,335,521,13,521,335,1105\tfrac1{105}, \tfrac3{35}, \tfrac5{21}, \tfrac13, \tfrac5{21}, \tfrac3{35}, \tfrac1{105}

For p=1p = 1 this is the composite Cavalieri-Simpson rule, as the paper notes. The weights of each row sum to ∫Bi=1\int B_i = 1. They reproduce the mass matrix with c=1c = 1 exactly. With c(ξ)=ξ2c(\xi) = \xi^2 and p=3p = 3 the two entries of rows 3 and 4 are Q3(cB4)=14495920160Q_3(c B_4) = \tfrac{144959}{20160} and Q4(cB3)=160872240=14478320160Q_4(c B_3) = \tfrac{16087}{2240} = \tfrac{144783}{20160}: the matrix is no longer symmetric, which the authors also note (Remark 7.1).

Variations

  • Generalized Gaussian rules. Rules exact for a whole spline space, such as the splines of degree 2p2p with Cp−1C^{p-1} smoothness that contain the mass integrands, with about half as many points as the space has functions. Their points and weights are found numerically, for example by Newton iteration.
  • Reduced Gauss rules. Fewer than p+1p + 1 points per element. Not exact, but reported to be stable and accurate for smooth splines in the Appendix of Hughes, Reali and Sangalli.
  • Sum factorization. Keep element-wise Gauss but compute the element matrices of a tensor product basis one direction at a time (Antolin, Buffa, Calabrò, Martinelli and Sangalli 2015). This lowers the cost without changing the rule.
  • Rules on Bezier elements. With Bezier extraction, the Bernstein values at the Gauss points are tabulated once for each degree.

Pitfalls

  • Exact is not the same as accurate. With a curved map or NURBS weights, no fixed rule is exact. The p+1p + 1 rule is a choice that keeps the convergence rate, not an exact integration.
  • The rule of one point every two elements is for one space. It is exact for splines of degree pp, Cp−1C^{p-1}, on a uniform mesh without boundary. It is not exact for the products in a mass or stiffness matrix, it needs changes near the boundary of a patch and for nonuniform knots, and using it as a mass matrix rule makes the matrix wrong.
  • Too few points make the matrix singular. A rule with fewer points than the rank of the matrix needs (for example a reduced rule on a stiffness matrix) can give spurious zero energy modes, as in classical finite elements. Check the rank or the spectrum.
  • Weighted quadrature changes the code structure. The loop is over rows, the weights depend on the row, and a matrix with a variable coefficient is not symmetric. Codes that rely on symmetry, such as a Cholesky solver, need the symmetric part or another approach.
  • Counting points is not counting time. In the tests of Calabrò, Sangalli and Tani memory operations dominate the time for high pp. Compare wall time, not only the number of points.

Code

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.

isogeometric_quadrature.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/isogeometric-quadrature/. The authors are listed in prov/61XER4.jsonl.

"""Quadrature for isogeometric Galerkin matrices in one parametric dimension.

- assemble: element loop with the n-point Gauss-Legendre rule per element
  (n = p + 1 is the default), for a B-spline or NURBS basis and a spline
  geometry map x(xi), giving the mass and stiffness matrices.
- half_point_rule: the rule of Hughes, Reali and Sangalli for splines of degree
  p and smoothness C^(p-1) on a uniform mesh, one point per two elements.
- weighted_quadrature_weights: the row-wise rule of Calabro, Sangalli and Tani
  for periodic uniform splines, with the knots and midpoints as points.
"""

import math
from fractions import Fraction


def gauss_legendre(n):
    """Nodes and weights of the n-point Gauss-Legendre rule on [0, 1] (floats)."""
    xs, ws = [], []
    for i in range(1, n + 1):
        x = math.cos(math.pi * (i - 0.25) / (n + 0.5))
        for _ in range(100):
            p0, p1 = 1.0, x
            for k in range(2, n + 1):
                p0, p1 = p1, ((2 * k - 1) * x * p1 - (k - 1) * p0) / k
            dp = n * (x * p1 - p0) / (x * x - 1) if n > 1 else 1.0
            dx = p1 / dp
            x -= dx
            if abs(dx) < 1e-16:
                break
        p0, p1 = 1.0, x
        for k in range(2, n + 1):
            p0, p1 = p1, ((2 * k - 1) * x * p1 - (k - 1) * p0) / k
        dp = n * (x * p1 - p0) / (x * x - 1) if n > 1 else 1.0
        xs.append((1 - x) / 2)
        ws.append(1 / ((1 - x * x) * dp * dp))
    return xs, ws


def basis_and_derivative(t, p, k, u):
    """Values and first derivatives of N_{k-p..k, p} at u in span k (de Boor's table)."""
    left, right = [0] * (p + 1), [0] * (p + 1)
    ndu = [[0] * (p + 1) for _ in range(p + 1)]
    ndu[0][0] = 1
    for j in range(1, p + 1):
        left[j] = u - t[k + 1 - j]
        right[j] = t[k + j] - u
        saved = 0
        for r in range(j):
            ndu[j][r] = right[r + 1] + left[j - r]
            tmp = ndu[r][j - 1] / ndu[j][r]
            ndu[r][j] = saved + right[r + 1] * tmp
            saved = left[j - r] * tmp
        ndu[j][j] = saved
    N = [ndu[r][p] for r in range(p + 1)]
    if p == 0:
        return N, [0]
    dN = []
    for r in range(p + 1):
        a = ndu[r - 1][p - 1] / ndu[p][r - 1] if r >= 1 else 0
        b = ndu[r][p - 1] / ndu[p][r] if r <= p - 1 else 0
        dN.append(p * (a - b))
    return N, dN


def spans(t):
    return [k for k in range(len(t) - 1) if t[k] < t[k + 1]]


def assemble(t, p, X, w=None, n_gauss=None, rule=None):
    """Mass and stiffness matrices of the basis on t, with geometry x = sum R_i X_i.

    X are scalar control points of the map, w the weights (None for B-splines).
    rule gives (nodes, weights) on [0, 1]; the default is Gauss with n_gauss points.
    """
    n = len(t) - p - 1
    w = w or [1] * n
    nodes, weights = rule or gauss_legendre(n_gauss or p + 1)
    M = [[0.0] * n for _ in range(n)]
    K = [[0.0] * n for _ in range(n)]
    for k in spans(t):  # @line L1
        a, b = t[k], t[k + 1]
        for s, ws in zip(nodes, weights):  # @line L2
            u = a + (b - a) * s
            N, dN = basis_and_derivative(t, p, k, u)  # @line L3
            loc = range(k - p, k + 1)
            W = sum(w[i] * Ni for i, Ni in zip(loc, N))
            dW = sum(w[i] * di for i, di in zip(loc, dN))
            R = [w[i] * Ni / W for i, Ni in zip(loc, N)]
            dR = [w[i] * (di * W - Ni * dW) / W**2 for i, Ni, di in zip(loc, N, dN)]
            jac = sum(X[i] * di for i, di in zip(loc, dR))  # @line L4
            dx = ws * (b - a) * jac
            for ra, ia in enumerate(loc):  # @line L5
                for rb, ib in enumerate(loc):
                    M[ia][ib] += R[ra] * R[rb] * dx
                    K[ia][ib] += (dR[ra] / jac) * (dR[rb] / jac) * dx
    return M, K  # @line L6


def cardinal_bspline(p, x):
    """The uniform B-spline of degree p with knots 0, 1, ..., p + 1, exactly."""
    x = Fraction(x)
    if x < 0 or x >= p + 1:
        return Fraction(0)
    s = Fraction(0)
    for j in range(p + 2):
        if x - j > 0:
            s += (-1) ** j * math.comb(p + 1, j) * (x - j) ** p
    return s / math.factorial(p)


def half_point_rule(p, h, lo, hi):
    """Points and weights of the half-point rule on [lo, hi], a uniform mesh of size h.

    p even: every other knot; p odd: the midpoint of every other element.
    The weight is 2h. The rule integrates every spline of degree p, C^(p-1),
    on the uniform knots of the whole line, whose support lies in [lo, hi].
    """
    start = Fraction(0) if p % 2 == 0 else Fraction(1, 2)
    pts, x = [], lo + start * h
    while x <= hi:
        pts.append(x)
        x += 2 * h
    return pts, [2 * h] * len(pts)


def solve(A, b):
    """Exact Gauss-Jordan elimination for a square nonsingular system."""
    n = len(A)
    M = [list(A[i]) + [b[i]] for i in range(n)]
    for c in range(n):
        piv = next(i for i in range(c, n) if M[i][c] != 0)
        M[c], M[piv] = M[piv], M[c]
        f = M[c][c]
        M[c] = [v / f for v in M[c]]
        for i in range(n):
            if i != c and M[i][c] != 0:
                g = M[i][c]
                M[i] = [x - g * y for x, y in zip(M[i], M[c])]
    return [M[i][n] for i in range(n)]


def periodic_bspline(p, n, i, x):
    """B-spline i of degree p on the periodic uniform mesh of [0, n] with h = 1."""
    x = Fraction(x) % n
    return sum(cardinal_bspline(p, x - i + n * s) for s in (-2, -1, 0, 1))


def bspline_product_integral(p, d):
    """Exact integral of N(x) N(x - d) for the cardinal B-spline of degree p."""
    total = Fraction(0)
    for a in range(-1, p + 2):
        # on [a, a + 1] the product is a polynomial of degree 2p; Simpson-type
        # exact rule: integrate the interpolant at 2p + 1 equispaced points
        m = 2 * p
        nodes = [a + Fraction(j, m) if m else Fraction(a) for j in range(m + 1)]
        vals = [cardinal_bspline(p, x) * cardinal_bspline(p, x - d) for x in nodes]
        total += newton_cotes(m, vals)
    return total


def newton_cotes(m, vals):
    """Closed Newton-Cotes rule with m + 1 points on an interval of length 1, exact."""
    if m == 0:
        return vals[0]
    xs = [Fraction(j, m) for j in range(m + 1)]
    A = [[x**k for x in xs] for k in range(m + 1)]
    b = [Fraction(1, k + 1) for k in range(m + 1)]
    wts = solve(A, b)
    return sum(wq * v for wq, v in zip(wts, vals))


def weighted_quadrature_weights(p, n, i):
    """Weights of the rule for the test function B_i on the periodic mesh of [0, n].

    The points are the knots and midpoints in the support of B_i, 2p + 1 of them.
    The weights solve sum_q w_q B_j(x_q) = integral of B_i B_j for the 2p + 1
    functions B_j whose support meets the support of B_i.
    """
    pts = [Fraction(i) + Fraction(q, 2) for q in range(1, 2 * p + 2)]
    js = [i + d for d in range(-p, p + 1)]
    A = [[periodic_bspline(p, n, j % n, x) for x in pts] for j in js]
    b = [bspline_product_integral(p, j - i) for j in js]
    return pts, solve(A, b)
test_isogeometric_quadrature.py 155 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/isogeometric-quadrature/. The authors are listed in prov/61XER4.jsonl.

import math
import random
from fractions import Fraction as F

from isogeometric_quadrature import (
    assemble,
    basis_and_derivative,
    cardinal_bspline,
    gauss_legendre,
    half_point_rule,
    newton_cotes,
    periodic_bspline,
    spans,
    weighted_quadrature_weights,
)


def knots(p, n_el):
    return [F(0)] * (p + 1) + [F(i, n_el) for i in range(1, n_el)] + [F(1)] * (p + 1)


def exact_matrices(t, p, c):
    """Mass and stiffness for B-splines and the affine map x = c xi, exactly.

    The integrands are polynomials of degree at most 2p on each span, so the
    closed Newton-Cotes rule with 2p + 1 points is exact.
    """
    n = len(t) - p - 1
    M = [[F(0)] * n for _ in range(n)]
    K = [[F(0)] * n for _ in range(n)]
    m = 2 * p
    for k in spans(t):
        a, b = t[k], t[k + 1]
        tab = [basis_and_derivative(t, p, k, a + (b - a) * F(j, m)) for j in range(m + 1)]
        for ra in range(p + 1):
            for rb in range(p + 1):
                vm = [N[ra] * N[rb] for N, _ in tab]
                vk = [d[ra] * d[rb] for _, d in tab]
                M[k - p + ra][k - p + rb] += (b - a) * newton_cotes(m, vm) * c
                K[k - p + ra][k - p + rb] += (b - a) * newton_cotes(m, vk) / c
    return M, K


def maxdiff(A, B):
    return max(abs(float(x) - float(y)) for ra, rb in zip(A, B) for x, y in zip(ra, rb))


def greville(t, p):
    return [sum(t[i + 1 : i + p + 1]) / p for i in range(len(t) - p - 1)]


def test_gauss_degree_of_exactness():
    for n in range(1, 8):
        xs, ws = gauss_legendre(n)
        for d in range(2 * n):
            assert abs(sum(w * x**d for x, w in zip(xs, ws)) - 1 / (d + 1)) < 1e-13
        assert abs(sum(w * x ** (2 * n) for x, w in zip(xs, ws)) - 1 / (2 * n + 1)) > 1e-9


def test_p_plus_1_gauss_is_exact_for_bsplines_on_an_affine_map():
    for p in (1, 2, 3, 4):
        t = knots(p, 5)
        c = F(3)
        X = [c * g for g in greville(t, p)]  # linear precision: x = 3 xi
        M, K = assemble(t, p, X)
        Me, Ke = exact_matrices(t, p, c)
        assert maxdiff(M, Me) < 1e-12 and maxdiff(K, Ke) < 1e-11
        Mp, _ = assemble(t, p, X, n_gauss=p)  # one point fewer is not exact
        assert maxdiff(Mp, Me) > 1e-6


def test_nonaffine_polynomial_map_needs_more_points():
    p = 3
    t = knots(p, 4)
    rng = random.Random(11)
    X = sorted(g + F(rng.randint(-3, 3), 100) for g in greville(t, p))
    X[0], X[-1] = F(0), F(1)
    ref_M, ref_K = assemble(t, p, X, n_gauss=40)
    M4, K4 = assemble(t, p, X, n_gauss=p + 1)
    M5, K5 = assemble(t, p, X, n_gauss=math.ceil(3 * p / 2))  # degree 3p - 1
    assert maxdiff(M4, ref_M) > 1e-9  # mass integrand has degree 3p - 1 = 8
    assert maxdiff(M5, ref_M) < 1e-12
    assert maxdiff(K5, ref_K) > 1e-9  # stiffness integrand is rational
    K12, _ = assemble(t, p, X, n_gauss=12)[1], None
    assert maxdiff(K12, ref_K) < maxdiff(K5, ref_K)


def test_rational_weights_break_exactness():
    p = 2
    t = knots(p, 3)
    w = [F(1), F(1, 2), F(2), F(1, 2), F(1)]
    X = greville(t, p)
    ref_M, _ = assemble(t, p, X, w=w, n_gauss=40)
    M3, _ = assemble(t, p, X, w=w, n_gauss=p + 1)
    assert maxdiff(M3, ref_M) > 1e-6
    M10, _ = assemble(t, p, X, w=w, n_gauss=10)
    assert maxdiff(M10, ref_M) < maxdiff(M3, ref_M)


def test_half_point_rule_exact_on_uniform_smooth_splines():
    rng = random.Random(12)
    for p in range(1, 7):
        for h in (F(1), F(1, 3)):
            coef = {i: F(rng.randint(-9, 9)) for i in range(-4, 6)}
            f = lambda x: sum(c * cardinal_bspline(p, x / h - i) for i, c in coef.items())
            lo, hi = -6 * h, (p + 8) * h
            pts, wts = half_point_rule(p, h, lo, hi)
            q = sum(w * f(x) for x, w in zip(pts, wts))
            # exact integral by Newton-Cotes with p + 1 points on each element
            exact = sum(h * newton_cotes(p, [f(lo + (e + F(j, p)) * h) for j in range(p + 1)]) for e in range(int((hi - lo) / h)))
            assert q == exact == h * sum(coef.values())
            assert len(pts) <= (hi - lo) / h / 2 + 1  # about one point per two elements


def test_half_point_rule_fails_outside_its_space():
    # the even rule (points at even integers) on a cubic B-spline: 2 * 2/3 != 1
    pts, wts = half_point_rule(2, F(1), F(-2), F(8))
    assert sum(w * cardinal_bspline(3, x) for x, w in zip(pts, wts)) == F(4, 3)
    # and on a mass matrix integrand of degree 2p with C^(p-1) smoothness
    pts, wts = half_point_rule(2, F(1), F(-2), F(8))
    q = sum(w * cardinal_bspline(2, x) ** 2 for x, w in zip(pts, wts))
    assert q != F(11, 20)


def test_weighted_quadrature_reproduces_the_mass_matrix():
    n = 10
    for p in (1, 2, 3):
        for i in (0, 4):
            pts, wts = weighted_quadrature_weights(p, n, i)
            assert len(pts) == 2 * p + 1
            for j in range(n):
                q = sum(w * periodic_bspline(p, n, j, x) for x, w in zip(pts, wts))
                d = (j - i + n // 2) % n - n // 2
                exact = F(0)
                for a in range(-1, p + 2):
                    nodes = [a + F(k, 2 * p) for k in range(2 * p + 1)]
                    exact += newton_cotes(2 * p, [cardinal_bspline(p, x) * cardinal_bspline(p, x - d) for x in nodes])
                assert q == exact
    pts, wts = weighted_quadrature_weights(1, n, 3)
    assert wts == [F(1, 3)] * 3  # composite Cavalieri-Simpson


def test_weighted_quadrature_with_a_coefficient_is_not_symmetric():
    n, p = 10, 3
    c = lambda x: x * x
    m = {}
    for i in (3, 4):
        pts, wts = weighted_quadrature_weights(p, n, i)
        for j in (3, 4):
            m[i, j] = sum(w * c(x) * periodic_bspline(p, n, j, x) for x, w in zip(pts, wts))
    assert m[3, 4] == F(144959, 20160) and m[4, 3] == F(16087, 2240)
    assert m[3, 4] != m[4, 3]

Exercises

  1. Show that the 2-point Gauss rule is exact for the mass and stiffness matrices of linear B-splines on any mesh with an affine map, and that one point is not exact for the mass matrix.
  2. Prove that for a B-spline geometry of degree pp in two dimensions, det⁡J\det J has degree at most 2p−12p - 1 in each variable, and conclude that 2p2p points per direction integrate the mass matrix exactly.
  3. Check the rule of one point every two elements for p=3p = 3 on the cubic B-spline on (0,4h)(0, 4h): list the points in the support, their values, and the sum.
  4. Show that the trapezoidal rule with one point per knot uses twice as many points as needed for continuous piecewise linear functions on a uniform mesh of the whole line.
  5. Derive the weighted quadrature weights 13,13,13\tfrac13, \tfrac13, \tfrac13 for p=1p = 1 from the three exactness conditions Qi(Bi−1)=16Q_i(B_{i-1}) = \tfrac16, Qi(Bi)=23Q_i(B_i) = \tfrac23, Qi(Bi+1)=16Q_i(B_{i+1}) = \tfrac16.

References

  1. T. J. R. Hughes, A. Reali and G. Sangalli, Efficient quadrature for NURBS-based isogeometric analysis, Computer Methods in Applied Mechanics and Engineering 199(5-8), 2010, 301 to 313, Section 1 (Table 1, points per element against continuity), Section 2 (the exact rule with one point every two elements on a uniform mesh, with its proof), Section 3 (rules for macro-elements found numerically) and the Appendix (reduced Gauss rules)
  2. F. Calabrò, G. Sangalli and M. Tani, Fast formation of isogeometric Galerkin matrices by weighted quadrature, Computer Methods in Applied Mechanics and Engineering 316, 2017, 606 to 622, Section 1 (the idea and the cost estimates), Section 2 (the univariate rules), Section 4 (multivariate rules and the choice of points), Section 5 (cost), Section 7 (numerical tests)
  3. T. J. R. Hughes, J. A. Cottrell and Y. Bazilevs, Isogeometric analysis: CAD, finite elements, NURBS, exact geometry and mesh refinement, Computer Methods in Applied Mechanics and Engineering 194(39-41), 2005, 4135 to 4195, the description of the method, element-wise Gauss quadrature on the parametric elements
  4. P. Antolin, A. Buffa, F. Calabrò, M. Martinelli and G. Sangalli, Efficient matrix computation for tensor-product isogeometric analysis: the use of sum factorization, Computer Methods in Applied Mechanics and Engineering 285, 2015, 817 to 828, the whole paper, sum factorization for element-wise Gauss quadrature
  5. J. A. Cottrell, T. J. R. Hughes and Y. Bazilevs, Isogeometric Analysis, Toward Integration of CAD and FEA, Wiley, 2009, Chapter 3 (NURBS as a basis for analysis, p. 69), the numerical integration of the element matrices

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 proofH0 no proof
  • add a proof in proofs/ (06.5)
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
  • three classic examples