Algorithm Search⌘K

Algorithmadvanced

Element-free Galerkin method

Also called EFG method, element free Galerkin method.

A meshfree Galerkin method with moving least squares shape functions built from scattered nodes, with no element connectivity.

Time
Θ(g (k m^2 + m^3 + k^2) + n k^2) worst
Space
Θ(n k) extra
Where
g = the number of quadrature points; k = the number of nodes whose support covers a point; m = the size of the polynomial basis; n = the number of nodes
Properties
deterministicnot iterativenot kronecker delta propertymeshfreeneeds background quadraturereproduces polynomials of the basis
Origin
T. Belytschko, Y. Y. Lu, L. Gu, B. Nayroles, P. Lancaster, K. Salkauskas, 1994

The element-free Galerkin (EFG) method solves a boundary value problem with the Galerkin method on a set of scattered nodes, without elements. Each node II has a weight function wIw_I with compact support of radius dId_I. At any point xx, a moving least squares (MLS) fit of a polynomial basis p(x)p(x) to the nodal parameters, weighted by the wI(x)w_I(x), defines the shape functions ϕI(x)\phi_I(x). They reproduce every polynomial in the basis exactly, they are as smooth as the weights, and they need only the nodes whose supports cover xx. The stiffness matrix is assembled by Gauss quadrature on a background grid of cells that does not need to match the nodes. The shape functions do not satisfy ϕI(xJ)=δIJ\phi_I(x_J) = \delta_{IJ}, so Dirichlet conditions are imposed weakly, with Lagrange multipliers, a penalty or Nitsche's method. The method suits problems where a mesh is a burden: large deformations, crack growth and adaptive refinement by adding nodes.

In plain words

A finite element program joins the points of a model into small triangles or boxes, and it must keep this mesh valid as the model changes. The element-free Galerkin method keeps only the points. Each point has a small zone of influence. To know the solution at some place, the method looks at the points whose zones cover that place and fits a straight line, or a parabola, through their values, giving more weight to the closer ones. This fit gives smooth shape functions with no mesh. The price is that the shape functions are not simple polynomials, so they are hard to integrate exactly. Also, the value of the solution at a point is not exactly the number stored at that point, so the fixed values at the boundary need extra equations.

The problem

Input. An interval [a,b][a, b] (the code is one dimensional, the method is not), a load ff, Dirichlet values u(a)=uau(a) = u_a and u(b)=ubu(b) = u_b, nodes a=x1<…<xn=ba = x_1 < \ldots < x_n = b with support radii dId_I, a polynomial basis p(x)p(x) of size mm (p=(1,x)p = (1, x) or (1,x,x2)(1, x, x^2)), and background cells with a Gauss rule.

Output. Coefficients aIa_I such that uh(x)=∑IϕI(x) aIu_h(x) = \sum_I \phi_I(x)\,a_I approximates the solution of −u′′=f-u'' = f, u(a)=uau(a) = u_a, u(b)=ubu(b) = u_b, together with the multipliers λ\lambda at the two ends.

The MLS shape functions. At a point xx, minimize ∑IwI(x) (p(xI)⊤c−aI)2\sum_I w_I(x)\,(p(x_I)^\top c - a_I)^2 over c∈Rmc \in \mathbb R^m and set uh(x)=p(x)⊤c(x)u_h(x) = p(x)^\top c(x). With the moment matrix A(x)=∑IwI(x) p(xI) p(xI)⊤A(x) = \sum_I w_I(x)\,p(x_I)\,p(x_I)^\top this gives

ϕI(x)=p(x)⊤A(x)−1 wI(x) p(xI),ϕI′=γ′⊤wI p(xI)+γ⊤wI′ p(xI),\phi_I(x) = p(x)^\top A(x)^{-1}\,w_I(x)\,p(x_I), \qquad \phi_I' = \gamma'^\top w_I\,p(x_I) + \gamma^\top w_I'\,p(x_I),

where γ=A−1p\gamma = A^{-1} p and γ′=A−1(p′−A′γ)\gamma' = A^{-1}(p' - A'\gamma). A(x)A(x) is nonsingular when at least mm supports cover xx with nodes in general position. The weight here is the cubic spline w(r)=23−4r2+4r3w(r) = \tfrac23 - 4r^2 + 4r^3 for r≤12r \le \tfrac12, w(r)=43−4r+4r2−43r3w(r) = \tfrac43 - 4r + 4r^2 - \tfrac43 r^3 for 12<r<1\tfrac12 < r < 1, and 00 after, with r=∣x−xI∣/dIr = |x - x_I|/d_I. It is twice continuously differentiable.

The discrete problem. Find (a,λ)(a, \lambda) with

