Algorithm Search⌘K

Algorithmcore

Boundary element method

Also called BEM, boundary integral equation method, boundary integral method.

Reformulates a linear PDE as an integral equation on the boundary and discretizes only the boundary, giving a dense system with fewer unknowns.

Time
Θ(m^3 + p m) worst
Space
Θ(m^2) extra
Where
m = the number of boundary elements; p = the number of interior points where the solution is evaluated
Properties
dense systemdeterministicnot iterativeneeds fundamental solutionunknowns on boundary only
Origin
M. A. Jaswon, G. T. Symm, F. J. Rizzo, C. A. Brebbia, 1963

The boundary element method solves a linear partial differential equation with a known fundamental solution, such as the Laplace equation, by working only on the boundary of the domain. Green's identity turns the equation into an integral equation that relates the boundary values uu and the normal derivatives q=∂u/∂nq = \partial u/\partial n. The method cuts the boundary into mm elements, takes uu and qq as constant (or polynomial) on each, and enforces the integral equation at one point per element (collocation) or in the mean (Galerkin). Where uu is given it solves for qq and the other way round. The values inside the domain then come from the same integrals. In two dimensions the unknowns are on a curve, so a mesh with mm elements does the work of an area mesh with about m2m^2 elements. The price is a dense matrix with weakly singular entries, which costs Θ(m2)\Theta(m^2) memory and Θ(m3)\Theta(m^3) time for direct elimination unless a fast method such as the fast multipole method applies it.

In plain words

To know the temperature everywhere inside a metal plate at rest, it is enough to know the temperature and the heat flow along its edge. A formula, which comes from the way heat spreads from a single point, gives the inside from the edge. The boundary element method uses this formula backwards. On each piece of the edge, either the temperature or the heat flow is known, and the formula, applied at the edge itself, gives one equation per piece for the unknown values. Solving these equations completes the information on the edge. After that, the formula gives the temperature at any inside point you ask for. Only the edge is cut into pieces, never the inside.

The problem

Input. A bounded domain Ω⊂R2\Omega \subset \mathbb R^2 with a polygonal boundary Γ\Gamma, traversed counterclockwise, and for each part of Γ\Gamma either the value uu (Dirichlet) or the outward normal derivative q=∂u/∂nq = \partial u/\partial n (Neumann). A list of interior points.

Output. Approximations of the missing boundary data and of uu at the interior points, where uu is the solution of Δu=0\Delta u = 0 in Ω\Omega with the given data.

The integral equation. With the fundamental solution G(x,y)=−12πln⁡∣x−y∣G(x, y) = -\frac{1}{2\pi}\ln|x - y| of −Δ-\Delta, Green's second identity gives for x∈Ωx \in \Omega

u(x)=∫ΓG(x,y) q(y) dsy−∫Γ∂G∂ny(x,y) u(y) dsy,u(x) = \int_\Gamma G(x, y)\,q(y)\,ds_y - \int_\Gamma \frac{\partial G}{\partial n_y}(x, y)\,u(y)\,ds_y,

and for xx at a smooth point of Γ\Gamma

12u(x)+∫Γ∂G∂ny(x,y) u(y) dsy=∫ΓG(x,y) q(y) dsy.\tfrac12 u(x) + \int_\Gamma \frac{\partial G}{\partial n_y}(x, y)\,u(y)\,ds_y = \int_\Gamma G(x, y)\,q(y)\,ds_y.

The first integral on the right is the single layer, and the integral on the left is the double layer. A nonzero source term ff in the Poisson equation adds a domain integral of GfG f, or a particular solution can absorb it.

The algorithm

  1. BEM-LAPLACE-2D(boundary, data)
  2. 1cut the boundary into m straight elements; x_i = midpoint of element i
  3. 2for i = 1 to m, for j = 1 to m
  4. 3G[i, j] <- integral over element j of G(x_i, y) ds_y ▷ closed form, weakly singular if i = j
  5. 4H[i, j] <- integral over element j of dG/dn_y(x_i, y) ds_y + 1/2 [i = j]
  6. 5in H u = G q, move the columns of the known values to the right side: A z = b
  7. 6solve A z = b by Gaussian elimination
  8. 7for each interior point x: u(x) <- sum over j of g_j(x) q_j - h_j(x) u_j
  9. 8return u and q on the boundary and the interior values

Closed forms for a straight element. Let the element run from aa to bb with length LL, unit tangent tt and outward normal nn. Write s0=(x−a)⋅ts_0 = (x - a)\cdot t and d=(x−a)⋅nd = (x - a)\cdot n. Then

∫0Lln⁡(s−s0)2+d2 ds=F(L−s0)−F(−s0),F(w)=12wln⁡(w2+d2)−w+darctan⁡(w/d),\int_0^L \ln\sqrt{(s - s_0)^2 + d^2}\,ds = F(L - s_0) - F(-s_0), \qquad F(w) = \tfrac12 w \ln(w^2 + d^2) - w + d \arctan(w/d),

with F(w)=wln⁡∣w∣−wF(w) = w\ln|w| - w when d=0d = 0. The double layer integral is −12π-\frac{1}{2\pi} times the signed angle θj(x)\theta_j(x) under which the element is seen from xx, and it is zero when xx is on the line of the element. So line L3 is exact also for i=ji = j, where it gives 12π L (1−ln⁡(L/2))\frac{1}{2\pi}\,L\,(1 - \ln(L/2)), and the diagonal of line L4 is exactly 12\tfrac12.