(KGG⊤0)(aλ)=(Fg),KIJ=∫abϕI′ϕJ′ dx,FI=∫abϕIf dx,GIb=ϕI(xb),\begin{pmatrix} K & G \\ G^\top & 0 \end{pmatrix}\begin{pmatrix} a \\ \lambda \end{pmatrix} = \begin{pmatrix} F \\ g \end{pmatrix}, \qquad K_{IJ} = \int_a^b \phi_I'\phi_J'\,dx, \quad F_I = \int_a^b \phi_I f\,dx, \quad G_{Ib} = \phi_I(x_b),

where xb∈{a,b}x_b \in \{a, b\} and g=(ua,ub)g = (u_a, u_b).

The algorithm

  1. EFG-1D(nodes x_I, radii d_I, basis p, cells, f, u_a, u_b)
  2. 1for each Gauss point (x_Q, w_Q) of the background cells
  3. 2find the nodes with |x_Q - x_I| < d_I; compute phi_I(x_Q) and phi_I'(x_Q) by MLS
  4. 3f_Q <- f(x_Q)
  5. 4K[I, J] <- K[I, J] + w_Q phi_I' phi_J'; F[I] <- F[I] + w_Q phi_I f_Q
  6. 5for each end x_b in {a, b}: G[I, b] <- phi_I(x_b) for the nodes that cover x_b
  7. 6solve the saddle point system [K G; G^T 0] [a; lambda] = [F; g]
  8. 7u_h(x) <- sum over the nodes that cover x of phi_I(x) a_I
  9. 8return u_h, u_h' and lambda

The multipliers are the boundary fluxes: λa=u′(a)\lambda_a = u'(a) and λb=−u′(b)\lambda_b = -u'(b), up to the discretization error.

Example

Shape functions at a node. Take the nodes 0,0.1,…,10, 0.1, \ldots, 1, the linear basis and dI=0.25d_I = 0.25. At x=0.5x = 0.5 the nodes 0.3,…,0.70.3, \ldots, 0.7 have r=0.8,0.4,0,0.4,0.8r = 0.8, 0.4, 0, 0.4, 0.8, and the weights are 4375,106375,250375,106375,4375\tfrac{4}{375}, \tfrac{106}{375}, \tfrac{250}{375}, \tfrac{106}{375}, \tfrac{4}{375}. The neighbourhood is symmetric about xx, so in coordinates centred at xx the moment matrix is diagonal and ϕI=wI/∑JwJ\phi_I = w_I/\sum_J w_J:

ϕ=(2235,53235,2547,53235,2235)≈(0.0085,0.2255,0.5319,0.2255,0.0085).\phi = \big(\tfrac{2}{235}, \tfrac{53}{235}, \tfrac{25}{47}, \tfrac{53}{235}, \tfrac{2}{235}\big) \approx (0.0085, 0.2255, 0.5319, 0.2255, 0.0085).

So ϕ6(x6)=0.53\phi_6(x_6) = 0.53, not 1: the coefficient a6a_6 is not the value of uhu_h at the node.

The patch test and the quadrature. With the same nodes, f=0f = 0, u(0)=1u(0) = 1 and u(1)=3u(1) = 3, the exact solution 1+2x1 + 2x is in the span of the shape functions. The result depends on the quadrature. With 40 cells of width h/4h/4, whose ends are the breakpoints of the weights, and 8 Gauss points, the error is 6×10−156 \times 10^{-15}, the coefficients are the nodal values 1,1.2,1.4,…1, 1.2, 1.4, \ldots and λ=(2,−2)\lambda = (2, -2). With one cell per node interval and 3 Gauss points, the error is 4.9×10−54.9 \times 10^{-5} in uu and 1.5×10−31.5 \times 10^{-3} in u′u', because the rational shape functions are not integrated exactly. With nodal integration (trapezoid weights at the nodes) the error is 7.5×10−37.5 \times 10^{-3} in uu and 0.230.23 in u′u'.

Convergence. For u=sin⁡πxu = \sin \pi x with uniform nodes, 4 cells per node interval and 5 Gauss points, the errors are:

nodes linear basis, L2L^2 linear basis, H1H^1 quadratic basis, L2L^2 quadratic basis, H1H^1
11 1.22×10−41.22 \times 10^{-4} 5.61×10−35.61 \times 10^{-3} 8.26×10−58.26 \times 10^{-5} 4.36×10−34.36 \times 10^{-3}
21 1.65×10−51.65 \times 10^{-5} 1.96×10−31.96 \times 10^{-3} 1.29×10−51.29 \times 10^{-5} 1.52×10−31.52 \times 10^{-3}
41 3.38×10−63.38 \times 10^{-6} 9.12×10−49.12 \times 10^{-4} 1.79×10−61.79 \times 10^{-6} 4.37×10−44.37 \times 10^{-4}
81 8.17×10−78.17 \times 10^{-7} 4.52×10−44.52 \times 10^{-4} 2.33×10−72.33 \times 10^{-7} 1.16×10−41.16 \times 10^{-4}