Collocation at midpoints. The midpoint of a straight element is a smooth point of Γ\Gamma, so the factor 12\tfrac12 is right there, also on a polygon with corners. At a corner with interior angle ϕ\phi the factor would be ϕ/(2π)\phi/(2\pi).

Example

One element per side. Take the unit square, one element per side in the order bottom, right, top, left, and u=xu = x. The midpoints are (12,0)(\tfrac12, 0), (1,12)(1, \tfrac12), (12,1)(\tfrac12, 1) and (0,12)(0, \tfrac12), so the given values are u=(12,1,12,0)u = (\tfrac12, 1, \tfrac12, 0). Line L3 gives the diagonal Gii=(1+ln⁡2)/(2π)=0.269473G_{ii} = (1 + \ln 2)/(2\pi) = 0.269473, G=0.053294G = 0.053294 for two adjacent sides and G=−0.006186G = -0.006186 for opposite sides. From the midpoint of a side, an adjacent side is seen under the angle arctan⁡2\arctan 2, and the opposite side under 2arctan⁡122\arctan\tfrac12. So line L4 gives Hii=12H_{ii} = \tfrac12, H=−arctan⁡(2)/(2π)=−0.176208H = -\arctan(2)/(2\pi) = -0.176208 for adjacent sides and H=−2arctan⁡(12)/(2π)=−0.147584H = -2\arctan(\tfrac12)/(2\pi) = -0.147584 for opposite sides. Each row of HH sums to 12−(2arctan⁡2+2arctan⁡12)/(2π)=0\tfrac12 - (2\arctan 2 + 2\arctan\tfrac12)/(2\pi) = 0.

By symmetry qq is zero on the bottom and the top and qleft=−qrightq_{\rm left} = -q_{\rm right}. The row of the right side then reads

12⋅1−0.176208⋅12⋅2=(0.269473+0.006186) qright,\tfrac12 \cdot 1 - 0.176208 \cdot \tfrac12 \cdot 2 = (0.269473 + 0.006186)\,q_{\rm right},

so qright=0.323792/0.275659=1.17461q_{\rm right} = 0.323792/0.275659 = 1.17461. The exact flux is 11. The interior value at the centre is exactly 12\tfrac12, by symmetry.

Convergence on the square. For u=exsin⁡yu = e^x \sin y with Dirichlet data on all four sides, the error at the centre is 1.6×10−41.6 \times 10^{-4}, 3.3×10−53.3 \times 10^{-5}, 7.4×10−67.4 \times 10^{-6} and 1.7×10−61.7 \times 10^{-6} with 4, 8, 16 and 32 elements per side, which is second order. With uu given on the bottom and the top and qq on the two other sides, the centre error is 1.6×10−41.6 \times 10^{-4} with 16 elements per side, and it also falls at a rate close to 2. On the elements in the middle third of each side, the flux error is below 2×10−32 \times 10^{-3} with 32 elements per side. On the element next to a corner it stays near 0.240.24 for every mesh: the flux jumps at the corner, and constant elements with collocation at the midpoints do not resolve this.

Correctness

The proofs are in the correctness proof.

  • The boundary integral equation holds for every harmonic uu (theorem). It follows from Green's second identity on Ω\Omega minus a small disc around xx, with the factor 12\tfrac12 from the half disc at a smooth boundary point.
  • The closed forms of lines L3 and L4 are exact (theorem). They come from the antiderivative of ln⁡r\ln r along a line and from the angle formula for the double layer.
  • Each row of HH sums to zero (theorem). The angles under which the other elements are seen from a midpoint add up to π\pi. So a constant uu gives Hu=0H u = 0, and if GG is nonsingular the computed flux of a constant is exactly zero.
  • Solvability and convergence (cited). In two dimensions the single layer operator is elliptic on the right space when the diameter of Ω\Omega is less than 1. Then Galerkin boundary elements converge with the optimal rates (Steinbach 2008). For midpoint collocation with constant elements the analysis is more delicate. The second order at interior points above is a measurement.
Proof: The boundary integral equation, the exact element integrals and the discrete Gauss lawpartial

Setting. Ω⊂R2\Omega \subset \mathbb R^2 is a bounded domain whose boundary Γ\Gamma is a simple closed polygon, traversed counterclockwise, with outward unit normal nn. G(x,y)=−12πln⁡∣x−y∣G(x, y) = -\frac{1}{2\pi}\ln|x - y|, so −ΔyG(x,⋅)=δx-\Delta_y G(x, \cdot) = \delta_x. The function uu is harmonic in Ω\Omega and continuously differentiable up to Γ\Gamma, and q=∂u/∂nq = \partial u/\partial n. The status is partial because the convergence of midpoint collocation is cited, not proved (Remark 2).

Lemma 1 (representation formula). For x∈Ωx \in \Omega, u(x)=∫ΓG(x,y) q(y) dsy−∫Γ∂nyG(x,y) u(y) dsyu(x) = \int_\Gamma G(x, y)\,q(y)\,ds_y - \int_\Gamma \partial_{n_y} G(x, y)\,u(y)\,ds_y.