The last observed orders are 2.052.05 and 1.011.01 for the linear basis and 2.942.94 and 1.911.91 for the quadratic basis (radius 3.5h3.5h), as for finite elements of the same degree.

Correctness

The proofs are in the correctness proof.

  • Reproduction (theorem). If A(x)A(x) is nonsingular, ∑IϕI(x) q(xI)=q(x)\sum_I \phi_I(x)\,q(x_I) = q(x) for every polynomial qq in the span of pp, and the same holds for the derivatives. In particular the ϕI\phi_I form a partition of unity.
  • Linear exactness needs exact integration (theorem). If the quadrature integrates ϕI′ q′\phi_I'\,q' exactly for every II and every linear qq (the integration constraint), the discrete solution is exact for a linear exact solution. This holds for the background cells of the fine run above to rounding error, and fails for nodal integration.
  • The constraints hold exactly (theorem). The last rows of line L6 are uh(a)=uau_h(a) = u_a and uh(b)=ubu_h(b) = u_b.
  • Convergence (cited, and measured). With exact integration and a regular node distribution the method converges like finite elements of the degree of the basis (Belytschko, Lu and Gu 1994, and the MLS approximation theory). The rates above are measurements.
Proof: MLS shape functions reproduce their basis, and EFG is exact for linear solutions under the integration constraintpartial

Setting. Nodes x1,…,xnx_1, \ldots, x_n in [a,b][a, b], weights wI≥0w_I \ge 0 that are continuously differentiable with wI(x)>0w_I(x) > 0 exactly when ∣x−xI∣<dI|x - x_I| < d_I, a basis p(x)=(p1(x),…,pm(x))p(x) = (p_1(x), \ldots, p_m(x)) of polynomials, A(x)=∑IwI(x) p(xI)p(xI)⊤A(x) = \sum_I w_I(x)\,p(x_I)p(x_I)^\top and ϕI(x)=p(x)⊤A(x)−1wI(x) p(xI)\phi_I(x) = p(x)^\top A(x)^{-1} w_I(x)\,p(x_I). Let UU be the set of points where A(x)A(x) is nonsingular. The status is partial because the convergence rates are cited from the literature and measured, not proved here (Remark 2).

Lemma 1 (the MLS fit). For x∈Ux \in U and any data aIa_I, the minimizer of J(c)=∑IwI(x) (p(xI)⊤c−aI)2J(c) = \sum_I w_I(x)\,(p(x_I)^\top c - a_I)^2 is unique, and p(x)⊤c(x)=∑IϕI(x) aIp(x)^\top c(x) = \sum_I \phi_I(x)\,a_I.

Proof. JJ is a convex quadratic in cc with Hessian 2A(x)2A(x). If A(x)A(x) is nonsingular it is positive definite, since c⊤Ac=∑IwI(p(xI)⊤c)2≥0c^\top A c = \sum_I w_I (p(x_I)^\top c)^2 \ge 0. So the unique minimizer solves A(x) c=∑IwI(x) p(xI) aIA(x)\,c = \sum_I w_I(x)\,p(x_I)\,a_I, and p(x)⊤c(x)=∑Ip(x)⊤A−1wI p(xI) aIp(x)^\top c(x) = \sum_I p(x)^\top A^{-1} w_I\,p(x_I)\,a_I. □\square

Theorem 1 (reproduction). For x∈Ux \in U and every q=p⊤βq = p^\top \beta in the span of the basis, ∑IϕI(x) q(xI)=q(x)\sum_I \phi_I(x)\,q(x_I) = q(x). On the open set UU the ϕI\phi_I are continuously differentiable and ∑IϕI′(x) q(xI)=q′(x)\sum_I \phi_I'(x)\,q(x_I) = q'(x).

Proof. Take aI=q(xI)=p(xI)⊤βa_I = q(x_I) = p(x_I)^\top\beta. Then J(β)=0J(\beta) = 0, which is the minimum, so c(x)=βc(x) = \beta by uniqueness and the fit is p(x)⊤β=q(x)p(x)^\top\beta = q(x). The entries of A(x)A(x) are continuously differentiable, and the inverse of a nonsingular matrix is a smooth function of its entries, so each ϕI\phi_I is continuously differentiable on UU. The identity ∑IϕI(x) q(xI)=q(x)\sum_I \phi_I(x)\,q(x_I) = q(x) holds on the open set UU, so its derivative holds too. □\square