Proof. Let DϵD_\epsilon be the disc of radius ϵ\epsilon around xx, inside Ω\Omega, and Ωϵ=Ω∖Dϵ‾\Omega_\epsilon = \Omega \setminus \overline{D_\epsilon}. On Ωϵ\Omega_\epsilon both uu and G(x,⋅)G(x, \cdot) are harmonic, so Green's second identity gives ∫∂Ωϵ(G ∂nu−u ∂nG) ds=0\int_{\partial\Omega_\epsilon}(G\,\partial_n u - u\,\partial_n G)\,ds = 0. The boundary of Ωϵ\Omega_\epsilon is Γ\Gamma and the circle ∣y−x∣=ϵ|y - x| = \epsilon, with the normal pointing toward xx on the circle. On the circle G=−12πln⁡ϵG = -\frac{1}{2\pi}\ln\epsilon and ∂nG=12πϵ\partial_n G = \frac{1}{2\pi\epsilon} (the normal points toward xx, where GG grows). So the circle contributes −ln⁡ϵ2π∫∂nu ds−12πϵ∫u ds-\frac{\ln\epsilon}{2\pi}\int \partial_n u\,ds - \frac{1}{2\pi\epsilon}\int u\,ds. The first term is O(ϵln⁡ϵ)O(\epsilon\ln\epsilon) because ∂nu\partial_n u is bounded, and the second tends to −u(x)-u(x) by continuity. Letting ϵ→0\epsilon \to 0 gives ∫Γ(Gq−u ∂nG) ds−u(x)=0\int_\Gamma (G q - u\,\partial_n G)\,ds - u(x) = 0. □\square

Lemma 2 (the boundary equation). For xx on Γ\Gamma in the interior of a straight side, 12u(x)+∫Γ∂nyG(x,y) u(y) dsy=∫ΓG(x,y) q(y) dsy\tfrac12 u(x) + \int_\Gamma \partial_{n_y} G(x, y)\,u(y)\,ds_y = \int_\Gamma G(x, y)\,q(y)\,ds_y, where both integrals exist as ordinary integrals.

Proof. Near xx the side is a line through xx, and for yy on it, (y−x)⋅ny=0(y - x)\cdot n_y = 0, so ∂nyG(x,y)=−(y−x)⋅ny2π∣y−x∣2\partial_{n_y} G(x, y) = -\frac{(y - x)\cdot n_y}{2\pi|y - x|^2} vanishes there. Away from xx the kernel is bounded. So the double layer integral is an ordinary integral, and the single layer integral exists because ln⁡∣x−y∣\ln|x - y| is integrable on a line. Repeat the proof of Lemma 1 with Ωϵ=Ω∖Dϵ‾\Omega_\epsilon = \Omega \setminus \overline{D_\epsilon} for this boundary point. For small ϵ\epsilon the part of the circle inside Ω\Omega is a half circle, so the term 12πϵ∫u ds\frac{1}{2\pi\epsilon}\int u\,ds over it tends to 12u(x)\tfrac12 u(x), and the logarithmic term tends to 0. The part of Γ\Gamma cut out by the disc has length 2ϵ2\epsilon, and its contribution tends to 0 because the double layer kernel is zero there and ∫−ϵϵ∣ln⁡∣s∣∣ ds→0\int_{-\epsilon}^{\epsilon}|\ln|s||\,ds \to 0. □\square

Lemma 3 (closed forms). Let a straight element run from aa to bb with length LL, unit tangent tt, normal n=(t2,−t1)n = (t_2, -t_1), and let s0=(x−a)⋅ts_0 = (x - a)\cdot t and d=(x−a)⋅nd = (x - a)\cdot n. Then ∫0Lln⁡(s−s0)2+d2 ds=F(L−s0)−F(−s0)\int_0^L \ln\sqrt{(s - s_0)^2 + d^2}\,ds = F(L - s_0) - F(-s_0) with FF as on the page, and ∫(y−x)⋅n/∣y−x∣2 dsy=−θ\int (y - x)\cdot n / |y - x|^2\,ds_y = -\theta, where θ\theta is the angle at xx between a−xa - x and b−xb - x, taken with the sign of dd.

Proof. With y=a+s ty = a + s\,t we have y−x=(s−s0) t−d ny - x = (s - s_0)\,t - d\,n, so ∣y−x∣2=(s−s0)2+d2|y - x|^2 = (s - s_0)^2 + d^2. Put w=s−s0w = s - s_0. For d≠0d \ne 0, F′(w)=12ln⁡(w2+d2)+w2w2+d2−1+d2w2+d2=ln⁡w2+d2F'(w) = \tfrac12\ln(w^2 + d^2) + \frac{w^2}{w^2 + d^2} - 1 + \frac{d^2}{w^2 + d^2} = \ln\sqrt{w^2 + d^2}. For d=0d = 0, ddw(wln⁡∣w∣−w)=ln⁡∣w∣\frac{d}{dw}(w\ln|w| - w) = \ln|w|, and the integral is improper but finite at w=0w = 0. For the second integral, (y−x)⋅n=−d(y - x)\cdot n = -d, so it equals −∫−s0L−s0d dww2+d2=−[arctan⁡(w/d)]-\int_{-s_0}^{L - s_0}\frac{d\,dw}{w^2 + d^2} = -\big[\arctan(w/d)\big]. The bracket is the angle swept by the direction of y−xy - x as yy moves from aa to bb. Its absolute value is the angle between a−xa - x and b−xb - x, which is less than π\pi, and its sign is that of dd. For d=0d = 0 both sides are zero. □\square