With q=1q = 1 this gives ∑IϕI=1\sum_I \phi_I = 1, a partition of unity, and ∑IϕI′=0\sum_I \phi_I' = 0. The formula for ϕI′\phi_I' on the page is the product rule with (A−1)′=−A−1A′A−1(A^{-1})' = -A^{-1}A'A^{-1}: with γ=A−1p\gamma = A^{-1}p, γ′=A−1p′−A−1A′A−1p=A−1(p′−A′γ)\gamma' = A^{-1}p' - A^{-1}A'A^{-1}p = A^{-1}(p' - A'\gamma), and ϕI=wI γ⊤p(xI)\phi_I = w_I\,\gamma^\top p(x_I).

Theorem 2 (the constraints). Any solution of the system of line L6 satisfies uh(a)=uau_h(a) = u_a and uh(b)=ubu_h(b) = u_b.

Proof. The last two rows of the system are ∑IGIb aI=gb\sum_I G_{Ib}\,a_I = g_b, and GIb=ϕI(xb)G_{Ib} = \phi_I(x_b), so they read uh(xb)=gbu_h(x_b) = g_b. □\square

Theorem 3 (linear exactness under the integration constraint). Let the basis contain 11 and xx, let [a,b]⊂U[a, b] \subset U, and let f=0f = 0 and u∗(x)=α+c xu^*(x) = \alpha + c\,x with ua=u∗(a)u_a = u^*(a) and ub=u∗(b)u_b = u^*(b). Suppose the quadrature QQ of line L1 satisfies the integration constraint

Q[ϕI′]=∑QwQ ϕI′(xQ)=ϕI(b)−ϕI(a)for every I.Q[\phi_I'] = \sum_Q w_Q\,\phi_I'(x_Q) = \phi_I(b) - \phi_I(a) \quad \text{for every } I.

If the matrix of line L6 is nonsingular, its solution is aI=u∗(xI)a_I = u^*(x_I) and λ=(c,−c)\lambda = (c, -c), and then uh=u∗u_h = u^* on [a,b][a, b].

Proof. Put aI∗=u∗(xI)a^*_I = u^*(x_I) and λ∗=(c,−c)\lambda^* = (c, -c). By Theorem 1, ∑JϕJ′(x) aJ∗=c\sum_J \phi_J'(x)\,a^*_J = c for every xx, so row II of the first block is

∑JKIJ aJ∗+ϕI(a) c−ϕI(b) c=∑QwQ ϕI′(xQ) c+c (ϕI(a)−ϕI(b))=0=FI,\sum_J K_{IJ}\,a^*_J + \phi_I(a)\,c - \phi_I(b)\,c = \sum_Q w_Q\,\phi_I'(x_Q)\,c + c\,(\phi_I(a) - \phi_I(b)) = 0 = F_I,

by the integration constraint and f=0f = 0. The last rows hold by Theorem 1: ∑IϕI(xb) aI∗=u∗(xb)=gb\sum_I \phi_I(x_b)\,a^*_I = u^*(x_b) = g_b. So (a∗,λ∗)(a^*, \lambda^*) solves the system, and it is the only solution because the matrix is nonsingular. Finally uh(x)=∑IϕI(x) u∗(xI)=u∗(x)u_h(x) = \sum_I \phi_I(x)\,u^*(x_I) = u^*(x) by Theorem 1. □\square

Remark 1 (when the constraint holds). The exact integral satisfies the constraint by the fundamental theorem of calculus, so the constraint asks the quadrature to integrate each ϕI′\phi_I' exactly. The ϕI\phi_I are rational on each interval between breakpoints xI±dIx_I \pm d_I and xI±dI/2x_I \pm d_I/2, so a Gauss rule on cells whose ends are these breakpoints converges very fast but is not exact. The reference test measures a patch test error of 6×10−156 \times 10^{-15} with 8 points on such cells, 4.9×10−54.9 \times 10^{-5} with 3 points on cells of one node interval, and 7.5×10−37.5 \times 10^{-3} with nodal integration, which violates the constraint. If the constraint fails, the same computation shows that the residual of (a∗,λ∗)(a^*, \lambda^*) in row II is c (Q[ϕI′]−ϕI(b)+ϕI(a))c\,(Q[\phi_I'] - \phi_I(b) + \phi_I(a)), so the error is proportional to the defect of the constraint.

Remark 2 (convergence, cited). For exact integration and a quasi uniform node set with supports proportional to the spacing, the MLS approximation with a basis of degree kk has interpolation errors O(hk+1)O(h^{k+1}) in L2L^2 and O(hk)O(h^k) in H1H^1, and the Galerkin method with multipliers inherits these rates when the multiplier space is stable. This is the standard result of the meshfree literature (Belytschko, Lu and Gu 1994, and Liu 2003). The reference tests measure the rates 22 and 11 for k=1k = 1 and close to 33 and 22 for k=2k = 2.

Complexity

In the real-RAM model, each of the gg quadrature points finds its kk neighbours (with a bucket grid, in constant expected time per neighbour), builds AA and A′A' in Θ(km2)\Theta(k m^2), solves two m×mm \times m systems in Θ(m3)\Theta(m^3) and adds k2k^2 entries to KK. So assembly costs Θ(g(km2+m3+k2))\Theta(g(k m^2 + m^3 + k^2)). The matrix KK has about nkn k nonzeros. A banded solve in one dimension costs Θ(nk2)\Theta(n k^2). The reference code uses dense Gaussian elimination and is meant only for small examples. Compared with finite elements, kk is larger (5 here, against 2 for linear elements in one dimension) and gg must be larger for accurate integration, so EFG costs several times more per unknown.

Properties

  • Smooth shape functions. The ϕI\phi_I have the smoothness of the weight, here C2C^2, so derivatives and stresses are continuous without any post-processing.
  • No Kronecker delta. The coefficients are not the nodal values. Essential conditions need multipliers, a penalty, Nitsche's method, or a coupling with finite elements at the boundary.
  • Rational, not polynomial. The shape functions are ratios of piecewise polynomials, so no Gauss rule integrates them exactly unless the cells match the breakpoints of the supports, and then only approximately.
  • Refinement by adding nodes. New nodes need no connectivity. Only the supports must keep covering every point with enough nodes for AA to be nonsingular.

Variants and improvements

  • Penalty and Nitsche boundary conditions. Replace the multipliers by β∫Γ(uh−g)v\beta \int_\Gamma (u_h - g)v with a large β\beta, or by Nitsche's consistent terms, which keep the system positive definite.
  • Stabilized conforming nodal integration (Chen and coauthors 2001). Integrate smoothed strains over cells around each node. It satisfies the integration constraint, so the method passes the linear patch test with one point per node.
  • Reproducing kernel particle method. A closely related construction of the shape functions as a corrected kernel. For the same basis and weights it gives the same functions as MLS.
  • Enrichment. Add singular or discontinuous functions to the basis pp, or cut the supports with a visibility criterion at a crack, for fracture mechanics.
  • Coupling with finite elements. Use EFG only where the mesh would distort, and finite elements elsewhere, with blended shape functions in between.

When to use it

Use it when a mesh is the main difficulty: crack propagation, large deformation and fragmentation, and adaptive refinement with nodes added or removed. For problems on a fixed geometry with small deformations, finite elements are cheaper and simpler, and they satisfy the boundary conditions directly. Smoothed particle hydrodynamics is the related collocation method for fluids, and radial basis function interpolation is a global meshless fit with no moving weights.

Pitfalls

  • Too few nodes in a support. If fewer than mm supports cover a point, or the covering nodes are collinear in 2D, A(x)A(x) is singular. Choose dId_I about 22 to 44 times the node spacing for the linear basis.
  • Weak quadrature. Few Gauss points per cell, or cells that cut across the supports, give an integration error that can dominate the discretization error and break the patch test, as the example shows.
  • Nodal integration. It is cheap, but it fails the patch test and allows spurious zero energy modes unless it is stabilized.
  • Treating coefficients as nodal values. The value at node II is uh(xI)=∑JϕJ(xI) aJu_h(x_I) = \sum_J \phi_J(x_I)\,a_J, not aIa_I. Plotting aIa_I gives a wrong picture.
  • Large penalty parameters. A penalty makes the system ill conditioned, while a small one does not enforce the boundary condition. Multipliers or Nitsche's method avoid the choice.

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.

element_free_galerkin_method.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/element-free-galerkin-method/. The authors are listed in prov/MYQ8NE.jsonl.

"""Element-free Galerkin method in one dimension.

Solves -u'' = f on [a, b] with u(a) = ua and u(b) = ub. The shape functions
are moving least squares (MLS) functions built from scattered nodes with a
polynomial basis of degree 1 or 2 and the cubic spline weight. They do not
satisfy phi_I(x_J) = delta_IJ, so the boundary conditions are imposed with
Lagrange multipliers. Integration uses Gauss points on background cells.
"""

import math

import scimat