The reference code uses exactly these formulas, with h=−12π∫(y−x)⋅n/∣y−x∣2 dsh = -\frac{1}{2\pi}\int (y - x)\cdot n/|y - x|^2\,ds, so lines L3 and L4 are exact up to rounding. At xx the midpoint of its own element, s0=L/2s_0 = L/2, d=0d = 0, and F(L/2)−F(−L/2)=Lln⁡(L/2)−LF(L/2) - F(-L/2) = L\ln(L/2) - L.

Theorem 1 (discrete Gauss law). Let xix_i be the midpoint of element ii. Then ∑jHij=0\sum_j H_{ij} = 0. So HH applied to a constant vector is zero, and if GG is nonsingular, the computed qq for constant Dirichlet data is zero.

Proof. Apply Lemma 2 to u=1u = 1, which is harmonic with q=0q = 0: 12+∫Γ∂nyG(xi,y) dsy=0\tfrac12 + \int_\Gamma \partial_{n_y} G(x_i, y)\,ds_y = 0. The integral over Γ\Gamma is the sum of the integrals over the elements, which are the off diagonal HijH_{ij} by Lemma 3 (and zero for j=ij = i). So 12+∑j≠iHij=0\tfrac12 + \sum_{j \ne i} H_{ij} = 0, which is ∑jHij=0\sum_j H_{ij} = 0 since Hii=12H_{ii} = \tfrac12. Note that this is an identity of exact integrals, not an approximation: the double layer of a constant is computed exactly. With constant data uj=cu_j = c, the system of line L5 is Gq=Hu=0G q = H u = 0, so q=0q = 0 if GG is nonsingular. □\square

Corollary 1. At an interior point xx, the same argument with Lemma 1 gives ∑jhj(x)=−1\sum_j h_j(x) = -1, so line L7 returns exactly cc for constant data. The reference tests check both identities to 10−1410^{-14}.

Remark 1 (the kernel of the single layer). On the circle of radius RR, 12πR∫∣y∣=Rln⁡∣x−y∣ dsy=ln⁡R\frac{1}{2\pi R}\int_{|y| = R}\ln|x - y|\,ds_y = \ln R for ∣x∣=R|x| = R (the mean value of ln⁡∣x−y∣\ln|x - y| over a circle through xx). So the constant density lies in the kernel of the single layer for R=1R = 1. Scaling the domain so that its diameter is less than 1 makes the single layer operator elliptic on H−1/2(Γ)H^{-1/2}(\Gamma) (Steinbach 2008).

Remark 2 (convergence, cited). For the Galerkin method with the single layer operator and piecewise constants, ellipticity and Cea's lemma give quasi optimal convergence in H−1/2(Γ)H^{-1/2}(\Gamma) (Steinbach 2008). The midpoint collocation of the code is the classical method of Symm. Its error at interior points, second order in the element length on the square, is measured by the reference tests and is not proved here.

Complexity

In the real-RAM model, lines L2 to L4 compute m2m^2 entries of two matrices, each in constant time, so Θ(m2)\Theta(m^2) time and space. Line L6 is dense Gaussian elimination, Θ(m3)\Theta(m^3) time. Line L7 costs Θ(m)\Theta(m) per interior point. In total, Θ(m3+pm)\Theta(m^3 + p m) time and Θ(m2)\Theta(m^2) extra space. An iterative solver such as GMRES with kk iterations costs Θ(km2)\Theta(k m^2), and with the fast multipole method one matrix vector product costs about Θ(m)\Theta(m) for a fixed accuracy, so large problems are solved in nearly linear time.

Properties

  • One dimension less. Only the boundary is meshed. For exterior problems, such as the field around a body in all of space, no truncation of the domain is needed, because GG already satisfies the condition at infinity.
  • Dense and not symmetric. Collocation gives a dense nonsymmetric matrix. Galerkin boundary elements give a symmetric system for the single layer equation, at the price of double integrals.
  • Exact interior representation. Once uu and qq are known on Γ\Gamma, line L7 gives uu and its derivatives at any interior point with no interpolation, and the result is harmonic.
  • Needs a fundamental solution. The method works for the Laplace, Helmholtz, Stokes and linear elasticity equations with constant coefficients. Variable coefficients and nonlinear terms bring back domain integrals.

Variants and improvements

  • Galerkin boundary elements. Test the integral equation with the basis functions. This gives the full stability and convergence theory, symmetric systems for the symmetric formulation, and better accuracy near corners.
  • Higher order elements. Linear or quadratic uu and qq on curved elements. At corners, two values of qq per node (double nodes) handle the jump of the normal.
  • Indirect method. Write uu as a single or double layer potential of an unknown density, solve for the density, then evaluate. A second kind equation with the double layer is well conditioned.
  • Fast methods. The fast multipole method, hierarchical matrices and panel clustering apply or compress the dense matrix in nearly linear time and memory.
  • Coupling with finite elements. Finite elements in a bounded region with nonlinear material and boundary elements for the linear exterior.

When to use it