def gauss_legendre(n):
    """Return the n Gauss-Legendre points and weights on [-1, 1]."""
    pts, wts = [], []
    for k in range(n):
        x = math.cos(math.pi * (k + 0.75) / (n + 0.5))
        for _ in range(100):
            p0, p1 = 1.0, x
            for j in range(2, n + 1):
                p0, p1 = p1, ((2 * j - 1) * x * p1 - (j - 1) * p0) / j
            dp = n * (x * p1 - p0) / (x * x - 1)
            dx = p1 / dp
            x -= dx
            if abs(dx) < 1e-16:
                break
        pts.append(x)
        wts.append(2 / ((1 - x * x) * dp * dp))
    return pts, wts


def cubic_spline_weight(r):
    """Return (w, dw/dr) of the cubic spline weight for r = |x - x_I| / d_I >= 0."""
    if r <= 0.5:
        return 2 / 3 - 4 * r * r + 4 * r ** 3, -8 * r + 12 * r * r
    if r < 1:
        return 4 / 3 - 4 * r + 4 * r * r - 4 / 3 * r ** 3, -4 + 8 * r - 4 * r * r
    return 0.0, 0.0


def _basis(x, degree):
    if degree == 1:
        return [1.0, x], [0.0, 1.0]
    return [1.0, x, x * x], [0.0, 1.0, 2 * x]


def mls_shape(x, nodes, radii, degree=1):
    """Return (idx, phi, dphi): the nodes whose support covers x and their MLS values and derivatives."""
    idx, w, dw = [], [], []
    for i, (xi, di) in enumerate(zip(nodes, radii)):
        r = abs(x - xi) / di
        if r < 1:
            wi, dwr = cubic_spline_weight(r)
            sign = 1.0 if x >= xi else -1.0
            idx.append(i)
            w.append(wi)
            dw.append(dwr * sign / di)
    m = degree + 1
    p, dp = _basis(x, degree)
    a = scimat.zeros(m)
    da = scimat.zeros(m)
    pis = [_basis(nodes[i], degree)[0] for i in idx]
    for wi, dwi, pi in zip(w, dw, pis):
        for r in range(m):
            for c in range(m):
                a[r][c] += wi * pi[r] * pi[c]
                da[r][c] += dwi * pi[r] * pi[c]
    # gamma = A^{-1} p, so phi_I = gamma . (w_I p_I); dgamma = A^{-1} (dp - dA gamma)
    gamma = scimat.solve(a, p)
    dgamma = scimat.solve(a, scimat.sub(dp, scimat.matvec(da, gamma)))
    phi = [wi * scimat.dot(gamma, pi) for wi, pi in zip(w, pis)]
    dphi = [dwi * scimat.dot(gamma, pi) + wi * scimat.dot(dgamma, pi) for wi, dwi, pi in zip(w, dw, pis)]
    return idx, phi, dphi


def quadrature_points(a, b, ncells, order):
    """Return Gauss points and weights on ncells equal background cells of [a, b]."""
    gp, gw = gauss_legendre(order)
    h = (b - a) / ncells
    out = []
    for c in range(ncells):
        x0 = a + c * h
        for t, wt in zip(gp, gw):
            out.append((x0 + (t + 1) * h / 2, wt * h / 2))
    return out


class EFG1D:
    """An EFG discretization of -u'' = f on [nodes[0], nodes[-1]] with Dirichlet ends."""

    def __init__(self, nodes, support, f, ua, ub, ncells=None, order=3, degree=1, quadrature=None):
        self.nodes = list(nodes)
        n = len(self.nodes)
        self.radii = [support] * n if not isinstance(support, list) else support
        self.degree = degree
        a, b = self.nodes[0], self.nodes[-1]
        if quadrature is None:
            quadrature = quadrature_points(a, b, ncells or (n - 1), order)
        k = scimat.zeros(n)
        rhs = [0.0] * n
        for xq, wq in quadrature:  # @line L1
            idx, phi, dphi = mls_shape(xq, self.nodes, self.radii, degree)  # @line L2
            fq = f(xq)  # @line L3
            for ii, i in enumerate(idx):
                rhs[i] += wq * phi[ii] * fq
                for jj, j in enumerate(idx):
                    k[i][j] += wq * dphi[ii] * dphi[jj]  # @line L4
        # Lagrange multipliers for u(a) = ua and u(b) = ub
        big = [row + [0.0, 0.0] for row in k] + [[0.0] * (n + 2) for _ in range(2)]
        for col, (xb, g) in enumerate(((a, ua), (b, ub))):
            idx, phi, _ = mls_shape(xb, self.nodes, self.radii, degree)
            for ii, i in enumerate(idx):
                big[i][n + col] = phi[ii]  # @line L5
                big[n + col][i] = phi[ii]
            rhs.append(g)
        sol = scimat.solve(big, rhs)  # @line L6
        self.coef = sol[:n]
        self.multipliers = sol[n:]
        self.stiffness = k

    def value(self, x):
        """Return (u_h(x), u_h'(x))."""
        idx, phi, dphi = mls_shape(x, self.nodes, self.radii, self.degree)
        u = sum(p * self.coef[i] for p, i in zip(phi, idx))  # @line L7
        du = sum(p * self.coef[i] for p, i in zip(dphi, idx))
        return u, du  # @line L8