Use it for linear problems with constant coefficients on domains whose boundary is much smaller than their volume: exterior acoustics and electromagnetics, potential flow around bodies, electrostatics, and fracture and contact problems where only surface values matter. Use finite elements for nonlinear materials, variable coefficients or when the whole field is needed on a fine grid. For more than a few thousand elements, a fast method is necessary, because the dense matrix grows with m2m^2.

Pitfalls

  • The 2D single layer at scale 1. On the unit circle, ∫Γln⁡∣x−y∣ dsy=0\int_\Gamma \ln|x - y|\,ds_y = 0 for xx on Γ\Gamma, so the constant density is in the kernel of the single layer and GG is nearly singular. In general this happens when the logarithmic capacity of Γ\Gamma is 1. Scale the domain so that its diameter is less than 1. The reference test shows the row sums of GG are below 2×10−32 \times 10^{-3} on the unit circle and about 0.3470.347 on the circle of radius 12\tfrac12.
  • Near singular integrals. For interior points close to the boundary, or for thin domains, the kernels vary fast along nearby elements and low order quadrature fails. Use the closed forms or adaptive quadrature.
  • Corners. The normal jumps at a corner, so qq is discontinuous there. Constant elements on each side handle this, but the flux next to a corner converges slowly or not at all in the maximum norm.
  • Orientation. The sign of the double layer depends on the direction of the normal. A clockwise boundary flips every HijH_{ij} with i≠ji \ne j, and the solution is wrong with no error message. The row sum test catches it.
  • Cost of the dense matrix. With m=105m = 10^5 elements the matrix has 101010^{10} entries. Without a fast method the method is limited to small problems.

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.

boundary_element_method.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/boundary-element-method/. The authors are listed in prov/03WMHA.jsonl.

"""Direct boundary element method for the 2D Laplace equation, constant elements.

The boundary is a closed polygon, traversed counterclockwise, cut into M
straight elements. On each element u and the outward normal derivative
q = du/dn are constant, and the boundary integral equation

    (1/2) u(x) + int_G dG/dn_y(x, y) u(y) ds_y = int_G G(x, y) q(y) ds_y,
    G(x, y) = -(1 / (2 pi)) ln |x - y|,

is collocated at the element midpoints. The integrals over straight elements
are computed in closed form, including the weakly singular one.
"""

import math

import scimat


def segment_integrals(x, a, b):
    """Return (g, h) = (int G(x, y) ds_y, int dG/dn_y(x, y) ds_y) over the segment a b.

    The normal of the segment is the outward normal of a counterclockwise
    boundary: n = (t_y, -t_x) for the unit tangent t from a to b.
    The formula holds for any point x, also on the segment.
    """
    length = math.hypot(b[0] - a[0], b[1] - a[1])
    tx, ty = (b[0] - a[0]) / length, (b[1] - a[1]) / length
    nx, ny = ty, -tx
    rx, ry = x[0] - a[0], x[1] - a[1]
    s0 = rx * tx + ry * ty  # projection of x on the line
    d = rx * nx + ry * ny  # signed distance of x from the line

    def prim(u):
        # antiderivative of ln sqrt(u^2 + d^2) in u
        if d == 0:
            return u * math.log(abs(u)) - u if u != 0 else 0.0
        return 0.5 * u * math.log(u * u + d * d) - u + d * math.atan(u / d)

    ln_int = prim(length - s0) - prim(-s0)
    g = -ln_int / (2 * math.pi)
    # int (y - x) . n / r^2 ds is the signed angle that the segment subtends at x
    ax, ay = a[0] - x[0], a[1] - x[1]
    bx, by = b[0] - x[0], b[1] - x[1]
    if d == 0:
        angle = 0.0
    else:
        angle = math.atan2(ax * by - ay * bx, ax * bx + ay * by)
        # the kernel (y - x) . n / r^2 equals -d / r^2, so the sign is that of -d
        angle = -abs(angle) if d > 0 else abs(angle)
    h = -angle / (2 * math.pi)
    return g, h


def polygon_elements(vertices, per_side):
    """Cut a counterclockwise polygon into per_side equal elements per side."""
    elems = []
    nv = len(vertices)
    for k in range(nv):
        p, r = vertices[k], vertices[(k + 1) % nv]
        for j in range(per_side):
            s, t = j / per_side, (j + 1) / per_side
            elems.append(((p[0] + s * (r[0] - p[0]), p[1] + s * (r[1] - p[1])), (p[0] + t * (r[0] - p[0]), p[1] + t * (r[1] - p[1]))))
    return elems


def midpoint(e):
    return ((e[0][0] + e[1][0]) / 2, (e[0][1] + e[1][1]) / 2)


def outward_normal(e):
    (ax, ay), (bx, by) = e
    length = math.hypot(bx - ax, by - ay)
    return ((by - ay) / length, -(bx - ax) / length)


def assemble(elems):
    """Return the M by M matrices G and H of the collocation system (H includes 1/2 I)."""
    m = len(elems)
    g = scimat.zeros(m)
    h = scimat.zeros(m)
    for i in range(m):  # @line L2
        xi = midpoint(elems[i])
        for j in range(m):
            gij, hij = segment_integrals(xi, elems[j][0], elems[j][1])
            g[i][j] = gij  # @line L3
            h[i][j] = hij + (0.5 if i == j else 0.0)  # @line L4
    return g, h