def nodal_quadrature(nodes):
    """Return the trapezoid weights at the nodes, the simplest nodal integration."""
    out = []
    for i, x in enumerate(nodes):
        left = nodes[i] - nodes[i - 1] if i > 0 else 0.0
        right = nodes[i + 1] - nodes[i] if i + 1 < len(nodes) else 0.0
        out.append((x, (left + right) / 2))
    return out


def errors(model, u, du, a, b, ncells=64, order=5):
    """Return the L2 error and the H1 seminorm error of model against u and du."""
    e0 = e1 = 0.0
    for xq, wq in quadrature_points(a, b, ncells, order):
        uh, duh = model.value(xq)
        e0 += wq * (uh - u(xq)) ** 2
        e1 += wq * (duh - du(xq)) ** 2
    return math.sqrt(e0), math.sqrt(e1)
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_element_free_galerkin_method.py 139 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/element-free-galerkin-method/. The authors are listed in prov/MYQ8NE.jsonl.

import math
import random

import scimat
from element_free_galerkin_method import (
    EFG1D,
    cubic_spline_weight,
    errors,
    gauss_legendre,
    mls_shape,
    nodal_quadrature,
)

NODES = [i / 10 for i in range(11)]


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


def du_sin(x):
    return math.pi * math.cos(math.pi * x)


def f_sin(x):
    return math.pi ** 2 * math.sin(math.pi * x)


def test_gauss_legendre_is_exact_for_degree_2n_minus_1():
    for n in (2, 3, 5, 8):
        pts, wts = gauss_legendre(n)
        for k in range(2 * n):
            exact = 0.0 if k % 2 else 2 / (k + 1)
            assert abs(sum(w * x ** k for x, w in zip(pts, wts)) - exact) < 1e-13


def test_cubic_spline_weight_is_c2_with_compact_support():
    h = 1e-6
    for r in (0.5, 1.0):
        wl, dl = cubic_spline_weight(r - h)
        wr, dr = cubic_spline_weight(r + h)
        assert abs(wl - wr) < 1e-5 and abs(dl - dr) < 1e-5
    assert cubic_spline_weight(1.0) == (0.0, 0.0)
    assert abs(cubic_spline_weight(0.0)[0] - 2 / 3) < 1e-15


def test_mls_reproduces_linear_and_quadratic_fields():
    rng = random.Random(4)
    nodes = sorted([0.0, 1.0] + [rng.random() for _ in range(15)])
    for degree in (1, 2):
        for _ in range(30):
            x = rng.random()
            idx, phi, dphi = mls_shape(x, nodes, [0.3] * len(nodes), degree)
            for k in range(degree + 1):
                assert abs(sum(p * nodes[i] ** k for p, i in zip(phi, idx)) - x ** k) < 1e-11
                d_exact = k * x ** (k - 1) if k else 0.0
                assert abs(sum(p * nodes[i] ** k for p, i in zip(dphi, idx)) - d_exact) < 1e-9


def test_derivatives_match_finite_differences():
    radii = [0.25] * len(NODES)
    h = 1e-6
    for x in (0.137, 0.5, 0.71):
        idx, _, dphi = mls_shape(x, NODES, radii)
        ip, pp, _ = mls_shape(x + h, NODES, radii)
        im, pm, _ = mls_shape(x - h, NODES, radii)
        assert idx == ip == im
        for k in range(len(idx)):
            assert abs((pp[k] - pm[k]) / (2 * h) - dphi[k]) < 1e-6


def test_no_kronecker_delta_property():
    # at the node 0.5 the five supports overlap; with a symmetric neighbourhood phi_I = w_I / sum w
    idx, phi, _ = mls_shape(0.5, NODES, [0.25] * len(NODES))
    assert idx == [3, 4, 5, 6, 7]
    expected = [2 / 235, 53 / 235, 25 / 47, 53 / 235, 2 / 235]
    assert all(abs(p - e) < 1e-14 for p, e in zip(phi, expected))