def bem_solve(elems, kinds, values):
    """Solve the mixed problem. kinds[j] is 'u' (u given) or 'q' (q given) on element j.

    Return (u, q, (G, H)): the boundary values of u and q on all elements.
    """
    m = len(elems)  # @line L1
    g, h = assemble(elems)
    # H u = G q; move the known values to the right side
    a = scimat.zeros(m)
    rhs = [0.0] * m
    for j in range(m):  # @line L5
        for i in range(m):
            if kinds[j] == "u":
                a[i][j] = -g[i][j]
                rhs[i] -= h[i][j] * values[j]
            else:
                a[i][j] = h[i][j]
                rhs[i] += g[i][j] * values[j]
    z = scimat.solve(a, rhs)  # @line L6
    u = [values[j] if kinds[j] == "u" else z[j] for j in range(m)]
    q = [z[j] if kinds[j] == "u" else values[j] for j in range(m)]
    return u, q, (g, h)


def interior_value(x, elems, u, q):
    """Return u(x) = sum_j (g_j(x) q_j - h_j(x) u_j) at a point x inside the domain."""
    total = 0.0
    for e, uj, qj in zip(elems, u, q):
        gj, hj = segment_integrals(x, e[0], e[1])
        total += gj * qj - hj * uj  # @line L7
    return total


def dirichlet(vertices, per_side, u_exact, points):
    """Solve the Dirichlet problem with boundary data u_exact; return (q, values at points)."""
    elems = polygon_elements(vertices, per_side)
    u_bc = [u_exact(*midpoint(e)) for e in elems]
    u, q, _ = bem_solve(elems, ["u"] * len(elems), u_bc)
    return q, [interior_value(p, elems, u, q) for p in points]  # @line L8
scimat.py 227 lines
# SPDX-License-Identifier: MIT
# Shared helper of the scientific-computing pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small dense linear algebra and error norms for the scientific-computing pages.

A matrix is a list of rows and a vector is a list. Entries may be int,
float or fractions.Fraction. The routines that do not take a square root
(solve, inv, det and the arithmetic) keep Fraction entries exact.
cholesky, cholesky_solve and norm2 take square roots and return floats.

API (fixed; other pages copy this file byte for byte):
    zeros(m, n=None)        m by n zero matrix (n = m if not given)
    eye(n)                  n by n identity
    add(A, B), sub(A, B)    entrywise sum and difference (vectors or matrices)
    scale(c, A)             c times A (vector or matrix)
    matmul(A, B)            matrix product
    matvec(A, x)            matrix times vector
    transpose(A)            transpose
    dot(x, y)               inner product of two vectors
    norm2(x)                Euclidean norm of a vector, as a float
    outer(x, y)             outer product x y^T
    solve(A, b)             Gaussian elimination with partial pivoting;
                            b is a vector or a matrix of right sides
    inv(A)                  inverse of A
    det(A)                  determinant of A
    cholesky(A)             lower triangular L with A = L L^T (floats)
    cholesky_solve(L, b)    solve L L^T x = b for a vector b
    err_l1(e, dx=1)         sum |e_j| dx
    err_l2(e, dx=1)         sqrt(sum e_j^2 dx), as a float
    err_linf(e, dx=1)       max |e_j| (dx is not used)
    observed_order(errors)  [log2(E_i / E_(i+1)) for successive errors]
"""

import math


def zeros(m, n=None):
    """Return an m by n matrix of zeros (n = m if n is None)."""
    if n is None:
        n = m
    return [[0] * n for _ in range(m)]


def eye(n):
    """Return the n by n identity matrix."""
    out = zeros(n, n)
    for i in range(n):
        out[i][i] = 1
    return out


def _is_matrix(a):
    return len(a) > 0 and isinstance(a[0], list)


def add(a, b):
    """Return a + b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x + y for x, y in zip(a, b)]