def test_patch_test_depends_on_the_quadrature():
    exact = [(1 + 2 * x, 2.0) for x in [0.05 * k for k in range(21)]]

    def worst(model):
        return max(abs(model.value(0.05 * k)[0] - exact[k][0]) for k in range(21))

    # cells of width h/4 align with the breakpoints of the weights: passes to rounding
    fine = EFG1D(NODES, 0.25, lambda x: 0.0, 1.0, 3.0, ncells=40, order=8)
    assert worst(fine) < 1e-13
    # one cell per node interval with 3 Gauss points: an error from the quadrature only
    coarse = EFG1D(NODES, 0.25, lambda x: 0.0, 1.0, 3.0, ncells=10, order=3)
    assert 1e-6 < worst(coarse) < 1e-3
    # nodal integration fails clearly
    nodal = EFG1D(NODES, 0.25, lambda x: 0.0, 1.0, 3.0, quadrature=nodal_quadrature(NODES))
    assert worst(nodal) > 1e-3


def test_boundary_conditions_hold_through_the_multipliers():
    model = EFG1D(NODES, 0.25, f_sin, 0.5, -1.0, ncells=40, order=5)
    assert abs(model.value(0.0)[0] - 0.5) < 1e-12
    assert abs(model.value(1.0)[0] + 1.0) < 1e-12
    # the coefficients are not the nodal values
    assert abs(model.coef[0] - 0.5) > 1e-4


def test_convergence_rates_linear_basis():
    errs = []
    for n in (11, 21, 41, 81):
        h = 1 / (n - 1)
        nodes = [i * h for i in range(n)]
        model = EFG1D(nodes, 2.5 * h, f_sin, 0.0, 0.0, ncells=4 * (n - 1), order=5)
        errs.append(errors(model, u_sin, du_sin, 0.0, 1.0))
    r0 = scimat.observed_order([e[0] for e in errs])
    r1 = scimat.observed_order([e[1] for e in errs])
    assert r0[-1] > 1.9 and abs(r1[-1] - 1) < 0.15


def test_convergence_rates_quadratic_basis():
    errs = []
    for n in (11, 21, 41):
        h = 1 / (n - 1)
        nodes = [i * h for i in range(n)]
        model = EFG1D(nodes, 3.5 * h, f_sin, 0.0, 0.0, ncells=4 * (n - 1), order=5, degree=2)
        errs.append(errors(model, u_sin, du_sin, 0.0, 1.0))
    r0 = scimat.observed_order([e[0] for e in errs])
    r1 = scimat.observed_order([e[1] for e in errs])
    assert r0[-1] > 2.6 and r1[-1] > 1.7


def test_irregular_nodes():
    rng = random.Random(7)
    n = 21
    h = 1 / (n - 1)
    nodes = [0.0] + [i * h + rng.uniform(-0.3, 0.3) * h for i in range(1, n - 1)] + [1.0]
    model = EFG1D(nodes, 3.0 * h, f_sin, 0.0, 0.0, ncells=80, order=6)
    e0, e1 = errors(model, u_sin, du_sin, 0.0, 1.0)
    assert e0 < 1e-3 and e1 < 2e-2

History

Lancaster and Salkauskas in 1981 studied moving least squares for fitting surfaces to scattered data. Nayroles, Touzot and Villon in 1992 used MLS functions in a Galerkin method, the diffuse element method, but kept only part of the derivatives. Belytschko, Lu and Gu in 1994 used the full derivatives, imposed the boundary conditions with Lagrange multipliers and integrated on background cells, and named the method element-free Galerkin. Dolbow and Belytschko in 1999 studied the quadrature error, and Chen and coauthors in 2001 gave a nodal integration that meets the integration constraint.

References

  1. T. Belytschko, Y. Y. Lu and L. Gu, Element-free Galerkin methods, International Journal for Numerical Methods in Engineering 37(2) (1994) 229-256, the MLS shape functions with their derivatives, the Lagrange multipliers for essential boundary conditions and the background cell quadrature
  2. P. Lancaster and K. Salkauskas, Surfaces generated by moving least squares methods, Mathematics of Computation 37(155) (1981) 141-158, the moving least squares approximation and its reproduction of the basis polynomials
  3. B. Nayroles, G. Touzot and P. Villon, Generalizing the finite element method, diffuse approximation and diffuse elements, Computational Mechanics 10(5) (1992) 307-318, the diffuse element method, a Galerkin method with MLS functions and approximate derivatives
  4. J. Dolbow and T. Belytschko, Numerical integration of the Galerkin weak form in meshfree methods, Computational Mechanics 23(3) (1999) 219-230, the quadrature error of background cells that do not match the supports, and its effect on the patch test
  5. J. S. Chen, C. T. Wu, S. Yoon and Y. You, A stabilized conforming nodal integration for Galerkin mesh-free methods, International Journal for Numerical Methods in Engineering 50(2) (2001) 435-466, the integration constraint for linear exactness and the smoothed nodal integration that meets it
  6. G. R. Liu, Mesh Free Methods, Moving beyond the Finite Element Method, CRC Press, 2003, the chapters on MLS shape functions and the EFG method

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