def sub(a, b):
    """Return a - b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x - y for x, y in zip(a, b)]


def scale(c, a):
    """Return c times a, for a vector or a matrix a."""
    if _is_matrix(a):
        return [[c * x for x in row] for row in a]
    return [c * x for x in a]


def transpose(a):
    """Return the transpose of the matrix a."""
    return [list(col) for col in zip(*a)]


def matmul(a, b):
    """Return the matrix product a b."""
    bt = transpose(b)
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def matvec(a, x):
    """Return the product of the matrix a and the vector x."""
    return [sum(aij * xj for aij, xj in zip(row, x)) for row in a]


def dot(x, y):
    """Return the inner product of the vectors x and y."""
    return sum(a * b for a, b in zip(x, y))


def norm2(x):
    """Return the Euclidean norm of the vector x, as a float."""
    return math.sqrt(float(dot(x, x)))


def outer(x, y):
    """Return the outer product x y^T as a matrix."""
    return [[a * b for b in y] for a in x]


def _eliminate(a, rhs):
    """Reduce a to upper triangular form with partial pivoting.

    a is a copy of the square matrix, rhs a list of right side rows (one
    row per row of a) that receives the same row operations. Return the
    number of row swaps. Raise ValueError if a pivot is zero.
    """
    n = len(a)
    swaps = 0
    for k in range(n):
        p = max(range(k, n), key=lambda i: abs(a[i][k]))
        if a[p][k] == 0:
            raise ValueError("matrix is singular")
        if p != k:
            a[k], a[p] = a[p], a[k]
            rhs[k], rhs[p] = rhs[p], rhs[k]
            swaps += 1
        for i in range(k + 1, n):
            f = a[i][k] / a[k][k]
            if f == 0:
                continue
            for j in range(k, n):
                a[i][j] -= f * a[k][j]
            for j in range(len(rhs[i])):
                rhs[i][j] -= f * rhs[k][j]
    return swaps


def solve(a, b):
    """Solve a x = b by Gaussian elimination with partial pivoting.

    b is a vector (the result is a vector) or a matrix with one column per
    right side (the result is a matrix). Fraction entries stay exact.
    Raise ValueError if a is singular.
    """
    n = len(a)
    work = [list(row) for row in a]
    vector = not _is_matrix(b)
    rhs = [[v] for v in b] if vector else [list(row) for row in b]
    _eliminate(work, rhs)
    m = len(rhs[0]) if n else 0
    x = [[0] * m for _ in range(n)]
    for i in range(n - 1, -1, -1):
        for j in range(m):
            s = rhs[i][j]
            for k in range(i + 1, n):
                s -= work[i][k] * x[k][j]
            x[i][j] = s / work[i][i]
    if vector:
        return [row[0] for row in x]
    return x


def inv(a):
    """Return the inverse of the square matrix a."""
    return solve(a, eye(len(a)))


def det(a):
    """Return the determinant of the square matrix a (0 if singular)."""
    work = [list(row) for row in a]
    rhs = [[] for _ in a]
    try:
        swaps = _eliminate(work, rhs)
    except ValueError:
        return 0
    d = -1 if swaps % 2 else 1
    for i in range(len(a)):
        d *= work[i][i]
    return d


def cholesky(a):
    """Return the lower triangular L with a = L L^T, in floats.

    Raise ValueError if a is not symmetric positive definite.
    """
    n = len(a)
    low = [[0.0] * n for _ in range(n)]
    for j in range(n):
        s = float(a[j][j]) - sum(low[j][k] ** 2 for k in range(j))
        if s <= 0.0:
            raise ValueError("matrix is not positive definite")
        low[j][j] = math.sqrt(s)
        for i in range(j + 1, n):
            t = float(a[i][j]) - sum(low[i][k] * low[j][k] for k in range(j))
            low[i][j] = t / low[j][j]
    return low


def cholesky_solve(low, b):
    """Solve L L^T x = b, with L from cholesky, for a vector b."""
    n = len(low)
    y = [0.0] * n
    for i in range(n):
        y[i] = (float(b[i]) - sum(low[i][k] * y[k] for k in range(i))) / low[i][i]
    x = [0.0] * n
    for i in range(n - 1, -1, -1):
        x[i] = (y[i] - sum(low[k][i] * x[k] for k in range(i + 1, n))) / low[i][i]
    return x


def err_l1(e, dx=1):
    """Return the discrete L1 norm sum |e_j| dx."""
    return sum(abs(v) for v in e) * dx


def err_l2(e, dx=1):
    """Return the discrete L2 norm sqrt(sum e_j^2 dx), as a float."""
    return math.sqrt(float(sum(v * v for v in e) * dx))


def err_linf(e, dx=1):
    """Return the max norm max |e_j|. dx is accepted for a uniform call and not used."""
    return max(abs(v) for v in e)


def observed_order(errors):
    """Return [log2(E_i / E_(i+1))] for a list of errors on meshes h, h/2, h/4, ..."""
    return [math.log2(float(errors[i]) / float(errors[i + 1])) for i in range(len(errors) - 1)]
test_boundary_element_method.py 126 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/boundary-element-method/. The authors are listed in prov/03WMHA.jsonl.

import math

import scimat
from boundary_element_method import (
    assemble,
    bem_solve,
    dirichlet,
    interior_value,
    midpoint,
    outward_normal,
    polygon_elements,
    segment_integrals,
)

SQUARE = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)]


def u_exp(x, y):
    return math.exp(x) * math.sin(y)


def q_exp(e):
    (x, y), (nx, ny) = midpoint(e), outward_normal(e)
    return math.exp(x) * (math.sin(y) * nx + math.cos(y) * ny)


def brute_force(x, a, b, n=20000):
    length = math.hypot(b[0] - a[0], b[1] - a[1])
    nx, ny = outward_normal((a, b))
    g = h = 0.0
    for k in range(n):
        s = (k + 0.5) / n
        rx, ry = a[0] + s * (b[0] - a[0]) - x[0], a[1] + s * (b[1] - a[1]) - x[1]
        r2 = rx * rx + ry * ry
        g += -math.log(r2) / (4 * math.pi) * length / n
        h += -(rx * nx + ry * ny) / r2 / (2 * math.pi) * length / n
    return g, h


def test_segment_integrals_against_quadrature():
    a, b = (0.2, 0.1), (0.9, 0.5)
    for x in [(0.4, 0.6), (0.6, 0.2), (-1.0, 3.0), (2.0, 0.0)]:
        g, h = segment_integrals(x, a, b)
        g2, h2 = brute_force(x, a, b)
        assert abs(g - g2) < 1e-8 and abs(h - h2) < 1e-8


def test_self_integral_closed_form():
    # x at the midpoint of its own element: int ln r ds = L ln(L / 2) - L, and the double layer is 0
    a, b = (0.0, 0.0), (0.3, 0.4)
    g, h = segment_integrals(midpoint((a, b)), a, b)
    assert abs(g + (0.5 * math.log(0.25) - 0.5) / (2 * math.pi)) < 1e-15
    assert h == 0.0


def test_gauss_law_for_the_double_layer():
    elems = polygon_elements(SQUARE, 5)
    _, h = assemble(elems)
    # with the 1/2 on the diagonal, every row of H sums to zero: constants are in its kernel
    assert max(abs(sum(row)) for row in h) < 1e-14
    # at an interior point the double layer of the constant 1 is -1
    total = sum(segment_integrals((0.3, 0.6), e[0], e[1])[1] for e in elems)
    assert abs(total + 1) < 1e-14


def test_constant_solution_has_zero_flux():
    elems = polygon_elements(SQUARE, 8)
    u, q, _ = bem_solve(elems, ["u"] * len(elems), [1.0] * len(elems))
    assert max(abs(v) for v in q) < 1e-12
    assert abs(interior_value((0.4, 0.7), elems, u, q) - 1) < 1e-13


def test_dirichlet_interior_values_converge_at_second_order():
    errs = []
    for per_side in (4, 8, 16, 32):
        _, vals = dirichlet(SQUARE, per_side, u_exp, [(0.5, 0.5)])
        errs.append(abs(vals[0] - u_exp(0.5, 0.5)))
    assert errs[-1] < 2e-6
    assert all(r > 1.9 for r in scimat.observed_order(errs))


def test_flux_away_from_corners_and_at_corners():
    per_side = 32
    elems = polygon_elements(SQUARE, per_side)
    u, q, _ = bem_solve(elems, ["u"] * len(elems), [u_exp(*midpoint(e)) for e in elems])
    err = [abs(qq - q_exp(e)) for e, qq in zip(elems, q)]
    # elements in the middle third of each side
    middle = [err[k * per_side + j] for k in range(4) for j in range(per_side // 3, 2 * per_side // 3)]
    assert max(middle) < 2e-3
    # the element next to the corner (1, 0) keeps an error of order one with constant elements
    assert err[per_side - 1] > 0.1


def test_mixed_problem():
    errs = []
    for per_side in (4, 8, 16):
        elems = polygon_elements(SQUARE, per_side)
        kinds, values = [], []
        for e in elems:
            (x, y), (nx, ny) = midpoint(e), outward_normal(e)
            if abs(ny) > 0.5:  # bottom and top: u given
                kinds.append("u")
                values.append(u_exp(x, y))
            else:  # left and right: q given
                kinds.append("q")
                values.append(q_exp(e))
        u, q, _ = bem_solve(elems, kinds, values)
        errs.append(abs(interior_value((0.5, 0.5), elems, u, q) - u_exp(0.5, 0.5)))
    assert errs[-1] < 2e-4
    assert all(r > 1.5 for r in scimat.observed_order(errs))


def test_unit_circle_makes_the_single_layer_nearly_singular():
    # On a circle of radius R, int ln |x - y| ds_y = 2 pi R ln R for x on the circle,
    # so for R = 1 the constant density is (almost) in the kernel of G.
    results = {}
    for radius in (1.0, 0.5):
        n = 64
        verts = [(radius * math.cos(2 * math.pi * k / n), radius * math.sin(2 * math.pi * k / n)) for k in range(n)]
        g, _ = assemble(polygon_elements(verts, 1))
        results[radius] = max(abs(sum(row)) for row in g)
    assert results[1.0] < 2e-3
    assert abs(results[0.5] - (-0.5 * math.log(0.5))) < 1e-3

History

Jaswon and Symm in 1963 wrote potential problems as boundary integral equations and solved them on a computer with piecewise constant densities. Rizzo in 1967 did the same for elastostatics with the direct formulation, which uses the boundary values themselves as unknowns. Brebbia in 1978 named it the boundary element method and showed its relation to finite elements. The fast multipole method of Greengard and Rokhlin from 1987 removed the quadratic cost of the dense matrix and made large problems possible.

References

  1. M. A. Jaswon, Integral equation methods in potential theory. I, Proceedings of the Royal Society of London A 275(1360) (1963) 23-32, the boundary integral equations of potential theory with the single and double layer
  2. G. T. Symm, Integral equation methods in potential theory. II, Proceedings of the Royal Society of London A 275(1360) (1963) 33-46, the numerical solution with piecewise constant densities and collocation at boundary points
  3. F. J. Rizzo, An integral equation approach to boundary value problems of classical elastostatics, Quarterly of Applied Mathematics 25(1) (1967) 83-95, the direct boundary integral formulation of elastostatics, with the boundary displacements and tractions as unknowns
  4. Olaf Steinbach, Numerical Approximation Methods for Elliptic Boundary Value Problems, Finite and Boundary Elements, Springer, 2008, the representation formula, the boundary integral operators and their mapping properties, the ellipticity of the 2D single layer operator after scaling, and the boundary element methods
  5. L. Greengard and V. Rokhlin, A fast algorithm for particle simulations, Journal of Computational Physics 73(2) (1987) 325-348, the fast multipole method, which applies the dense boundary element matrix in nearly linear time

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 correctness
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example